Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres: UPDATE a boolean column that sets all other booleans in that column to false

Tags:

sql

postgresql

I'm wondering if I can do this in one query

Usecase: twitter pinned tweet. You can have at most one pinned tweet and setting a new pinned tweet, unset all the other previously pinned tweets.

Any ideas?

like image 329
Matt Avatar asked Oct 07 '16 05:10

Matt


1 Answers

UPDATE tweets
SET pinned = NOT pinned
WHERE id = 1234 OR pinned = TRUE;

Or to be extra cautious

WHERE (id = 1234 AND pinned = FALSE) OR (pinned = TRUE AND id <> 1234)
like image 126
Jakub Kania Avatar answered Oct 07 '22 10:10

Jakub Kania