0

I want this to be like this.

I have an ENUM column with 0 AND 1, i want to toggle between these two values on each query.

UPDATE settings
SET state = 1 IF state = 0 
              ELSE IF state = 0 
                   SET STATE = 1 WHERE id = '$id';

I tried this, but it leaves the column empty.

UPDATE settings SET state = IF(state=1, 0, 1) 

Thanks.

5
  • Why not SET state = (1 - state) WHERE... If the column is initially NULL, you have to set default value = 0 or use state= 1- IFNULL(state,0) Commented Nov 10, 2014 at 14:00
  • Its not initially NULL, its initially '0'. Commented Nov 10, 2014 at 14:11
  • Ok, then "state = 1 - state" will work. When 1 it will be set to 0, and when 0 - to 1. Commented Nov 10, 2014 at 14:16
  • @i486 maybe there's something wrong with my system, this acts like the answer below. Sets state = '', and them '0', then ''; not 1. Anyway, can you put this as the answer and explain the maths? Commented Nov 10, 2014 at 14:24
  • Define column as INT or TINYINT (or even BIT). With enum it looks like string/varchar, i.e. no math. Commented Nov 10, 2014 at 14:38

2 Answers 2

2

I don't like enum for various reasons. Especially when you use it to store 0 and 1 it can be confusing, yes, even error prone.

Use a tinyint, it's much easier to use and more readable.

mysql> create table switch(state tinyint default 0);

mysql> insert into switch values (0);

mysql> select * from switch;
+-------+
| state |
+-------+
|     0 |
+-------+

mysql> update switch set state = not state; /*simple as that :)*/

mysql> select * from switch;
+-------+
| state |
+-------+
|     1 |
+-------+

mysql> update switch set state = not state;

mysql> select * from switch;
+-------+
| state |
+-------+
|     0 |
+-------+
Sign up to request clarification or add additional context in comments.

1 Comment

1 and 0 are treated as true and false.
0

You can also use simple if statement :

mysql > UPDATE switch SET state=if(state=0,1,0);

Comments

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.