Skip to main content
Albero Academy

Advanced Data Types & JSON

Store semi-structured data in JSON columns, use ENUM/SET wisely, and compute columns automatically with generated columns.

Chapter 10MySQL15 min readBeginner friendly
  • #MySQL
  • #JSON
  • #Data Types

Not all data fits neatly in fixed columns. MySQL's JSON type stores flexible, semi-structured data; generated columns compute values automatically. Used judiciously, these bridge relational and document-style modelling in one database.

The JSON type

A JSON column stores a validated JSON document — handy for attributes that vary from row to row:

a JSON column
CREATE TABLE profiles (
student_id INT PRIMARY KEY,
prefs JSON
);
INSERT INTO profiles VALUES
(1, '{"theme": "dark", "skills": ["python","sql"], "newsletter": true}');

Querying JSON

Extract values with the ->> operator (unquoted text) or JSON_EXTRACT, and search arrays with JSON_CONTAINS:

reading inside JSON
SELECT student_id,
prefs->>'$.theme' AS theme,
prefs->>'$.skills[0]' AS first_skill
FROM profiles
WHERE JSON_CONTAINS(prefs->'$.skills', '"python"');
-- Update a single key in place
UPDATE profiles SET prefs = JSON_SET(prefs, '$.theme', 'light') WHERE student_id = 1;

ENUM & SET

  • ENUM('entry','mid','senior') — exactly one value from a fixed list; compact and self-documenting.
  • SET('python','sql','react') — several values from a fixed list in one column.

They're convenient, but adding a new option means an ALTER TABLE; for fast-changing lists, a lookup table is more flexible.

Generated columns

A generated column is computed from other columns automatically — and can be indexed, which is how you make a JSON field fast to query:

computed & indexed
ALTER TABLE profiles
ADD theme VARCHAR(20)
GENERATED ALWAYS AS (prefs->>'$.theme') STORED,
ADD INDEX idx_theme (theme); -- now theme is fast to filter

Practice

Add a prefs JSON column, insert a document, and query a nested value and an array element. Convert a status column to an ENUM. Add a generated column that extracts a JSON field and index it, then filter on it.

Key takeaways

  1. 01The JSON type stores validated, flexible semi-structured documents.
  2. 02Read JSON with ->>'$.path' / JSON_EXTRACT; search arrays with JSON_CONTAINS; edit with JSON_SET.
  3. 03ENUM stores one value from a fixed list; SET stores several — both need ALTER to extend.
  4. 04Generated columns compute from other columns and can be indexed — the way to make JSON fields fast.
  5. 05If a field is filtered constantly, make it a real column; reserve JSON for variable attributes.