Re: JSON and Postgres Variable Queries

From: Robert Haas <robertmhaas(at)gmail(dot)com>
To: Joey Caughey <jcaughey(at)parrotmarketing(dot)com>
Cc: "pgsql-hackers(at)postgresql(dot)org" <pgsql-hackers(at)postgresql(dot)org>, gkimball(at)parrotmarketing(dot)com
Subject: Re: JSON and Postgres Variable Queries
Date: 2014-06-23 15:06:59
Message-ID: CA+TgmoYRL8T0YmpTdf4aDMOza1d7HUgQWCR3DKEZDzMK8V0bZg@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On Fri, Jun 20, 2014 at 11:26 AM, Joey Caughey
<jcaughey(at)parrotmarketing(dot)com> wrote:
> I’m having an issue with JSON requests in Postgres and was wondering if
> anyone had an answer.
>
> I have an orders table with a field called “json_data”.
>
> In the json data there is a plan’s array with an id value in them.
> { "plan”: { “id”: “1” } } }
>
> I can do regular queries that will work, like so:
> SELECT json_data->>’plan'->>’id' as plan_id FROM orders;
>
> But if I try to query on the data that is returned it will fail:
> SELECT json_data->>’plan'->>’id' as plan_id FROM orders WHERE plan_id = 1;
> OR
> SELECT json_data->>’plan'->>’id' as plan_id FROM orders GROUP BY plan_id;
> OR
> SELECT json_data->>’plan'->>’id' as plan_id FROM orders ORDER BY plan_id;
>
> Is this something that has been overlooked? or is there another way to go
> about this?

You might find a sub-SELECT helpful:

SELECT * FROM (SELECT json_data->>’plan'->>’id' as plan_id FROM
orders) x WHERE plan_id = 1

It might be a generally useful thing for WHERE-clause items to be able
to reference items from the target list by alias, or maybe it's
problematic for some reason that I don't know about, but right now
they can't.

--
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Stephen Frost 2014-06-23 15:15:29 Re: replication commands and log_statements
Previous Message Kevin Grittner 2014-06-23 15:06:54 Re: How to use the 'char() ' as data type and a function name in the same time.