Skip to content

Instantly share code, notes, and snippets.

@tathamoddie
Created August 5, 2010 01:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tathamoddie/509087 to your computer and use it in GitHub Desktop.
Save tathamoddie/509087 to your computer and use it in GitHub Desktop.
Swap two values in SQL that have a unique constraint
SET NOCOUNT ON
CREATE TABLE Foo
(
Id int primary key,
SortIndex int unique
)
GO
INSERT INTO Foo VALUES (1, 10)
INSERT INTO Foo VALUES (2, 20)
INSERT INTO Foo VALUES (3, 30)
INSERT INTO Foo VALUES (4, 40)
SELECT * FROM Foo ORDER BY SortIndex
UPDATE Foo
SET SortIndex = CASE SortIndex
WHEN 30 THEN 20
WHEN 20 THEN 30
END
WHERE SortIndex IN (20, 30)
SELECT * FROM Foo ORDER BY SortIndex
DROP TABLE Foo
--Output:
-- Id SortIndex
-- ----------- -----------
-- 1 10
-- 2 20
-- 3 30
-- 4 40
-- Id SortIndex
-- ----------- -----------
-- 1 10
-- 3 20
-- 2 30
-- 4 40
@jngbng
Copy link

jngbng commented Nov 24, 2017

does not work on mysql 5.7.

@mjasnikovs
Copy link

Dose not work in PostgreSQL 9 "error: duplicate key value violates unique constraint"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment