I currently have a PostgreSQL table that looks something like this, the data column is JSON, I am trying to query the table based on keys that may or may not be in the JSON data.
| A | B | C | data |
----------------------------------------------------
| 1 | 2 | 3 | {} |
| 2 | 3 | 3 | {"name": "jack", "message": "123"} |
| 3 | 4 | 3 | {"name": "jill", "voice": "456"} |
| 4 | 2 | 3 | {"name": "bill", "email" "789"} |
Currently I have
SELECT *
FROM (
SELECT
a,
b,
c,
coalesce(
CASE
WHEN (data ->> 'message') IS NULL
THEN NULL
ELSE (data ->> 'message')
END,
'') AS message,
coalesce(
CASE
WHEN (data ->> 'voice') IS NULL
THEN NULL
ELSE (data ->> 'voice')
END,
'') AS voice,
coalesce(
CASE
WHEN (data ->> 'email') IS NULL
THEN NULL
ELSE (data ->> 'email')
END,
'') AS email
FROM mytable) AS t
WHERE (t.message = "789" OR
t.voice = "789" OR
t.email = "789");
I am currently getting the error, ERROR: column "789" does not exist
I know there is probably a more efficient way of doing it. Any help greatly appreciated.
asked Oct 20, 2017 at 17:23
sir_t
1331 gold badge3 silver badges13 bronze badges
-
1Strings need to be enclosed in single quotes in SQL. Double quotes are for identifiers.user330315– user3303152017年10月20日 19:13:20 +00:00Commented Oct 20, 2017 at 19:13
-
Ahhhhhh! so obvious. Thankssir_t– sir_t2017年10月21日 21:24:01 +00:00Commented Oct 21, 2017 at 21:24
1 Answer 1
use single quotes t.message = '789'
answered Oct 20, 2017 at 17:34
classicalConditioning
6557 silver badges15 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-sql