PostgreSQL 18 reference · Aggregate Functions
PostgreSQL ANY_VALUE() Function
Return an arbitrary non-NULL value from a group. Useful for columns you know are the same within each group.
PostgreSQL 18 Since 16
Syntax
any_value(expression)
Parameters
| Parameter | Description |
|---|---|
expression |
A column or expression. |
Return value
One of the group's values.
Examples
SELECT o.customer_id, any_value(c.name) AS name, count(*) AS orders
FROM orders AS o JOIN customers AS c USING (customer_id)
GROUP BY o.customer_id
ORDER BY orders DESC, o.customer_id
LIMIT 3;
Output
customer_id | name | orders
-------------+--------------+--------
1 | Ada Lovelace | 3
2 | Alan Turing | 2
3 | Grace Hopper | 2
(3 rows)Run this on your computer — see “Get Started” for setup.
SELECT any_value(x) IS NOT NULL AS found FROM (VALUES (NULL), (5)) AS t(x);
Output
found ------- t (1 row)
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| PostgreSQL 16 | Added |
Related
MIN()· Return the smallest value in a group. Works with numbers, text, dates and, since PostgreSQL 18, arrays.MAX()· Return the largest value in a group. Works with numbers, text, dates and, since PostgreSQL 18, arrays.- SQL Aggregate Functions · tutorial
- SQL GROUP BY · tutorial