SQL Challenger
0 of 250 complete

Lessons

0 of 250 complete

Saved in this browser

Lesson 152 of 250

Hard

Add a cleaned channel field to receipt JSON

Your task

Return receipt ID and enriched_metadata. Use JSON_SET to add the channel field to each metadata object with a lowercase, trimmed channel value. Preserve existing fields and sort by ID.

JSON_SET can produce updated JSON in a result column while the stored document remains available.

Sample data

Table:receipts
idsold_onamountchannelmetadata
12025-01-0136 ONLINE {"currency":"EUR","tags":["gift","jazz"]}
22025-01-1622Store{"currency":"EUR","tags":["indie"]}
32025-01-3154 online{"currency":"EUR","tags":["returning","bundle"]}
42025-03-0438STORE {"currency":"EUR","tags":[]}
52025-04-0944Online{"currency":"EUR","tags":["indie"]}

Expected output

idenriched_metadata
1{"currency":"EUR","tags":["gift","jazz"],"channel":"online"}
2{"currency":"EUR","tags":["indie"],"channel":"store"}
3{"currency":"EUR","tags":["returning","bundle"],"channel":"online"}
4{"currency":"EUR","tags":[],"channel":"store"}
5{"currency":"EUR","tags":["indie"],"channel":"online"}
Show a hint

Pass the original document, the path $.channel, and LOWER(TRIM(channel)) to JSON_SET.

Dates, text, and JSON guide

Work with dates as ISO text

The receipt dates use YYYY-MM-DD, so their text order matches calendar order. Use an inclusive start and exclusive end for periods. This query returns receipts in the first quarter, without including April 1.

SELECT id, sold_on, amount
FROM receipts
WHERE sold_on >= '2025-01-01'
  AND sold_on < '2025-04-01';

Normalize values before comparing them

The receipt channel values vary in capitalization and spacing. TRIM removes surrounding spaces and LOWER handles these ASCII names. Use the same normalization when grouping values that represent the same category.

SELECT LOWER(TRIM(channel)) AS channel, COUNT(*) AS receipts
FROM receipts
GROUP BY LOWER(TRIM(channel));

Extract a field or expand an array

JSON_EXTRACT reads a value at a path, such as the currency code. JSON_EACH turns an array into rows with a value column. After expansion, receipt IDs can repeat and a receipt with no tags contributes no rows.

SELECT r.id, JSON_EXTRACT(r.metadata, '$.currency') AS currency,
       tag.value AS tag
FROM receipts AS r
CROSS JOIN JSON_EACH(r.metadata, '$.tags') AS tag;
SQLiteCtrl / ⌘ + Enter

Press Control+Space for SQL suggestions. Use the arrow keys to select an option and Enter to insert it.

Results

Loading SQLite…