Any Value Arbitrary Group Sample

PostgreSQL 16 ANY_VALUE picks an arbitrary non-null value per group, so wide GROUP BY queries stop failing with the must-appear-in-GROUP-BY error.

SqlData Fetching

Code

snippet
-- PostgreSQL 16 的 ANY_VALUE():分组里任取一个非空值,
-- 免掉"必须出现在 GROUP BY 里"的报错,也不必用 min/max 冒充代表值
CREATE TABLE stores (region text NOT NULL, city text NOT NULL, staff int NOT NULL);
INSERT INTO stores VALUES
  ('west', 'perth', 12), ('west', 'boise', 8),
  ('east', 'lisbon', 20), ('east', 'porto', 6);

-- 裸选 city 会报 42803:
-- SELECT region, city FROM stores GROUP BY region;
-- ERROR: column "stores.city" must appear in the GROUP BY clause
--        or be used in an aggregate function

SELECT
  region,
  ANY_VALUE(city)  AS some_city,
  ANY_VALUE(staff) AS some_staff,
  COUNT(*)         AS store_count
FROM stores
GROUP BY region
ORDER BY region;

What the code does

Several statements share this file — SELECT / INSERT / CREATE, with stores among the objects involved.

Breaking the statements into their working parts: COUNT 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.

Applying it

Run the statement against the stores table.

Statements that matter

SELECT
region,
ANY_VALUE(city)  AS some_city,
ANY_VALUE(staff) AS some_staff,
COUNT(*)         AS store_count
FROM stores
GROUP BY region
ORDER BY region;
INSERT INTO stores VALUES
('west', 'perth', 12), ('west', 'boise', 8),
('east', 'lisbon', 20), ('east', 'porto', 6);
CREATE TABLE stores (region text NOT NULL, city text NOT NULL, staff int NOT NULL);

Interactive Tools for This Topic

FAQ

Which tables appear in this script?
`stores`.