sqlpostgresqlleft-join

Is there a point in left joining a table where none of its columns get used?


CREATE OR REPLACE VIEW my_schema.my_table as
SELECT
    t.integer_id_column,
    t.col2,
    COALESCE(r.col1, r.col2) AS ID,
    r.col1,
    t.col3,
    t.col4,
    r.col2
FROM table1 t
LEFT JOIN table2 qr ON t.integer_id_column = qr.integer_id_column
LEFT JOIN table3 r ON r.integer_quantity = t.integer_quantity AND r.date = t.date
WHERE t.type = 'my_type' AND (t.cost = 0 or t.cost IS NULL)
ORDER BY 1 DESC;

I'm working with a PostgreSQL database, and I see the above table created. I don't see any point in the left join on table2 since the select statement doesn't actually select anything from table2. Is there some reason that this would be done in Postgres that I'm not aware of?


Solution

  • To answer the question asked: it can make a difference.

    LEFT JOIN table2 ... can multiply output rows if qr.integer_id_column is not defined UNIQUE. (Even without using any of the table columns anywhere in the query, other than the join condition.) Rarely useful, but possible.

    Conversely, that LEFT JOIN is a complete no-op, if qr.integer_id_column is defined UNIQUE. Multiplication cannot happen, and you can safely remove it.

    Aside: you can't have "col2" twice as output column name in a view definition. Probably just a slip-up while anonymizing column names.