tags:

views:

67

answers:

3

I have a database table with a column named featured which is used to highlight featured content on a page. Currently, I'm using two SQL statements to toggle the featured rows on/off like so:

-- Reset everything to non-featured
UPDATE tbl SET featured = '0'; 

-- Now set the selected rows as featured.
UPDATE tbl SET featured = '1' WHERE id IN (4, 10, 21);  

Is it possible to combine both of these into one statement?

+3  A: 

Use:

UPDATE tbl
   SET featured = CASE 
                    WHEN id IN (4, 10, 21) THEN '1'
                    ELSE '0'
                  END;
OMG Ponies
A: 

Yes, you can combine both of these into one statement.

John
While that may literally answer the question asked, I don't believe this is a helpful response. The implied question is "how can a single statement be constructed to do this?"
ddc0660
@jigs: Nobody likes a smart alec.
Bill Karwin
UPDATE Activity SET Activity.Charges = 10WHERE (Activity.[Activity ID]) In (2,3,4);This is a example which is working.
John
sorry, i didnt get your question, the other ans is right
John
@ddc0660: maybe jigs have acquired bad habits from becoming a programmer heheh :D http://stackoverflow.com/questions/164432/what-real-life-bad-habits-has-programming-given-you/164446#164446
Michael Buen
+3  A: 

Use:

UPDATE tbl SET featured = id IN (4, 10, 21);  

[EDIT]

@OMG Ponies:

that works, you can take advantage of the fact that boolean conditions in Mysql can be directly mapped to integer.

in Postgresql, you have to do this, need to cast the boolean to integer:

update tbl set featured = (id in ('b','d'))::int
Michael Buen
Cool. The OP has the numbers within single quotes, just have to cast/convert if it's necessary.
OMG Ponies