5

In the following request:

SELECT
  myid,
  min(name) AS name,
  array_agg(array[zip, city])) AS city
FROM my_table
WHERE name LIKE 'Doe'
GROUP BY myid
LIMIT 10

I get the following result:

+-------+------+-------------------+
| myid  | name | city              |
+-------+------+-------------------+
| A123  | Doe  | {{69,"Groville"}} |
| B456  | Doe  | {{NULL,NULL}}     |
+-------+------+-------------------+

How can I get rid of the NULL values and get an empty field for city instead ?

=== EDIT ===

Replaced (array_agg(name))[1] AS name by min(name) AS name in the query, as suggested by @a_horse_with_no_name.

2
  • 1
    Unrelated, but: why not use min(name) instead of first aggregating all names and then pick one Commented May 8, 2020 at 11:46
  • Because I didn't know it :) Thanks for the tip! Commented May 8, 2020 at 11:53

2 Answers 2

8

You can use array_remove():

array_agg(array_remove(array[zip, city], null))
Sign up to request clarification or add additional context in comments.

1 Comment

I get this error: ERROR: cannot accumulate empty arrays, SQL state: 2202E.
6

You can use conditional aggregation.

SELECT myid,
       min(name) AS name,
       array_agg(array[zip, city]) filter (where num_nulls(zip, city) = 0) AS city
FROM my_table
WHERE name LIKE 'Doe'
GROUP BY myid
LIMIT 10

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.