The Concept
Schema introspection with information_schema
Every SQL database keeps a catalog of its own tables, but not under the same name. information_schema is the SQL-standard view of it, and PostgreSQL, MySQL and SQL Server all provide one. Oracle uses its own views (ALL_TABLES, ALL_TAB_COLUMNS), and SQLite has sqlite_master plus PRAGMA table_info. In PostgreSQL you query information_schema to discover tables, columns, types and constraints without a DBA or documentation.
# Schema introspection: discover all tables and columns in an undocumented database
import psycopg2
conn = psycopg2.connect("postgresql://user:pass@client-db:5432/legacy_prod")
cur = conn.cursor()
# Step 1: List all tables and row counts
cur.execute("""
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public'
ORDER BY table_name;
""")
tables = cur.fetchall()
print(f"Found {len(tables)} tables in public schema")
# Step 2: For each table, get columns, types, and nullability
for (table_name,) in tables[:5]: # Show first 5 for brevity
cur.execute("""
SELECT column_name, data_type, is_nullable, column_default
FROM information_schema.columns
WHERE table_name = %s
ORDER BY ordinal_position;
""", (table_name,))
columns = cur.fetchall()
print(f"\n{table_name} ({len(columns)} columns):")
for col_name, col_type, nullable, default in columns:
null_str = "NULL" if nullable == "YES" else "NOT NULL"
default_str = f" DEFAULT {default}" if default else ""
print(f" {col_name}: {col_type} {null_str}{default_str}")
# Step 3: Discover existing foreign key constraints
cur.execute("""
SELECT
tc.table_name, kcu.column_name,
ccu.table_name AS foreign_table_name,
ccu.column_name AS foreign_column_name
FROM information_schema.table_constraints tc
JOIN information_schema.key_column_usage kcu
ON tc.constraint_name = kcu.constraint_name
JOIN information_schema.constraint_column_usage ccu
ON tc.constraint_name = ccu.constraint_name
WHERE tc.constraint_type = 'FOREIGN KEY';
""")
fks = cur.fetchall()
print(f"\n\nFound {len(fks)} foreign key constraints:")
for fk in fks:
print(f" {fk[0]}.{fk[1]} → {fk[2]}.{fk[3]}")
Discovering hidden relationships
When foreign key constraints don't exist (common in legacy databases), you discover relationships by matching column names and validating with join queries.
# Discover hidden foreign key relationships without constraints
def discover_relationships(cur, table_a, table_b):
"""Find columns that might link two tables based on name matching."""
# Get columns for both tables
cur.execute("""
SELECT column_name, data_type FROM information_schema.columns
WHERE table_name = %s ORDER BY ordinal_position;
""", (table_a,))
cols_a = cur.fetchall()
cur.execute("""
SELECT column_name, data_type FROM information_schema.columns
WHERE table_name = %s ORDER BY ordinal_position;
""", (table_b,))
cols_b = cur.fetchall()
# Match by naming convention: a column in A that starts with B's stem.
# tbl_cust_master -> "cust", which matches cust_id in tbl_orders_v2.
# (The full name, "cust_master", would match nothing.)
stem = table_b.removeprefix("tbl_").split("_")[0]
potential_links = []
for col_a_name, col_a_type in cols_a:
for col_b_name, col_b_type in cols_b:
# Check if column in A references B by name
if stem in col_a_name.lower() and col_a_type == col_b_type:
# Validate with actual join
try:
cur.execute(f"""
SELECT COUNT(*) FROM {table_a} a
JOIN {table_b} b ON a.{col_a_name} = b.{col_b_name}
WHERE a.{col_a_name} IS NOT NULL;
""")
join_count = cur.fetchone()[0]
if join_count > 0:
potential_links.append({
"column": col_a_name,
"references": f"{table_b}.{col_b_name}",
"type": col_a_type,
"join_rows": join_count,
"confidence": "HIGH" if join_count > 100 else "MEDIUM",
})
except Exception:
conn.rollback() # Type mismatch or other error
return potential_links
# Example: find relationships between orders and customers
rels = discover_relationships(cur, "tbl_orders_v2", "tbl_cust_master")
print("Discovered relationships:")
for r in rels:
print(f" {r['column']} → {r['references']} ({r['type']}, {r['join_rows']} join rows, {r['confidence']})")
Recursive CTEs for hierarchical data
Enterprise databases always have hierarchical data: org charts, bill-of-materials, category trees. Recursive CTEs traverse these hierarchies in a single query.
-- Recursive CTE: traverse an org chart from any employee up to the CEO
WITH RECURSIVE org_chain AS (
-- Base case: start with a specific employee
SELECT employee_id, employee_name, manager_id, 1 AS level
FROM employees
WHERE employee_id = 42 -- Start from employee #42
UNION ALL
-- Recursive case: join to find the manager
SELECT e.employee_id, e.employee_name, e.manager_id, oc.level + 1
FROM employees e
JOIN org_chain oc ON e.employee_id = oc.manager_id
)
SELECT employee_id, employee_name, level, manager_id
FROM org_chain
ORDER BY level DESC; -- CEO at top, employee at bottom
-- Recursive CTE: bill-of-materials explosion
-- Find all components needed to build product X (including sub-assemblies)
WITH RECURSIVE bom_explosion AS (
-- Base case: top-level product. A recursive CTE takes its column names
-- from this first SELECT, so total_quantity has to be named here.
SELECT component_id, component_name, parent_id, quantity AS total_quantity, 1 AS level
FROM bill_of_materials
WHERE parent_id = 'PROD-X'
UNION ALL
-- Recursive case: a sub-component's count multiplies by its parent's total
SELECT b.component_id, b.component_name, b.parent_id,
b.quantity * be.total_quantity, be.level + 1
FROM bill_of_materials b
JOIN bom_explosion be ON b.parent_id = be.component_id
)
SELECT component_id, component_name, total_quantity, level
FROM bom_explosion
ORDER BY level, component_name;
# Execute recursive CTE from Python
cur.execute("""
WITH RECURSIVE category_tree AS (
SELECT category_id, category_name, parent_category_id, 1 AS depth,
category_name::TEXT AS path
FROM categories
WHERE parent_category_id IS NULL
UNION ALL
SELECT c.category_id, c.category_name, c.parent_category_id, ct.depth + 1,
ct.path || ' > ' || c.category_name
FROM categories c
JOIN category_tree ct ON c.parent_category_id = ct.category_id
)
SELECT category_id, category_name, depth, path
FROM category_tree
ORDER BY path;
""")
tree = cur.fetchall()
print("Category Tree:")
for cat_id, name, depth, path in tree:
indent = " " * (depth - 1)
print(f"{indent}{name} (id={cat_id}, depth={depth})")
print(f"{indent} path: {path}")
Window functions for data profiling
-- Data profiling with window functions
-- 1. Find duplicate records using ROW_NUMBER
SELECT * FROM (
SELECT
customer_id, email, created_at,
ROW_NUMBER() OVER (PARTITION BY email ORDER BY created_at) AS dup_rank
FROM tbl_cust_master
) t WHERE dup_rank > 1;
-- Returns all duplicate email records, oldest first
-- 2. Detect data drift: compare consecutive values with LAG
SELECT
date, daily_revenue,
LAG(daily_revenue, 1) OVER (ORDER BY date) AS prev_day_revenue,
daily_revenue - LAG(daily_revenue, 1) OVER (ORDER BY date) AS daily_change,
ROUND(
(daily_revenue - LAG(daily_revenue, 1) OVER (ORDER BY date))
/ NULLIF(LAG(daily_revenue, 1) OVER (ORDER BY date), 0) * 100, 2
) AS pct_change
FROM daily_revenue_summary
ORDER BY date DESC
LIMIT 30;
-- 3. Percentile analysis: find the 95th percentile response time
SELECT
PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY response_time_ms) AS p95_response,
PERCENTILE_CONT(0.50) WITHIN GROUP (ORDER BY response_time_ms) AS median_response,
PERCENTILE_CONT(0.99) WITHIN GROUP (ORDER BY response_time_ms) AS p99_response,
AVG(response_time_ms) AS avg_response,
COUNT(*) AS total_requests
FROM api_request_logs
WHERE request_date >= '2026-01-01';
-- 4. Running total and moving average
SELECT
date,
daily_revenue,
SUM(daily_revenue) OVER (ORDER BY date) AS running_total,
AVG(daily_revenue) OVER (
ORDER BY date
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS seven_day_moving_avg
FROM daily_revenue_summary
ORDER BY date DESC;
Build
Practical application
The graded lab is the naming-convention step on its own: you write guess_foreign_keys(), which proposes foreign-key candidates from two lists of columns and types. The optional extension takes the rest of this lesson to a real database: point it at a PostgreSQL database you can reach (we don't supply one), recover the schema with information_schema, confirm the relationships with joins, and profile the data with recursive CTEs and window functions. The extension isn't graded automatically.
Try it yourself: match candidate foreign-key columns across two table schemas by naming convention and type.
table_a_columns = [
("order_id", "integer"), ("cust_id", "integer"), ("order_date", "date"), ("notes", "text"),
]
table_b_columns = [
("customer_id", "integer"), ("customer_name", "text"), ("region", "text"),
]
def guess_foreign_keys(cols_a, table_b_name, cols_b):
stem = table_b_name.replace("tbl_", "").rstrip("s")
candidates = []
for name_a, type_a in cols_a:
for name_b, type_b in cols_b:
if stem in name_a.lower() and type_a == type_b:
candidates.append((name_a, f"{table_b_name}.{name_b}"))
return candidates
matches = guess_foreign_keys(table_a_columns, "customers", table_b_columns)
print("Candidate foreign key relationships:")
for col, ref in matches:
print(f" {col} -> {ref}")
if not matches:
print(" No candidates found — try relaxing the naming heuristic.")
You're handed a 12-year-old PostgreSQL database with 340 tables, no DBA, no documentation. What's your first step to understand the schema?
information_schema is PostgreSQL's SQL-standard metadata catalog. Querying it gives you a complete inventory of tables, columns, data types, nullability, defaults, and existing constraints — without needing a DBA or documentation. This is step 1 of schema recovery: you can't understand relationships or write queries until you know what tables and columns exist. Asking the client works for 5 tables, not 340. Reading sample data is useful later for validation, but you need the full column inventory first. SELECT * on 340 tables is impractical and won't reveal types or constraints.