Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return records that has one matching value in two columns

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading