Skip to content

Instantly share code, notes, and snippets.

@swateek
Last active January 17, 2022 13:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swateek/fe14ee2b85df451cbd30ec5cfb7b4068 to your computer and use it in GitHub Desktop.
Save swateek/fe14ee2b85df451cbd30ec5cfb7b4068 to your computer and use it in GitHub Desktop.
Working with JSON data structures in MySQL
-- https://www.digitalocean.com/community/tutorials/working-with-json-in-mysql
-- select rows where isPrivate field is ""
SELECT * FROM ecom_categories WHERE JSON_EXTRACT(`attributes` , '$.isPrivate') = "";
-- select rows where isPrivate field is not a part of JSON object
SELECT * FROM ecom_categories WHERE JSON_EXTRACT(`attributes` , '$.isPrivate') IS NULL;
-- add isPrivate field to attributes which are not present
UPDATE ecom_categories SET `attributes` = JSON_INSERT(`attributes`, '$.isPrivate', false);
-- remove isPrivate field from attributes
UPDATE ecom_categories SET `attributes` = JSON_REMOVE(`attributes`, '$.isPrivate');
-- conditional update of isPrivate field
UPDATE ecom_categories SET `attributes` = JSON_REPLACE(`attributes`, '$.isPrivate', true) WHERE type="MOBILE";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment