SQL: GROUP BY can reference a column position, and should not

GROUP BY 1 means the first selected column. It works, it is shorter, and it silently means something different the moment someone adds a column to the SELECT list.

Code
SELECT created_at::date, status, COUNT(*)
  FROM orders
 GROUP BY 1, 2;               -- date, status

-- Someone adds a column at the front...
SELECT customer_id, created_at::date, status, COUNT(*)
  FROM orders
 GROUP BY 1, 2;               -- now customer_id, date - a different report

-- Name them:
 GROUP BY created_at::date, status;
Output
-- The query still runs. The numbers are still plausible. Nothing errors.
-- That is what makes it worth avoiding.
--
-- ORDER BY 1 has the same problem and the same fix. It is defensible in a
-- throwaway query at a prompt, and not in anything committed.
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-08-25