Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Not an expert in SQL yet. :) Let us assume we have the below table:

Table A (id1 and id2 are primary keys)

Columns:
id1      id2   status
 1        1    true // values entry
 1        2    false
 3        4    true
 3        5    false

Now while getting data for id1, I want to make sure the status is true in both the rows. What would be the efficient way to get this?

In the example, I want to return empty result since id1 has false state in at least 1 entry.
SQL
Select id1 from A where status = true


What I have tried:

I tried, however it does not check if same id is available in other rows.
SQL
SELECT DISTINCT id1 FROM A WHERE status = 1 

Do we need to add sub query for this then using IN or Exists? Will really appreciate it if any of you guys point me in the right direction. :)
SQL
SELECT DISTINCT id1 FROM A WHERE status = 1 and not exist in (SELECT DISTINCT id1 FROM A WHERE status = 0)
??
Posted
Updated 13-Sep-23 3:54am
v5

DISTINCT isn't what you want: you need a GROUP BY[^] clause.
If you GROUP BY id1 with a WHERE selecting for true entries only, the COUNT method will return 1 for each id value - which means you aren't interested in it.

So try this:
SQL
SELECT id1 FROM MyTable GROUP BY id1 WHERE status = 1 HAVING COUNT(id1) = 2
 
Share this answer
 
Griff's answer works if you only have two entries for each id1. But there's nothing in your question to suggest such a limitation. :)

A correlated sub-query with a Not Exists is probably the clearest solution:
SQL
SELECT DISTINCT id1
FROM A As A1
WHERE Not Exists
(
    SELECT 1
    FROM A As A2
    WHERE A2.id1 = A1.id1
    And A2.status = 0
)

Alternatively, you could use EXCEPT:
SQL
SELECT id1 FROM A WHERE status = 1
EXCEPT
SELECT id1 FROM A WHERE status = 0
EXCEPT and INTERSECT (Transact-SQL) - SQL Server | Microsoft Learn[^]
 
Share this answer
 
Comments
OriginalGriff 31-Aug-23 4:56am    
"I want to make sure the status is true in both the rows."
Hence a "two row per ID" solution :D
Richard Deeming 31-Aug-23 4:58am    
Agreed, the question isn't entirely clear. The sample data only shows two rows for each id1 value, but there's no indication that there couldn't be more (or less) than two. :)
Member 11314626 31-Aug-23 6:20am    
Yes, I realised after seeing answer from OriginalGriff. Thank you both :)! Played with Not Exists and Except, both worked.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900