Why it happens: an ambiguous column when joining tables
WITH customers(id, name) AS (
VALUES (1, 'Amy'), (2, 'Liam')
), orders(id, customer_id) AS (
VALUES (101, 1), (102, 2)
)
SELECT id, name
FROM customers
JOIN orders
ON customers.id = orders.customer_id;Both customers and orders have a column called id. The engine needs to know which one you want to return.
Check the result with small data
Each table has its own id, and they mean different things.
WITH customers(id, name) AS (VALUES (1,'Amy')),
orders(id, customer_id) AS (VALUES (101,1))
SELECT c.id AS customer_id, p.id AS order_id
FROM customers c JOIN orders p ON p.customer_id=c.id;| customer_id | order_id |
|---|---|
| 1 | 101 |
The c.id and p.id prefixes show which entity each value belongs to. If you write just SELECT id, the engine cannot tell which one you want.
Check your understanding: Which id would you use to link other order data?
Show answer
p.id, the order identifier. c.id identifies the customer.
How to fix it in SQL
WITH customers(id, name) AS (
VALUES (1, 'Amy'), (2, 'Liam')
), orders(id, customer_id) AS (
VALUES (101, 1), (102, 2)
)
SELECT c.id AS customer_id,
c.name,
p.id AS order_id
FROM customers AS c
JOIN orders AS p
ON c.id = p.customer_id
ORDER BY c.id;| customer_id | name | order_id |
|---|---|---|
| 1 | Amy | 101 |
| 2 | Liam | 102 |
How to check it
Check that the identifier returned belongs to the entity you are looking for.
How to avoid it next time
Use the same aliases consistently in SELECT, ON, WHERE and ORDER BY.
Related cases worth checking
Once you assign an alias, use it consistently throughout the query. As well as avoiding ambiguity, short prefixes make it obvious where each column comes from in multi-table JOINs.
A good sign: someone else can read p.id and c.id and know straight away that they identify different entities.
Decide where a column comes from before renaming the output
When customers and orders both have an idcolumn, you must decide which one to display and which one drives the filter. c.id AS customer_id and p.id AS order_id let you expose both identities under different names. The output alias improves the report, but it does not replace qualifying the columns inside the join condition.
Check every part of the statement: the error can show up in SELECT, ON, WHERE u ORDER BY. Do not switch every reference to the first table out of habit. Filtering on c.id = 5 means looking for a customer; filtering on p.id = 5 means looking for an order. Both queries can be valid and return different sets.
Avoid relying on SELECT * when the result feeds an application. Two columns with the same name can overwrite each other or be hard to tell apart when each row becomes an object. Select only the columns you need and give each output a unique name. As a test, include a customer whose id differs from their order's id: that exposes a fix that only worked by coincidence.
Technical questions: PostgreSQL: SELECT, columns and aliases (opens in a new tab).