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:
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:
SELECT student_id,prefs->>'$.theme' AS theme,prefs->>'$.skills[0]' AS first_skillFROM profilesWHERE JSON_CONTAINS(prefs->'$.skills', '"python"');-- Update a single key in placeUPDATE 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:
ALTER TABLE profilesADD 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
- 01The JSON type stores validated, flexible semi-structured documents.
- 02Read JSON with ->>'$.path' / JSON_EXTRACT; search arrays with JSON_CONTAINS; edit with JSON_SET.
- 03ENUM stores one value from a fixed list; SET stores several — both need ALTER to extend.
- 04Generated columns compute from other columns and can be indexed — the way to make JSON fields fast.
- 05If a field is filtered constantly, make it a real column; reserve JSON for variable attributes.
