2

My Query is

SELECT
    id,
    ARRAY_AGG(session_os)::integer[]
FROM
    t
GROUP BY id
HAVING ARRAY_AGG(session_os)::integer[] && ARRAY[1,NULL]

It's giving ERROR: array must not contain nulls

Actually I want to get rows like

  id   | Session_OS
-------|-------------
 641   | {1, 2}
 642   | {NULL, 2}
 643   | {NULL}

Kindly check the sample data here

https://dbfiddle.uk/?rdbms=postgres_13&fiddle=7793fa763a360bf7334787e4249d6107

1
  • I only get this error when the extension intarray is installed (which dbfiddle apparently has installed by default, which is a bit strange to me) Commented Dec 15, 2020 at 17:00

2 Answers 2

1

The && operator does not support NULL values. So, you need another approach. For example you could join the data to the table first. This gives you the ids which are linked to your required data. At the second step you are able to arregate all values using these ids.

step-by-step demo:db<>fiddle

SELECT
    id,
    ARRAY_AGG(session_os)                        -- 4                         
FROM t
WHERE id IN (                                    -- 3
    SELECT 
        id
    FROM
        t
    JOIN (
        SELECT unnest(ARRAY[1, null]) as a       -- 1
    )s ON s.a IS NOT DISTINCT FROM t.session_os  -- 2
)
GROUP BY id
  1. Create a table or query result which contains your relevant data, incl. the NULL value.
  2. You can join the data, incl. the NULL value, using the operator IS NOT DISTINCT FROM, which considers the NULL.
  3. Now you have fetched the relevant id values which can be used in the WHERE filter
  4. Finally your can do your aggregation
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. Can you check when I am passing only null in array it's throwing an error.dbfiddle.uk/…
dbfiddle.uk/… If your array contains only a NULL value, it is not clear which type the array is. so you have to cast it manually. In that case you have int values, which requires an int array
Thank. Working fine everything.
0

The extension intarray installs its own && operator for int[], and this doesn't allow NULLs and it takes precedence over the built-in && operator.

If you are not using intarray, you can just uninstall it (except for in dbfiddle, where you can't). If you are using it occasionally, I think it is best to install it in its own schema which is not in your search path. Then you need to schema qualify its operators when you do need them.

Alternatively, you can leave intarray in place and schema qualify the normal built-in operators when you need those ones specifically, as shown here.

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.