SQL

SQL

March 24, 2024

Basics #

Fundamental Syntax #

  • SELECT
  • FROM
  • WHERE
  • GROUP BY
  • HAVING
  • ORDER BY
  • LIMIT

Types of Joins - PostgreSQL-Docs #

  • INNER JOIN
  • LEFT JOIN
  • RIGHT JOIN
  • FULL OUTER JOIN

Joins of all types can be chained together or nested: either or both of T1 and T2 may be joined tables. Parentheses may be used around JOIN clauses to control the join order. In the absence of parentheses, JOIN clauses nest left-to-right.

To put this together, assume we have tables t1

num | name
-----+------
  1 | a
  2 | b
  3 | c 

and t2

num | value
-----+-------
  1 | xxx
  3 | yyy
  5 | zzz

then we get the following results for the various joins:

  => SELECT * FROM t1 CROSS JOIN t2;
  num | name | num | value
  -----+------+-----+-------
    1 | a    |   1 | xxx
    1 | a    |   3 | yyy
    1 | a    |   5 | zzz
    2 | b    |   1 | xxx
    2 | b    |   3 | yyy
    2 | b    |   5 | zzz
    3 | c    |   1 | xxx
    3 | c    |   3 | yyy
    3 | c    |   5 | zzz
  (9 rows)

  => SELECT * FROM t1 INNER JOIN t2 ON t1.num = t2.num;
  num | name | num | value
  -----+------+-----+-------
    1 | a    |   1 | xxx
    3 | c    |   3 | yyy
  (2 rows)

  => SELECT * FROM t1 INNER JOIN t2 USING (num);
  num | name | value
  -----+------+-------
    1 | a    | xxx
    3 | c    | yyy
  (2 rows)

  => SELECT * FROM t1 NATURAL INNER JOIN t2;
  num | name | value
  -----+------+-------
    1 | a    | xxx
    3 | c    | yyy
  (2 rows)

  => SELECT * FROM t1 LEFT JOIN t2 ON t1.num = t2.num;
  num | name | num | value
  -----+------+-----+-------
    1 | a    |   1 | xxx
    2 | b    |     |
    3 | c    |   3 | yyy
  (3 rows)

  => SELECT * FROM t1 LEFT JOIN t2 USING (num);
  num | name | value
  -----+------+-------
    1 | a    | xxx
    2 | b    |
    3 | c    | yyy
  (3 rows)

  => SELECT * FROM t1 RIGHT JOIN t2 ON t1.num = t2.num;
  num | name | num | value
  -----+------+-----+-------
    1 | a    |   1 | xxx
    3 | c    |   3 | yyy
      |      |   5 | zzz
  (3 rows)

  => SELECT * FROM t1 FULL JOIN t2 ON t1.num = t2.num;
  num | name | num | value
  -----+------+-----+-------
    1 | a    |   1 | xxx
    2 | b    |     |
    3 | c    |   3 | yyy
      |      |   5 | zzz
  (4 rows)

The join condition specified with ON can also contain conditions that do not relate directly to the join. This can prove useful for some queries but needs to be thought out carefully. For example:

  => SELECT * FROM t1 LEFT JOIN t2 ON t1.num = t2.num AND t2.value = 'xxx';
  num | name | num | value
  -----+------+-----+-------
    1 | a    |   1 | xxx
    2 | b    |     |
    3 | c    |     |
  (3 rows)

SQL-JOINS-Wikipedia