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.
Code
-- 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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.
FAQ
- Which tables appear in this script?
- `stores`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.