Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send this SQL statement in a single query?

Tags:

php

mysql

I am using MySQL and I want to send a statement similar to this one in a single query :

UPDATE fruits SET ToBuy=’yes’ WHERE Price <100, ToBuy=’no’ WHERE Price >=100

I know that I can divide this in 2 separate queries and it works this way but I was wondering if it is possible to do it with a single query.

like image 651
panda Avatar asked Oct 20 '22 11:10

panda


2 Answers

You need a CASE statement:

UPDATE fruits
SET ToBuy = CASE WHEN Price < 100 THEN 'yes' WHEN Price >=100 THEN 'no' END

Of course you could just use CASE WHEN Price < 100 THEN 'yes' ELSE 'no' END as well, but I've used the above clause to match your logic.

like image 129
TobyLL Avatar answered Oct 22 '22 01:10

TobyLL


Using the CASE keyword would work :

UPDATE fruits

SET
   ToBuy = CASE WHEN Price<100 THEN  'yes'
               ELSE 'no'
like image 24
Rémi Becheras Avatar answered Oct 22 '22 01:10

Rémi Becheras