Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I query with JSON function/operator where key is either not null or is null?

I am looking for the active record version of the following sql code:

select *
from users
where (details->'email') is not null

Let's say that my User model has a json field called, details, and some records will have an email key-value and some will not. I'm trying to query the user records that have an email, key-value. I tried using the following, User.where("details->'email' is not null"), but my terminal prints out this:

PG::UndefinedFunction: ERROR:  operator does not exist: json -> boolean

I found this SO post, which attempts to do the opposite query, but the idea is the same. If someone can show me the Active Record version of querying where a json key is or is not present, I'd greatly appreciate it.

like image 393
robskrob Avatar asked Aug 05 '15 14:08

robskrob


People also ask

IS NOT NULL JSON SQL?

Note: A JSON value of null is a value as far as SQL is concerned. It is not NULL, which in SQL represents the absence of a value (missing, unknown, or inapplicable data). In particular, SQL condition IS NULL returns false for a JSON null value, and SQL condition IS NOT NULL returns true.

How do I query Jsonb data in SQL?

Querying the JSON documentPostgreSQL has two native operators -> and ->> to query JSON documents. The first operator -> returns a JSON object, while the operator ->> returns text. These operators work on both JSON as well as JSONB columns. There are additional operators available for JSONB columns.

What is Jsonb_build_object?

jsonb_build_object(VARIADIC "any") Builds a JSON object out of a variadic argument list. By convention, the argument list consists of alternating keys and values. json_build_object('foo',1,'bar',2)

Can JSON be null Postgres?

Expands a JSON array to a set of text values. Returns the type of the outermost JSON value as a text string. Possible types are object, array, string, number, boolean, and null.


1 Answers

This worked for getting users with an email key:

User.where("(details->'email') is not null")

This worked for getting users without an email key:

User.where("(details->'email') is null")
like image 137
robskrob Avatar answered Nov 10 '22 01:11

robskrob