1

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 Answers 3

7

Use:

UPDATE tbl
   SET featured = CASE 
                    WHEN id IN (4, 10, 21) THEN '1'
                    ELSE '0'
                  END;
Sign up to request clarification or add additional context in comments.

Comments

4

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

2 Comments

Cool. The OP has the numbers within single quotes, just have to cast/convert if it's necessary.
indeed, the auto-conversion would be a performance hit if you didn't explicitly cast/convert
-3

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

4 Comments

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?"
@jigs: Nobody likes a smart alec.
UPDATE Activity SET Activity.Charges = 10 WHERE (Activity.[Activity ID]) In (2,3,4); This is a example which is working.
@ddc0660: maybe jigs have acquired bad habits from becoming a programmer heheh :D stackoverflow.com/questions/164432/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.