smartyfy.mrindigi.com

Databases & SQL Master Course — 100. Text Date and JSON Practice Lab

Lesson 100 Text Date and JSON Practice Lab

Prerequisites and objectives

Combine text cleaning, calendar validation, JSON type inspection, and reject reporting. You will safely inspect mixed-quality payloads, preserve a strict integer quantity contract, produce accepted business rows and an exception report, and reconcile the complete batch without silently losing malformed documents.

Define the lab contract and create the fixture

Each accepted payload must be a strict JSON object. SKU must be text and nonblank after ordinary-space trimming. Quantity must be a JSON integer from zero through one thousand, not a numeric-looking string or boolean. Day must be an exact valid calendar-date string under the tested round-trip rule.

Use a fresh SQLite database. The view first substitutes an empty object only as a safe parsing input for invalid JSON; it retains the original payload and validity result. That substitute is not accepted data and does not repair the malformed document. All displayed queries are read-only.

CREATE TABLE mixed_payloads (source_id INTEGER PRIMARY KEY,payload TEXT NOT NULL);
INSERT INTO mixed_payloads VALUES
 (1,'{"sku":" P1 ","qty":2,"day":"2026-10-01"}'),
 (2,'{"sku":"P2","qty":"2","day":"2026-10-01"}'),
 (3,'broken'),(4,'{"sku":" ","qty":3,"day":"2026-10-01"}'),
 (5,'{"sku":"P5","qty":0,"day":"2026-02-30"}'),
 (6,'{"sku":"P6","qty":1,"day":"2026-10-02"}'),
 (7,'{"sku":"P7","qty":null,"day":"2026-10-03"}'),(8,'[]');
CREATE VIEW reviewed_payloads AS
WITH safe AS (SELECT source_id,payload,json_valid(payload) AS valid,
 CASE WHEN json_valid(payload)=1 THEN payload ELSE '{}' END AS safe_payload FROM mixed_payloads),
fields AS (SELECT source_id,payload,valid,json_type(safe_payload) AS root_type,
 json_type(safe_payload,'$.sku') AS sku_type,json_type(safe_payload,'$.qty') AS qty_type,
 json_type(safe_payload,'$.day') AS day_type,trim(json_extract(safe_payload,'$.sku')) AS sku,
 json_extract(safe_payload,'$.qty') AS qty,json_extract(safe_payload,'$.day') AS day FROM safe)
SELECT *,CASE WHEN valid<>1 THEN 'invalid_json'
 WHEN root_type<>'object' THEN 'expected_object'
 WHEN sku_type IS NOT 'text' OR length(sku)=0 THEN 'invalid_sku'
 WHEN qty_type IS NOT 'integer' OR qty<0 OR qty>1000 THEN 'invalid_quantity'
 WHEN day_type IS NOT 'text' OR length(day)<>10 OR day NOT GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]' OR date(day,'+0 days') IS NULL OR date(day,'+0 days')<>day THEN 'invalid_day'
 ELSE NULL END AS reject_reason FROM fields;

Separate safe parsing from acceptance

The safe CTE ensures extraction functions never receive malformed JSON text in this fixture. The fields CTE exposes root type, field types, and proposed scalar values. The final CASE applies a deterministic first-reason policy. Each layer has one responsibility, making the pipeline easier to inspect and test.

Do not classify the safe replacement object as a real source object. The original valid flag is checked first, so broken remains invalid_json. This preserves the distinction between a malformed document and a valid empty object missing required fields.

SELECT source_id,COALESCE(reject_reason,'accepted') FROM reviewed_payloads ORDER BY source_id;
Deterministic first outcome for each JSON source row
Source Outcome
1 accepted
2 invalid_quantity
3 invalid_json
4 invalid_sku
5 invalid_day
6 accepted
7 invalid_quantity
8 expected_object
A syntax check, safe parse and contract classification retain all eight source rows. Only rows 1 and 6 are accepted with quantities 2 and 1; broken remains invalid_json.
Safe parsing prevents crashes while preserving the original acceptance decision. Open full-size diagram

Protect type meaning before coercion

Row two contains a string quantity, so it is rejected even though its characters look like the number two. Row seven contains explicit JSON null. Both fail the integer contract for different source reasons. A more detailed exception model could retain those subtypes while still using one broad quantity category here.

JSON booleans also need attention: SQLite scalar extraction represents true as integer one, but json_type reports true rather than integer. Checking source JSON type prevents a boolean from being accidentally accepted as a one-unit quantity.

Keep transformations narrow and explainable

Trimming row one’s padded SKU is explicitly allowed. Converting its date to a different day is not. The invalid February date is rejected because normalization would change its calendar meaning. Likewise, inventing a quantity for an explicit null would create an unsupported fact.

The accepted output is a proposal for a later load, not a published record. A destination may still require SKU existence, uniqueness, a source-batch idempotency key, and transaction handling. This lab establishes only the documented shape, type, range, and calendar contract.

Reconcile and preserve evidence

The eight source identifiers must remain accounted for in the review result. Accepted and rejected sets should be disjoint and exhaustive. Keep raw payloads so a reviewer can explain why a row failed and compare a corrected resubmission without guessing what the original document contained.

Version the rules when using this design operationally. A change from integer-only to numeric-string acceptance is a material contract change, not a harmless refactor. Store enough provenance to distinguish changed data from changed validation policy when a rerun produces a different outcome.

Review the remaining limitations

This fixture does not implement a complete JSON Schema validator, duplicate-object-key policy, authorization model, or production ingestion system. Extra keys are allowed by the shown rules. The date validation is tied to a tested SQLite representation and should be rechecked when porting to another database.

The following modules examine PostgreSQL and MySQL semantics. Carry the acceptance requirements with you, but do not assume that identically named JSON or date functions return the same SQL types. Porting should preserve the business contract and explicitly test each engine’s behavior.

Four worked exercises

Exercise 1

Produce the accepted relational projection.

Worked solution
SELECT source_id,sku,qty,day FROM reviewed_payloads WHERE reject_reason IS NULL ORDER BY source_id;

Only rows one and six qualify. The projection retains source identity and the normalized SKU alongside typed quantity and day. It does not discard the original payload stored in the staging table.

Exercise 2

Summarize rejected source rows by primary reason.

Worked solution
SELECT reject_reason,COUNT(*) FROM reviewed_payloads WHERE reject_reason IS NOT NULL GROUP BY reject_reason ORDER BY reject_reason;

There are six rejected sources: two quantity failures and one in each other category. The report counts primary outcomes, not every possible rule violation inside each payload.

Exercise 3

Verify full batch coverage and the accepted quantity total.

Worked solution
SELECT COUNT(*),SUM(CASE WHEN reject_reason IS NULL THEN 1 ELSE 0 END),SUM(CASE WHEN reject_reason IS NOT NULL THEN 1 ELSE 0 END) FROM reviewed_payloads;
SELECT SUM(qty) FROM reviewed_payloads WHERE reject_reason IS NULL;

Two accepted plus six rejected accounts for all eight source rows. The accepted quantity total is three units. The total is a useful control but cannot replace inspecting which source identifiers were accepted.

Exercise 4

Demonstrate why JSON source type must be checked before accepting extracted integer-looking values.

Worked solution
SELECT json_extract('{"qty":true}','$.qty'),typeof(json_extract('{"qty":true}','$.qty')),json_type('{"qty":true}','$.qty');

The extracted value is SQL integer one, but the JSON type is true. An ingestion rule checking only the SQL storage class would accept a boolean incorrectly. Source-type and resulting-SQL-type checks answer different questions.

Knowledge check

Question 1

Why retain the original validity flag after substituting a safe object?

  1. To claim the replacement is the original document
  2. To keep malformed source JSON rejected
  3. To make every payload accepted
  4. To treat a substituted empty object as a valid missing-fields case
Answer and explanation

B. Safe parsing must not erase the evidence of invalid input.

Question 2

Why is the string quantity two rejected?

  1. Two exceeds the maximum
  2. JSON strings are always invalid JSON
  3. A numeric-looking JSON string satisfies the integer token rule
  4. The contract requires a JSON integer
Answer and explanation

D. Syntax-valid data can still violate the field-type contract.

Question 3

Why inspect json_type for a boolean quantity?

  1. JSON true always extracts as text true
  2. The integer storage class proves the token was not a boolean
  3. Extraction can represent true as SQL integer one
  4. typeof proves the original JSON token type
Answer and explanation

C. The source token type carries information that scalar extraction can blur.

Question 4

What does the rejection summary count?

  1. Primary outcomes per rejected source row
  2. Every failed rule in each document
  3. Only malformed JSON syntax
  4. The number of distinct invalid fields across the batch
Answer and explanation

A. The CASE policy reports one first reason per source.

Question 5

What remains before loading an accepted row into a real destination?

  1. Nothing because JSON validity is sufficient
  2. A guarantee that every accepted SKU already exists
  3. Only formatting the accepted fields as display text
  4. Destination integrity, idempotency, and authorized workflow checks
Answer and explanation

D. This lab’s acceptance scope is deliberately limited.

Pitfalls and summary

Do not let safe parsing become silent repair or let scalar coercion erase source-type distinctions. Keep raw evidence, apply a versioned acceptance contract, and reconcile every source row. The result is a reproducible review pipeline whose limits are clear enough to carry into another database dialect.

SQLite behavior and references

Examples were checked with SQLite 3.53.1 on 10 October 2026. Use a SQLite SQL editor; Python is not a prerequisite. Verify dialect-specific functions, comparison rules, and numeric behavior before moving the examples to another engine.

Primary references