Monday, December 5, 2016

MySQL and JSON column

Since version 5.7 MySQL has support for JSON. Here's create table script and simple CRUD SQL statements.

CREATE TABLE `t1` (
  `id` int(11) NOT NULL,
  `jdoc` json DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `t1` (`id`, `jdoc`) VALUES
(1, '["officia", "et", "anim", "dolore", "ut", "duis", "quis"]'),
(2, '{"valid_until": "23.03.2016"}'),
(4, '{"valid_until": "24.04.2012"}'),
(6, '["lorem", "ipsum"]'),
(7, '{"valid_until": "24.04.2034"}');

ALTER TABLE `t1`  ADD PRIMARY KEY (`id`);

ALTER TABLE `t1`  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;

-- SELECT id, json_extract(jdoc, "$.valid_until") as jd FROM t1 WHERE json_extract(jdoc, "$.valid_until") IS NOT NULL
-- INSERT INTO t1 VALUES (null, '{"valid_until":"24.04.2034"}' )
-- UPDATE t1 SET jdoc= JSON_SET(jdoc, "$.valid_until", "24.04.2016") WHERE id = 3;
-- DELETE FROM t1  WHERE json_extract(jdoc, "$.valid_until") = '24.04.2016';


No comments:

Post a Comment