0

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
2
  • 1
    Strings need to be enclosed in single quotes in SQL. Double quotes are for identifiers. Commented Oct 20, 2017 at 19:13
  • Ahhhhhh! so obvious. Thanks Commented Oct 21, 2017 at 21:24

1 Answer 1

1

use single quotes t.message = '789'

answered Oct 20, 2017 at 17:34
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.