CREATE TABLE GlobalCustomPrice (
 pairId VARCHAR(16) NOT NULL PRIMARY KEY,
 rate DECIMAL(9, 4) NOT NULL,
 active BOOLEAN NOT NULL DEFAULT false,
 updatedBy VARCHAR(36) NOT NULL,
 updatedAt DATETIME(3) NOT NULL
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- Preserve the former settings. An active setting takes priority over an inactive draft.
INSERT INTO GlobalCustomPrice (pairId, rate, active, updatedBy, updatedAt)
SELECT pairId, rate, active, updatedBy, updatedAt
FROM (
 SELECT pairId, rate, active, updatedBy, updatedAt,
  ROW_NUMBER() OVER (PARTITION BY pairId ORDER BY active DESC, updatedAt DESC, marketType DESC) AS preference
 FROM CustomPrice
) ranked
WHERE preference = 1;
