0

If I have tables like this:

t1:
 id | name 
----+------
  1 | a
  2 | b
  3 | c
  4 | d

t2:
 id | value 
----+-------
 10 | xxx
 20 | yyy
 30 | zzz

t_join:
 t1_id | t2_id 
-------+-------
     1 |    10
     2 |    20
     3 |    30

A SELECT query for t1.id=1 looks like:

SELECT t1.id, t1.name, t2.value FROM t1, t2,t_join WHERE t1.id=t_join.t1_id AND t2.id=t_join.t2_id AND t1.id=1;

And of course returns:

id | name | value 
----+------+-------
  1 | a    | xxx

If I do the same thing with id=4, I get nothing.

 SELECT t1.id, t1.name, t2.value FROM t1, t2,t_join WHERE t1.id=t_join.t1_id AND t2.id=t_join.t2_id AND t1.id=4;
 id | name | value 
----+------+-------
(0 rows)

And, if I do the same thing with a nonsense id=1234132, I also get nothing.

SELECT t1.id, t1.name, t2.value FROM t1, t2,t_join WHERE t1.id=t_join.t1_id AND t2.id=t_join.t2_id AND t1.id=1234132;
 id | name | value 
----+------+-------
(0 rows)

Is there a way I can differentiate between having an empty result (id=4) vs something that's null (id=1234132)? I guess I want verification that the id I'm checking exists without a separate query. Is this possible?

1
  • Did you try the OUTER JOIN with table t1? which will return all the records in t1 Commented Mar 27, 2017 at 23:18

1 Answer 1

2

How about a left join:

SELECT t1.id, t1.name, t2.value
FROM t1 LEFT JOIN
     t_join
     ON t1.id = t_join.t1_id LEFT JOIN
     t2 
     ON t2.id = t_join.t2_id 
WHERE t1.id = 1;

If t.id is not found, you'll get no rows. If there are no matches in t2, then you'll get a NULL value.

Also, a simple rule: Never use commas in the FROM clause. Always, always use proper, explicit JOIN syntax.

Sign up to request clarification or add additional context in comments.

3 Comments

Do you mean SELECT t1.id, t1.name, t2.value FROM t1 LEFT JOIN t_join ON t1.id = t_join.t1_id LEFT JOIN t2 ON t2.id = t_join.t2_id WHERE t1.id = 1; (The second Left Join). Also, are you recommending never to do the JOIN via WHERE clause as I did in the original question?
@Newtang . . . Commas in the FROM clause have been obsolete for over 20 years.
I understood the FROM comment, thanks. I was asking about the proper explicit JOIN part.

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.