Use MySQL JSON Column Type for Flexible Metadata in WordPress Plugin Tables

A JSON column for flexible data in a WordPress plugin table

Some data has no fixed shape. The answers to a quiz depend on the questions: a choice here, a free text there, a rating somewhere else. Stored as post meta, one response becomes 50 rows in wp_postmeta. A custom table with a JSON column stores it as one row, and MySQL can still read single values out of it and even index them.

Problem: A quiz plugin stores every answer as a separate post meta row. A results page for one quiz with 2,000 responses loads 100,000 meta rows, and a top-10 list by score takes seconds.

Solution: Create a table with one row per response, put the variable answers in a JSON column, copy the score into a generated column with an index for sorting, and read and update single fields with JSON_EXTRACT() and JSON_SET().

The table

CREATE TABLE wp_quiz_responses (
    id           BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    quiz_id      BIGINT UNSIGNED NOT NULL,
    user_id      BIGINT UNSIGNED DEFAULT NULL,
    submitted_at DATETIME NOT NULL,
    data         JSON NOT NULL,
    score        DECIMAL(6,2) AS (JSON_UNQUOTE(JSON_EXTRACT(data, '$.score'))) STORED,
    PRIMARY KEY (id),
    KEY quiz_score (quiz_id, score),
    KEY user_id (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

The JSON type exists since MySQL 5.7.8. MySQL validates the document on insert and stores it in a binary format, so reading one key does not parse the whole text. In MariaDB, JSON is an alias for LONGTEXT with a validity check; the functions below work the same there. The shorter data->>'$.score' syntax is MySQL only, so the examples use JSON_UNQUOTE(JSON_EXTRACT()), which runs on both.

The generated column score is computed from the JSON on every insert and update. With an index on (quiz_id, score), a ranking per quiz is read from the index instead of extracting the score from every row.

dbDelta() does not know generated columns and would report the table as changed on every run, so in the plugin the table is created once with a version check:

function ha_quiz_install(): void {
    global $wpdb;
    if ( get_option( 'ha_quiz_db_version' ) === '1' ) {
        return;
    }
    $table = $wpdb->prefix . 'quiz_responses';
    $wpdb->query( "CREATE TABLE IF NOT EXISTS {$table} ( /* columns as above */ ) {$wpdb->get_charset_collate()}" );
    update_option( 'ha_quiz_db_version', '1', false );
}

Insert a response from PHP

global $wpdb;
$wpdb->insert(
    $wpdb->prefix . 'quiz_responses',
    array(
        'quiz_id'      => $quiz_id,
        'user_id'      => get_current_user_id() ?: null,
        'submitted_at' => current_time( 'mysql', true ),
        'data'         => wp_json_encode( array(
            'score'    => 85.5,
            'duration' => 142,
            'answers'  => array(
                'q1' => array( 'type' => 'choice', 'selected' => 'B', 'correct' => true ),
                'q2' => array( 'type' => 'text', 'value' => 'WordPress is a CMS' ),
            ),
        ) ),
    ),
    array( '%d', '%d', '%s', '%s' )
);

wp_json_encode() creates the document; the generated column is not part of the insert.

Read and update single fields

-- top 10 of a quiz, uses the quiz_score index
SELECT id, user_id, score
FROM wp_quiz_responses
WHERE quiz_id = 42
ORDER BY score DESC
LIMIT 10;

-- one answer out of the document
SELECT user_id,
       JSON_UNQUOTE(JSON_EXTRACT(data, '$.answers.q1.selected')) AS q1
FROM wp_quiz_responses
WHERE quiz_id = 42;

-- how many answered q1 wrong (JSON false, not the string 'false')
SELECT COUNT(*)
FROM wp_quiz_responses
WHERE quiz_id = 42
  AND JSON_EXTRACT(data, '$.answers.q1.correct') = CAST('false' AS JSON);

-- change one field in place
UPDATE wp_quiz_responses
SET data = JSON_SET(data, '$.reviewed', TRUE)
WHERE id = 1001;

Conditions on keys inside the JSON, like the q1 query, cannot use an index and read every row of the quiz. That is fine for a report, but values that are filtered or sorted often belong in a generated column with an index, as score above. The CAST('false' AS JSON) comparison works in MySQL; in MariaDB compare with JSON_EXTRACT(...) = 'false', because there the result is text.

NOTE: A JSON column is not a replacement for a schema. Fields that every row has (quiz, user, date) are normal columns, because they are filtered, joined and indexed. JSON is for the part that really differs from row to row. How the rest of a custom table is created and versioned: custom database table with dbDelta.