Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "select where" within json in Oracle SQL Developer?

I have a table called DISCOUNT_CODES with two columns, one having JSON values:

CODE           ACTIVE
1234           {"active":"Y"}
2468           {"active":"N"}
1359           {"active":"Y"}

As the second column is in JSON, I was wondering if there was a way I can select the codes that are active without having to do a select query like:

SELECT CODE FROM DISCOUNT_CODES WHERE ACTIVE = '{"active":"Y"}';

In pseudo-code, I am wondering if something like this is possible:

SELECT CODE FROM DISCOUNT_CODES WHERE JSON(ACTIVE $.active) = "Y";

Edit: I am using Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production

like image 319
Jett Avatar asked Aug 29 '26 20:08

Jett


2 Answers

Yes, you can use a SELECT statement containing JSON_TABLE() function for the DB version 12c+ such as the one below :

SELECT d.code
  FROM discount_codes d
 CROSS JOIN JSON_TABLE(active, '$' COLUMNS (
                                            active VARCHAR2(100) PATH '$.active'
                                           )
                      ) j
 WHERE j.active = 'Y' 

Demo

like image 61
Barbaros Özhan Avatar answered Sep 01 '26 09:09

Barbaros Özhan


You can also use JSON_EXISTS

SELECT CODE FROM DISCOUNT_CODES
WHERE json_exists(ACTIVE, '$?(@.active == "Y")');
like image 37
Derviş Kayımbaşıoğlu Avatar answered Sep 01 '26 10:09

Derviş Kayımbaşıoğlu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!