I have 2 tables:
A B
-- ----
ID FKID
-- ----
1 3
2 3
3 4
4 4
I need a select statement which shows me all of A with a field that tells me if table B has any ids that match that ID.
Desired Result
-----------
ID | hasB
-----------
1 no
2 no
3 yes
4 yes
For checking the existence we need to use the COL_LENGTH() function. COL_LENGTH() function returns the defined length of a column in bytes. This function can be used with the IF ELSE condition to check if the column exists or not.
Outer joins are joins that return matched values and unmatched values from either or both tables.
When you use a simple (INNER) JOIN , you'll only get the rows that have matches in both tables. The query will not return unmatched rows in any shape or form.
In SQL Server this would be the most efficient way rather than doing an OUTER JOIN
then removing the duplicates with DISTINCT
. Not sure for postgres, you'd need to check the plans.
SELECT ID,
CASE
WHEN EXISTS (SELECT *
FROM B
WHERE B.FKID = A.ID) THEN 'yes'
ELSE 'no'
END AS hasB
FROM A
SELECT DISTINCT
a.ID,
CASE WHEN b.FKID IS NULL THEN 'no' ELSE 'yes' END AS hasB
FROM
tableA a LEFT JOIN
tableB b ON a.ID = b.FKID
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With