Group By Primary Key Unlocks Columns
Grouping by the primary key lets every column of the table appear in SELECT via functional dependency, but grouping by a non-key column cannot.
Code
-- 按主键分组时其余列可以合法出现在 SELECT 里:
-- PG 识别 PK → 全行的函数依赖 (functional dependency),每组内非键列值唯一
-- (SQL 标准不允许,PG 对有主键的普通表开放这一推断)
CREATE TEMP TABLE orders (
id bigint PRIMARY KEY,
customer_id bigint NOT NULL,
amount_cents int NOT NULL
);
INSERT INTO orders VALUES (1, 10, 500), (2, 10, 700), (3, 11, 200);
SELECT id, customer_id, COUNT(*) AS order_rows
FROM orders
GROUP BY id
ORDER BY id;
-- 换成非键列分组:customer_id 不函数依赖决定 id,SELECT id 直接报错
-- ERROR: column "orders.id" must appear in the GROUP BY clause
-- or be used in an aggregate function
SELECT customer_id, SUM(amount_cents) AS spent
FROM orders
GROUP BY customer_id
ORDER BY customer_id;The build of the snippet
What runs here is SELECT / INSERT / CREATE — orders are the objects involved.
orders exists because the script builds it as a session-local temp table — no advance setup, and the session’s end is its cleanup.
Mechanically, the statements are built from: COUNT, SUM aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Applying it
Setup is internal: the session-local tables it queries (orders) are made by the file, so a single complete run against a scratch database suffices.
Statements that matter
SELECT customer_id, SUM(amount_cents) AS spent
FROM orders
GROUP BY customer_id
ORDER BY customer_id;
SELECT id, customer_id, COUNT(*) AS order_rows
FROM orders
GROUP BY id
ORDER BY id;
CREATE TEMP TABLE orders (
id bigint PRIMARY KEY,
customer_id bigint NOT NULL,
amount_cents int NOT NULL
);
Interactive Tools for This Topic
FAQ
- Which tables does the SQL touch?
- The references are `orders`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.