Updated on 2025-10-23 GMT+08:00

Join Queries

A join query may also be referred to as a cross-table query, where multiple tables need to be associated.
-- Create a table and insert data into the table.
m_db=# CREATE TABLE emp(
    id int,             -- Employee ID
    name varchar(20),   -- Employee name
    deptno int          -- Department ID of the employee
);

m_db=# CREATE TABLE dept(
    deptno int,         -- Department ID
    depname varchar(20) -- Department name
);

m_db=# INSERT INTO emp VALUES (1, 'Joe', 10), (2, 'Scott', 20), (3, 'Ben', 999);   -- The department for Ben has not been confirmed yet. Therefore, the department ID is 999.
m_db=# INSERT INTO dept VALUES (10, 'hr'), (20, 'it'), (30, 'sal');                -- There is no employee in the sal department.
  • INNER JOIN
    m_db=# SELECT t1.id,t1.name,t2.depname FROM emp t1 JOIN dept t2 ON t1.deptno = t2.deptno;
     id | name  | depname 
    ----+-------+---------
      1 | Joe   | hr
      2 | Scott | it
    (2 rows)
  • LEFT JOIN
    m_db=# SELECT t1.id,t1.name,t2.depname FROM emp t1 LEFT JOIN dept t2 ON t1.deptno = t2.deptno;
     id | name  | depname 
    ----+-------+---------
      1 | Joe   | hr
      2 | Scott | it
      3 | Ben   | 
    (3 rows)
  • RIGHT JOIN
    m_db=# SELECT t1.id,t1.name,t2.depname FROM emp t1 RIGHT JOIN dept t2 ON t1.deptno = t2.deptno;
     id | name  | depname 
    ----+-------+---------
      1 | Joe   | hr
      2 | Scott | it
        |       | sal
    (3 rows)