I have the following SQL table that I am trying to retrieve details from based on whether a boolean value is true.
Dummy data
Name | Score | Deleted | annonomous | showuser | ID
Jane | 5 | 0 | 1 | 0 | 7896
John | 1 | 1 | 1 | 0 | 7896
John | 6 | 0 | 0 | 0 | 7896
John | 9 | 0 | 0 | 1 | 7896
I want to get back the records for a specific user that has an annonomous=1 OR showuser=1. NOTE these two columns can never have the same value of true together(like a toggle)
This is what I tried
select *
from table
where name='John' and Deleted=0 and ID=7896 and annonomous=1 OR showuser=1
But the above query is returning the user that I deleted
This is the output I get
Name | Score | Deleted | annonomous | showuser | ID
John | 1 | 1 | 1 | 0 | 7896
John | 9 | 0 | 0 | 1 | 7896
But the output I wanted is
Name | Score | Deleted | annonomous | showuser | ID
John | 9 | 0 | 0 | 1 | 7896
>Solution :
Almost a typo, but you need parentheses in your WHERE clause:
SELECT *
FROM yourTable
WHERE name = 'John' AND Deleted = 0 ID = 7896 AND (annonomous = 1 OR showuser = 1);
Because the AND operator has greater precedence than OR, your current query is being evaluated as this:
SELECT *
FROM yourTable
WHERE (name = 'John' AND Deleted = 0 ID = 7896 AND annonomous = 1) OR showuser = 1;
This version will unconditionally return any record having showuser = 1, regardless of who the user may be.