Skip to content

Instantly share code, notes, and snippets.

@bennadel
Created February 1, 2024 12:10
Conditionally Updating Columns When Using ON DUPLICATE KEY UPDATE In MySQL
CREATE TABLE `email_verification` (
`email` varchar(255) NOT NULL,
`textCode` varchar(50) NOT NULL,
`updatedAt` datetime NOT NULL,
PRIMARY KEY (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
SET @email = 'ben@bennadel.com';
SET @textCode = 'ok';
INSERT INTO
email_verification
SET
email = @email,
textCode = @textCode,
updatedAt = UTC_TIMESTAMP()
ON DUPLICATE KEY UPDATE
textCode = VALUES( textCode ),
updatedAt = VALUES( updatedAt )
;
SET @email = 'ben@bennadel.com';
SET @textCode = 'ok';
INSERT INTO
email_verification
SET
email = @email,
textCode = @textCode,
updatedAt = UTC_TIMESTAMP()
ON DUPLICATE KEY UPDATE
textCode = IF(
( textCode = 'suppressed' ),
textCode, -- Return the existing value (suppressed)
VALUES( textCode ) -- Return the new value.
),
updatedAt = VALUES( updatedAt )
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment