Databases & SQL Master Course — 067. Schema Inspection
Lesson 067 Schema Inspection
Prerequisites and objectives
You can read table definitions, constraints, and STRICT declarations. This lesson turns the database into a source of evidence about its own schema. You will inspect columns, keys, foreign keys, indexes, and table options, then distinguish declared structure from data checks and application assumptions.
Create the practice fixture
Use a fresh SQLite database supporting STRICT tables and generated columns. The fixture contains a depot, a strict stock table, a generated doubled quantity, and an explicit index. This lesson’s inspection queries are read-only. Do not edit SQLite’s schema catalog directly; supported schema statements are covered in the next lesson.
PRAGMA foreign_keys=ON;
CREATE TABLE depots (depot_id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE inspected_stock (
stock_id INTEGER PRIMARY KEY,
sku TEXT NOT NULL UNIQUE,
depot_id INTEGER NOT NULL REFERENCES depots(depot_id),
units INTEGER NOT NULL CHECK(units>=0),
doubled INTEGER GENERATED ALWAYS AS (units*2) VIRTUAL
) STRICT;
CREATE INDEX idx_stock_depot ON inspected_stock(depot_id);
INSERT INTO depots VALUES (1,'North');
INSERT INTO inspected_stock(stock_id,sku,depot_id,units) VALUES (1,'P1',1,4);
Ask a specific metadata question
Schema inspection works best when each query answers a concrete question. What columns exist? Which ones are generated? Which key does this child reference? Is the table actually strict? A remembered migration file is useful context, but the connected database’s metadata tells you what is installed in that database.
Start with table_xinfo rather than table_info when generated or hidden columns may matter. Select named metadata fields so the report remains focused. The hidden flag is zero for ordinary columns, two for a virtual generated column, and three for a stored generated column in this context.
SELECT name,type,hidden FROM pragma_table_xinfo('inspected_stock') ORDER BY cid;
The report includes doubled even though the application does not supply it during INSERT. An inspection tool that reads only ordinary columns could miss a dependency before attempting to rename or remove units. Metadata is useful precisely because it exposes more than a normal SELECT of a few application fields.

Combine structure with defining SQL
Column metadata does not provide every CHECK expression as a convenient separate field. Read the table’s defining SQL from sqlite_schema when reviewing those rules. The catalog also records views, triggers, and indexes. Automatically created indexes for constraints may have no standalone SQL text, so an absent SQL string does not imply that the index is meaningless.
Use index_list to see index properties and index_info to inspect an index’s key columns. Do not infer a constraint’s business meaning solely from an automatically generated index name. The explicit idx_stock_depot index helps locate rows by depot, while the SKU uniqueness rule is a separate integrity guarantee.
Verify configuration and actual contents separately
A declared foreign key and an enabled enforcement setting are separate observations. Inspect foreign_key_list for the declared relationship, then foreign_keys for the connection setting. A foreign_key_check tests existing references and returns violation rows when it finds problems. An empty result is the expected success shape, not a row containing the word ok.
Integrity_check returns ok for the healthy fixture, but it is not a substitute for foreign_key_check. Nor does either command establish that every business rule was modeled correctly. A perfectly intact database can faithfully store a schema whose requirements were misunderstood. Technical integrity and domain correctness need complementary evidence.
Make inspection repeatable
Record the environment, SQLite version, inspected table, and exact question alongside metadata results. Specify ordering when comparing reports. Avoid relying on the ordinal positions of undocumented output fields or internal object naming patterns. Table-valued PRAGMA functions allow ordinary SELECT filtering and ordering for supported read-only pragmas.
These functions are SQLite-specific, with table-valued PRAGMA support introduced in version 3.16.0. The table_list metadata used here requires 3.37.0 or later, matching our strict-table baseline. Other engines expose their own catalogs or information-schema views; port the inspection question rather than assuming identical syntax.
Four worked exercises
Exercise 1
Confirm that the stock table is strict and report its full column count.
Worked solution
SELECT name,ncol,strict FROM pragma_table_list WHERE name='inspected_stock' AND schema='main';
The result reports five columns and strict equal to one. The count includes the generated doubled column. This verifies the installed option rather than merely trusting the original CREATE statement in a notebook.
Exercise 2
Inspect the declared foreign-key mapping and the current enforcement setting.
Worked solution
SELECT "table","from","to" FROM pragma_foreign_key_list('inspected_stock') ORDER BY id,seq;
PRAGMA foreign_keys;
The child depot_id references depots.depot_id, and this connection has enforcement enabled. The double-quoted metadata names avoid ambiguity with SQL keywords. Both observations are needed before relying on the relationship during writes.
Exercise 3
Find the explicit depot index’s key column and inspect whether its index entry is unique.
Worked solution
SELECT name FROM pragma_index_info('idx_stock_depot') ORDER BY seqno;
SELECT name,"unique" FROM pragma_index_list('inspected_stock') WHERE name='idx_stock_depot';
The index keys depot_id and is not unique. Several stock rows may belong to one depot. An index can support access without imposing a uniqueness rule; do not describe every index as a candidate key.
Exercise 4
Check current references and structural integrity, then confirm the defining SQL includes the quantity check.
Worked solution
PRAGMA foreign_key_check;
PRAGMA integrity_check;
SELECT instr(sql,'CHECK(units>=0)')>0 FROM sqlite_schema WHERE type='table' AND name='inspected_stock';
The reference check finds no violations, integrity reports ok, and the fixture’s defining SQL includes the expected CHECK. The string test is a narrow fixture assertion, not a robust general SQL parser; formatting differences can change such a text match.
Knowledge check
Question 1
Why use table_xinfo for this fixture?
- It returns CREATE TABLE SQL for every dependency
- It includes the generated column
- It validates all stored generated values
- It only shows primary-key columns
Answer and explanation
B. The fuller column report exposes generated and hidden-column metadata.
Question 2
What does an empty foreign_key_check result mean?
- No foreign-key violations were reported
- The database has no tables
- All business rules are proven correct
- Foreign-key enforcement is necessarily off
Answer and explanation
A. It is a data-validation result with a particular success shape.
Question 3
What does the explicit nonunique depot index allow?
- Only one stock row per depot
- Only one depot in the database
- NULL in every required column
- Several stock rows for the same depot
Answer and explanation
D. Access support and uniqueness are distinct index properties.
Question 4
Where can the table’s CHECK expression be reviewed?
- The notnull field from table_info
- The key-column list from index_info
- Its defining SQL in sqlite_schema
- The foreign-key list for the table
Answer and explanation
C. Catalog SQL complements the structured column and relationship metadata.
Question 5
Why inspect the current database rather than only a migration file?
- A successful migration proves the schema can never change later
- Reading metadata repairs any missing constraints
- Sample rows completely describe the declared constraints
- Installed schema can differ from intended schema
Answer and explanation
D. Inspection establishes the actual connected environment’s structure.
Pitfalls and summary
Do not confuse metadata, connection settings, and data validation. Select the inspection tool that answers the question, include generated columns when relevant, and read defining SQL for rules not exposed separately. Healthy technical checks support confidence, but they cannot prove that the schema represents the right business model.
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
- SQLite PRAGMA reference: Read-only schema and integrity inspection
- SQLite schema table: Catalog objects and defining SQL