Log inSign up

JSON data, views and procedures in MySQL 8

Declare a column as JSON, read values with -> and ->>, and index the fields you filter on through a generated column or a multi-valued index. Save common queries as views with CREATE VIEW, put repeated multi-step logic in a stored procedure called with CALL, and use REGEXP_LIKE and TIMESTAMPDIFF for pattern and date arithmetic.

Topic: Databases · Tested on: Ubuntu 24.04 and 22.04, Debian 12 and 13, Rocky Linux 9, AlmaLinux 9 · Updated 2026-12-03

What do you need to follow along?

A MySQL 8.0 or 8.4 server and an account that can create tables, views and routines in one database. Install it with the MySQL 8 guide, then create a scratch database and a user for it:

sudo mysql
CREATE DATABASE store CHARACTER SET utf8mb4;
CREATE USER 'deploy'@'localhost' IDENTIFIED BY 'Pick-A-Long-Passphrase';
GRANT ALL PRIVILEGES ON store.* TO 'deploy'@'localhost';
EXIT;
mysql -u deploy -p store

ALL PRIVILEGES on the database includes CREATE VIEW, CREATE ROUTINE, ALTER ROUTINE and EXECUTE. On servers with binary logging enabled (the default in MySQL 8), creating functions may also require log_bin_trust_function_creators; procedures do not. More on narrowing grants is in MySQL users and privileges.

How do you store and read JSON in MySQL?

Use the JSON type: MySQL validates the document on insert, stores it in a binary format and lets you pull out values with path expressions.

CREATE TABLE items (
  id    INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  name  VARCHAR(100) NOT NULL,
  spec  JSON NOT NULL
);
INSERT INTO items (name, spec) VALUES
  ('Starter', '{"cpu": 1, "ram_gb": 2, "disk": {"type": "ssd", "gb": 55}, "tags": ["linux", "small"]}'),
  ('Builder', '{"cpu": 4, "ram_gb": 8, "disk": {"type": "nvme", "gb": 180}, "tags": ["nvme", "ci"]}');

SELECT name, spec->>'$.disk.type' AS disk, spec->'$.ram_gb' AS ram FROM items;
SELECT name FROM items WHERE spec->>'$.disk.type' = 'nvme';
SELECT name FROM items WHERE JSON_CONTAINS(spec->'$.tags', '"ci"');

-> returns a JSON value (strings keep their quotes); ->> unquotes it, which is what you want for comparisons and display. Change documents in place with the JSON functions:

UPDATE items SET spec = JSON_SET(spec, '$.ram_gb', 16) WHERE name = 'Builder';
UPDATE items SET spec = JSON_ARRAY_APPEND(spec, '$.tags', 'fast') WHERE id = 2;
UPDATE items SET spec = JSON_REMOVE(spec, '$.tags[1]') WHERE id = 1;

How do you index fields inside a JSON column?

JSON columns cannot be indexed directly, so add a generated column for a scalar field or a multi-valued index for an array, then query in a way the optimizer can match.

ALTER TABLE items
  ADD COLUMN disk_type VARCHAR(10) GENERATED ALWAYS AS (spec->>'$.disk.type') VIRTUAL,
  ADD INDEX idx_disk_type (disk_type);

ALTER TABLE items ADD INDEX idx_tags ((CAST(spec->'$.tags' AS CHAR(20) ARRAY)));
SELECT name FROM items WHERE 'ci' MEMBER OF (spec->'$.tags');
EXPLAIN SELECT name FROM items WHERE 'ci' MEMBER OF (spec->'$.tags');

A VIRTUAL generated column takes no row storage; only its index does. Multi-valued indexes serve MEMBER OF, JSON_CONTAINS and JSON_OVERLAPS. Check the key column in EXPLAIN as explained in keys and indexes.

To turn a JSON array into rows for joins and reports, JSON_TABLE does the job:

SELECT i.name, t.tag
FROM items i,
JSON_TABLE(i.spec, '$.tags[*]' COLUMNS (tag VARCHAR(20) PATH '$')) AS t;

How do you create and manage views?

A view stores a SELECT under a name; queries against it always read live data. Use views to hide join logic from applications or to give a reporting account access to selected columns only.

CREATE OR REPLACE VIEW item_summary AS
SELECT id, name,
       spec->>'$.cpu'        AS cpu,
       spec->>'$.ram_gb'     AS ram_gb,
       spec->>'$.disk.type'  AS disk_type
FROM items;

SELECT * FROM item_summary WHERE disk_type = 'nvme';
SHOW CREATE VIEW item_summary\G
GRANT SELECT ON store.item_summary TO 'reports'@'localhost';

By default a view runs with the privileges of its definer (SQL SECURITY DEFINER), which is what lets the reporting account read it without access to items. Add WITH CHECK OPTION to an updatable view if inserts through it must satisfy its WHERE clause. Drop a view with DROP VIEW item_summary;; the base tables stay untouched.

How do you write a stored procedure?

Change the client delimiter so semicolons inside the body do not end the statement, define the procedure with IN and OUT parameters, then call it.

DELIMITER //
CREATE PROCEDURE upgrade_ram(IN p_item INT UNSIGNED, IN p_gb INT, OUT p_old INT)
BEGIN
  DECLARE EXIT HANDLER FOR SQLEXCEPTION
  BEGIN
    ROLLBACK;
    RESIGNAL;
  END;

  START TRANSACTION;
  SELECT spec->>'$.ram_gb' INTO p_old FROM items WHERE id = p_item FOR UPDATE;
  IF p_old IS NULL THEN
    SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'item not found';
  END IF;
  UPDATE items SET spec = JSON_SET(spec, '$.ram_gb', p_gb) WHERE id = p_item;
  COMMIT;
END //
DELIMITER ;

CALL upgrade_ram(1, 4, @old);
SELECT @old AS previous_ram;

The handler rolls back and re-raises any error, so callers see the real message and no half-finished change remains. List and inspect routines with SHOW PROCEDURE STATUS WHERE Db = 'store'; and SHOW CREATE PROCEDURE upgrade_ram\G. Procedures are stored in the database, so dump them with mysqldump --routines, as covered in backup and restore.

How do you match text patterns with REGEXP?

Use REGEXP (or REGEXP_LIKE()) to filter rows by a regular expression, and REGEXP_REPLACE, REGEXP_SUBSTR and REGEXP_INSTR to transform or extract text. MySQL 8 uses the ICU library, so Unicode and most familiar syntax work.

CREATE TABLE contacts (id INT AUTO_INCREMENT PRIMARY KEY, email VARCHAR(190), phone VARCHAR(40));
INSERT INTO contacts (email, phone) VALUES
  ('ops@example.net', '+351 21 000 1234'), ('bad-address', '(555) 010-0199');

SELECT email FROM contacts WHERE email REGEXP '^[^@ ]+@[^@ ]+\\.[a-z]{2,}$';
SELECT email FROM contacts WHERE NOT REGEXP_LIKE(email, '@');
SELECT phone, REGEXP_REPLACE(phone, '[^0-9+]', '') AS digits FROM contacts;
SELECT REGEXP_SUBSTR(email, '@.*$') AS domain FROM contacts;

In SQL string literals a backslash must be doubled, so \\. matches a literal dot. Matching is case-insensitive under the default collation; pass 'c' as the match type in REGEXP_LIKE(email, pattern, 'c') for a case-sensitive test. Regular expressions cannot use an ordinary index, so combine them with an indexed condition on large tables.

How do you calculate differences between dates?

TIMESTAMPDIFF(unit, start, end) returns the whole number of units between two dates or datetimes; units include SECOND, MINUTE, HOUR, DAY, WEEK, MONTH and YEAR.

SELECT TIMESTAMPDIFF(DAY, '2026-11-01', '2026-12-03') AS days;          -- 32
SELECT TIMESTAMPDIFF(MONTH, '2026-01-31', '2026-02-28') AS months;     -- 0
SELECT TIMESTAMPDIFF(MINUTE, created_at, NOW()) AS age_min FROM customers LIMIT 5;

SELECT name, TIMESTAMPDIFF(DAY, NOW(), expires_at) AS days_left
FROM subscriptions
WHERE expires_at < NOW() + INTERVAL 7 DAY;

Results are truncated, not rounded, which explains the second line. For simple day counts DATEDIFF(end, start) also works, and DATE_ADD or the + INTERVAL form shifts dates. Keep the server and session time zone consistent (UTC is the easy choice) so NOW() means the same thing everywhere; see time zone and time sync. The customers and subscriptions tables are placeholders for your own schema.

When should logic live in the database rather than the app?

Put logic in the database when several applications must enforce the same rule or when a multi-step change has to be atomic close to the data; keep it in the application when it changes often or needs external services.

Views are low risk and easy to version. Procedures are useful for batch jobs and data fixes, but they are harder to test and review than application code, so keep them short, store their source in your repository and deploy them with migrations. JSON columns suit flexible attributes; anything you join on, constrain or report on regularly deserves a real column. If MariaDB is your server, most of this works too, but JSON is stored as text there and some functions differ, so check the MariaDB guide.

Plans that fit this guide

Base city prices. Every plan includes a dedicated IPv4 address, IPv6, full root and all 18 images.

All prices
PlanFits becauseSizeMonthlyOrder from
A1-2development and small stores1 vCPU, 2 GB RAM, 50 GB NVMe$7.20/mo$43.20 for 6 months
A2-4busier apps with JSON indexes2 vCPU, 4 GB RAM, 100 GB NVMe$14.40/mo$43.20 for 3 months

Questions about MySQL JSON, views and stored procedures

What is the difference between -&gt; and -&gt;&gt;?

-> is short for JSON_EXTRACT and returns JSON, so strings keep their quotes. ->> also applies JSON_UNQUOTE, returning plain text for comparisons and output.

Can I put a full JSON column in an index?

No. Index individual paths through a generated column, or array elements through a multi-valued index with CAST(... AS ... ARRAY).

Why does my procedure fail with a syntax error at END?

The client ended the statement at the first semicolon. Set DELIMITER // before CREATE PROCEDURE and switch back with DELIMITER ; afterwards. GUI tools often handle this for you.

Are views slower than writing the query out?

Usually not. MySQL merges simple views into the outer query. Views with GROUP BY, DISTINCT or aggregates may be materialised into a temporary table, so check with EXPLAIN.

Does REGEXP use indexes?

No. It reads every candidate row. Narrow rows first with an indexed condition, or use a FULLTEXT index for word searches.