how to select array of distinct values excluding nulls using postgres? for example list of user phone numbers per job department?
Assistant
User
maybe it is simple to just remove NULL from final array?
Assistant
Yes, you can remove NULL values from an array after aggregation using the ARRAY_REMOVE function in PostgreSQL. This is a clean and concise way to ensure your final array contains only distinct, non-null values.
Here's how you can do it:
sql
User
is it possible to remove with ARRAY_REMOVE NULLS AND empty strings? maybe theere is function that excludes one array values from another?
Assistant
Yes, you can remove both NULLs and empty strings from an array in PostgreSQL, and you can also . Here's how to do it:
To retrieve an array of distinct, non-null phone numbers per job department in PostgreSQL, you can use a combination of GROUP BY, ARRAY_AGG, DISTINCT, and optional FILTER or WHERE clauses depending on whether you want to include departments with no phone numbers.
✅ Option 1: Exclude Departments with No Phone Numbers
If you only want departments that have at least one non-null phone number, this is the simplest and most efficient approach.
sql
SELECT
department,
ARRAY_AGG(DISTINCT phone_number) AS phones
FROM
users
WHERE
phone_number IS NOT NULL
GROUP BY
department;
🔍 Explanation:
WHERE phone_number IS NOT NULL: Ensures only rows with actual phone numbers are considered.
DISTINCT: Removes duplicate phone numbers within each department.
ARRAY_AGG(...): Collects the distinct phone numbers into an array.
GROUP BY department: Groups the result by department.
This will exclude departments where all phone numbers are NULL.
✅ Option 2: Include All Departments (Even Those with No Phone Numbers)
If you want to include all departments, even those with no non-null phone numbers, you can use the FILTER clause inside the aggregate function and wrap it in COALESCE to return an empty array instead of NULL.
sql
SELECT
department,
COALESCE(
ARRAY_AGG(DISTINCT phone_number) FILTER (WHERE phone_number IS NOT NULL),
'{}'::text[]
) AS phones
FROM
users
GROUP BY
department;
🔍 Explanation:
FILTER (WHERE phone_number IS NOT NULL): Filters out NULL values before aggregation.
DISTINCT: Ensures only unique phone numbers are included.
COALESCE(..., '{}'::text[]): Replaces NULL with an empty array ({}) for departments with no valid phone numbers.
GROUP BY department: Groups the result by department.
This will include all departments, even those with no phone numbers.
🧩 Optional: Add Sorting to the Resulting Arrays
If you'd like the phone numbers to be sorted alphabetically or numerically, you can add an ORDER BY clause inside the ARRAY_AGG:
sql
SELECT
department,
COALESCE(
ARRAY_AGG(DISTINCT phone_number ORDER BY phone_number) FILTER (WHERE phone_number IS NOT NULL),
'{}'::text[]
) AS phones
FROM
users
GROUP BY
department;
📌 Summary
Requirement
Query
Only departments with at least one non-null phone number
Option 1
All departments, including those with no phone numbers
Option 2
Sorted phone numbers
Add ORDER BY inside ARRAY_AGG
Empty arrays instead of NULL
Use COALESCE(..., '{}'::text[])
Choose the appropriate query based on whether you want to include all departments or only those with phone numbers.
SELECT
department,
ARRAY_REMOVE(ARRAY_AGG(DISTINCT phone_number), NULL) AS phones
FROM
users
GROUP BY
department;
🔍 Explanation:
ARRAY_AGG(DISTINCT phone_number)
Collects unique phone numbers per department, including NULL if any exist.
ARRAY_REMOVE(..., NULL)
Removes all NULL values from the resulting array.
✅ Example Output:
department
phones
HR
{"555-1234", "555-5678"}
IT
{}
Sales
{"555-9876"}
HR has two distinct phone numbers.
IT had only NULL values, so the array becomes empty ({}).
Sales has one valid phone number.
📌 Notes:
Departments with no rows (e.g., no users at all) won’t appear in the result unless you explicitly include them via a LEFT JOIN or similar.
This method is simple and readable, especially when you want to avoid FILTER or WHERE clauses.
It’s safe for handling NULLs in the final array, even if some groups have only NULL values.
🧩 Optional: Add Sorting
If you want the phone numbers sorted:
sql
SELECT
department,
ARRAY_REMOVE(ARRAY_AGG(DISTINCT phone_number ORDER BY phone_number), NULL) AS phones
FROM
users
GROUP BY
department;
⚠️ Performance Consideration:
This approach aggregates NULLs first and then removes them, which may be slightly less efficient than filtering them out earlier (e.g., with WHERE phone_number IS NOT NULL or FILTER (WHERE phone_number IS NOT NULL)).
However, for small to moderate datasets, the difference is negligible, and the clarity of the query may outweigh the performance impact.
✅ Summary:
Use ARRAY_REMOVE(ARRAY_AGG(...), NULL) to:
Remove NULLs from the final array
Keep distinct values
Simplify the query by avoiding pre-filtering logic
This is a practical and idiomatic PostgreSQL technique for cleaning up arrays after aggregation.
exclude values from another array
🔸 1. Remove NULLs and Empty Strings
Use ARRAY_REMOVE(..., NULL) and chain it with another ARRAY_REMOVE(..., '') to remove empty strings:
sql
SELECT
department,
ARRAY_REMOVE(ARRAY_REMOVE(ARRAY_AGG(phone_number), NULL), '') AS cleaned_phones
FROM
users
GROUP BY
department;
ARRAY_REMOVE(..., ''): Removes empty strings ('') from the result.
🔸 2. Exclude Values from Another Array
To remove values from one array that exist in another array, use the array subtraction operator (-):
sql
SELECT
ARRAY['555-1234', '555-5678', '555-9876']::text[]
- ARRAY['555-5678', '555-9876']::text[] AS filtered;
🔍 Output:
code
filtered
----------
{"555-1234"}
This removes all elements from the first array that exist in the second array.
🔸 3. Combine Both: Remove NULLs, Empty Strings, and Exclude Another Array
sql
SELECT
department,
ARRAY_REMOVE(ARRAY_REMOVE(ARRAY_AGG(phone_number), NULL), '')
- ARRAY['555-0000', '555-9999'] AS filtered_phones
FROM
users
GROUP BY
department;
🔍 Explanation:
ARRAY_REMOVE(..., NULL): Remove NULLs.
ARRAY_REMOVE(..., ''): Remove empty strings.
- ARRAY[...]: Exclude specific values (e.g., invalid or placeholder numbers).
🧩 Optional: Use FILTER Clause (PostgreSQL 9.4+)
You can also filter during aggregation to avoid adding unwanted values in the first place:
sql
SELECT
department,
ARRAY_AGG(phone_number) FILTER (WHERE phone_number IS NOT NULL AND phone_number <> '')
- ARRAY['555-0000', '555-9999'] AS filtered_phones
FROM
users
GROUP BY
department;
🔍 Benefits:
More efficient: Filters values before aggregation.
Avoids post-processing steps like ARRAY_REMOVE.
📌 Summary
Task
Syntax
Remove NULLs
ARRAY_REMOVE(array, NULL)
Remove empty strings
ARRAY_REMOVE(array, '')
Remove values from another array
array1 - array2
Remove both NULLs and empty strings
ARRAY_REMOVE(ARRAY_REMOVE(array, NULL), '')
Filter before aggregation
FILTER (WHERE condition)
This approach is clean, efficient, and works for most use cases involving arrays in PostgreSQL.