Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Postgres: column reference is ambiguous (42702)

42702 means two joined sources expose the same column name and the query never qualifies it. Alias every table and prefix the column, or use USING.

~5 min readSQL
#PostgreSQL#SQL#Joins#Errors
A Postgres join crate with two identical cyan columns meeting an amber ambiguity gate, a table alias tag beside it

Introduction & Quick Summary

Postgres refuses a query because one name refers to two things:

code
ERROR: column reference "created_at" is ambiguous LINE 1: SELECT id, created_at FROM orders JOIN customers ON orders.customer_id = customers.id; ^ SQL state: 42702

Both orders and customers have a created_at column. The query asks for created_at without saying which one, and Postgres will not guess. The fix is one word of qualification, and the error message already shows the position with a caret.

Where it appears:

  • Joins where both sides share column names (id, created_at, status).
  • Self-joins where the same table is aliased twice or not aliased at all.
  • CTEs and subqueries that project two columns with the same output name.
  • UPDATE ... FROM with RETURNING that references an unqualified column present on both sides.
  • PL/pgSQL functions where a parameter or variable has the same name as a column.

Quick answer: alias every table, qualify every column, and never rely on SELECT * to tell you which duplicate won.

Core Mechanics, Signatures & Reproducible Setup

Name resolution runs in a defined order: output columns of the FROM items are collected first, and an unqualified reference must match exactly one of them. If two match, the parser raises 42702 before planning, so no index or statistics can affect it.

CREATE TABLE customers ( id bigserial PRIMARY KEY, name text NOT NULL, created_at timestamptz NOT NULL DEFAULT now() ); CREATE TABLE orders ( id bigserial PRIMARY KEY, customer_id bigint NOT NULL REFERENCES customers(id), created_at timestamptz NOT NULL DEFAULT now() ); -- fails with 42702 SELECT id, created_at FROM orders JOIN customers ON orders.customer_id = customers.id; -- correct SELECT o.id AS order_id, c.id AS customer_id, o.created_at FROM orders AS o JOIN customers AS c ON c.id = o.customer_id;

The same family of errors points at different mistakes:

SQL stateMessageMeaning
42702column reference "x" is ambiguoustwo visible columns share the name
42703column "x" does not existno visible column with that name
42P09alias "x" is ambiguoustwo FROM items use one alias
42601syntax error at or nearthe query never reached resolution

Key Comparison Table

ApproachResultUse when
Qualify with an aliasunambiguous, explicitalways in joins
JOIN ... USING (id)one merged id columnboth sides use the same name by design
NATURAL JOINmerges every shared columnalmost never, it hides changes
Subquery with explicit aliasesstable output namesthe outer query needs a clear contract
SELECT * with USINGduplicate columns in outputnever in application queries
Qualified RETURNINGresolves the right tableUPDATE ... FROM

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Read the caret, not just the message

The LINE and caret position identify the exact token. In a long generated query, that is faster than reading the whole statement.

sql
-- psql reports the position: -- LINE 3: AND created_at > now() - interval '7 days' -- ^

If the caret sits under a column you thought was qualified, check the alias: o.created_at with no o in the FROM clause produces 42703, not 42702, so a 42702 caret always points at an unqualified name or a genuinely duplicated alias.

2. USING merges columns, and that changes names

JOIN ... USING (id) produces a single id column, so an unqualified id is unambiguous while orders.id still refers to the table. Code that mixes both styles breaks when the join is rewritten.

SELECT id, o.created_at, c.name FROM orders AS o JOIN customers AS c USING (id);

In application queries, prefer explicit ON with aliases. USING is compact and fine in ad-hoc analysis, but it makes the output shape depend on which columns the tables happen to share.

3. Self-joins without distinct aliases

Joining a table to itself requires two aliases. Reusing one is a 42P09, and omitting them gives an ambiguous column for every shared field.

SELECT e.name AS employee, m.name AS manager FROM employees AS e LEFT JOIN employees AS m ON m.id = e.manager_id;

Naming aliases after their role (e, m, sender, recipient) keeps long joins readable and makes the qualification obvious at a glance.

4. Duplicate output names from CTEs and subqueries

A subquery that selects two id columns exposes two columns named id. The outer query then cannot reference either without an alias.

WITH pairs AS ( SELECT o.id, c.id FROM orders AS o JOIN customers AS c ON c.id = o.customer_id ) SELECT pairs.id FROM pairs; -- 42702 -- fix inside the CTE WITH pairs AS ( SELECT o.id AS order_id, c.id AS customer_id FROM orders AS o JOIN customers AS c ON c.id = o.customer_id ) SELECT order_id, customer_id FROM pairs;

Alias at the projection, not at the outer reference. The CTE then has a contract other queries can rely on.

5. UPDATE ... FROM and RETURNING

An UPDATE with a joined FROM sees both tables in RETURNING, so an unqualified column that exists in both is ambiguous.

sql
UPDATE orders AS o SET status = 'shipped' FROM customers AS c WHERE c.id = o.customer_id AND c.region = 'eu' RETURNING o.id, o.status; -- qualify: RETURNING id would be ambiguous

The target table's columns are not shadowed by the FROM, they are merged into the same namespace. Qualification is the only reliable form.

6. PL/pgSQL variables shadowing columns

Inside a function, a variable with the same name as a column makes WHERE id = id ambiguous. Postgres raises the same 42702, and the resolution is a rename or an explicit conflict setting.

CREATE FUNCTION orders_for(customer_id bigint) RETURNS SETOF orders LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY SELECT o.* FROM orders AS o WHERE o.customer_id = orders_for.customer_id; -- qualified by function name END; $$;

Renaming the parameter (p_customer_id) is clearer than relying on qualification rules, and #variable_conflict use_column is available for cases where the column must win.

Output columns that collide with a table column. An alias in the SELECT list can hide a table column of the same name. Postgres resolves ORDER BY against output names first, so the sort silently uses the computed value rather than the stored one.

SELECT o.id, o.created_at AS created_at_utc FROM orders AS o ORDER BY created_at; -- ambiguity between output name and table column

Qualify the sort key (ORDER BY o.created_at) or rename the output so the two never share a name. The same rule applies to GROUP BY: a group by an output alias is accepted only in a few positions, and relying on it makes the query break as soon as another table joins in.

Common Compilation/Runtime Mistakes & Version Gotchas

  • SELECT * in a view or CTE. Two columns with the same name become two ambiguous columns downstream. List columns explicitly.
  • Aliasing with reserved or repeated names. AS user, AS order, or the same alias twice produces errors that look like column problems.
  • Ordering by an output alias. ORDER BY created_at can bind to the output column rather than a table column; when both exist, the behaviour surprises. Qualify or use the ordinal deliberately.
  • ORM-generated joins. An ORM that joins two tables without aliases can emit 42702 when a model gains a column with a common name. Read the generated SQL, not the model.
  • Partitioned tables and inheritance. Child tables add columns to the visible set, so a query that worked before a new partition column can become ambiguous after a schema change.
SymptomCauseFix
fails after adding a columnnew name collidesqualify columns
fails only in a functionvariable shadows columnrename the parameter
fails only in productiondifferent search_path or viewschema-qualify the view
works in one client, not anotherclient rewrites *list columns

Format and test the statement with the SQL formatter and runner, and inspect the table shapes with the SQL schema tool before rewriting a join by hand.

The SQL state is listed in the Postgres error codes appendix, and the resolution rules for column names in joins are specified under SELECT.

Official references

primary documentation

The SQL documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit SQL work — they run entirely in this browser tab, so nothing you paste leaves your device.

All SQL guides

More in SQL

All SQL guides

The guides filed next to this one in SQL, in library order.