PostgreSQL JSONB – Finding Element with Null Attribute in Array

jsonpostgresqlpsql

With the following table in psql 10:

CREATE TABLE logs(id serial, data JSONB); 
INSERT INTO logs VALUES
  (1, '[{"name":"test1","date":"2018-01-09"},{"name":"test2","date":"2018-01-10"}]'),
  (2, '[{"name":"test3","date":"2018-01-10"},{"name":"test4","date":null}]');

How do I find row #2 by querying the date=null value in the array?

I already know how to query by name to find row#2:

AND data @> '[{"name": "test4"}]'

But I don't know how you can query for rows with or without a null date attribute.

Best Answer

Like this,

SELECT * FROM logs WHERE data @> '[{"date":null}]';
 id |                                    data                                    
----+----------------------------------------------------------------------------
  2 | [{"date": "2018-01-10", "name": "test3"}, {"date": null, "name": "test4"}]
(1 row)