🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Metadata Queries for Lineage and Introspection

Advanced SQLMetadata Queries⭐ Premium

The catalogue is a database of databases

Every relational engine stores its own description of itself — tables, columns, indexes, grants, statistics — in ordinary tables you can query like any other data. That self-description is the most underused feature in SQL. The questions engineers answer by clicking through a client or grepping migration files are almost all single queries against the catalogue: which tables hold a column called customer_ref, what would break if this view were dropped, which index is unused, and who has access to the payroll table.

The skill has a second audience. Governance and data-catalogue initiatives depend on exactly this metadata to build lineage, and a lineage system is essentially a query over dependency records plus a join to ownership. Teams that can query the catalogue directly can answer compliance questions in minutes instead of waiting for a tooling project, and can validate whether the tooling is telling the truth.

By the end of this lesson you should be able to navigate both the standard and engine-specific catalogue layers, write the dependency query that powers lineage, and derive useful signals from execution statistics rather than guessing at them.

Two layers with different contracts

Most engines expose a portable standard view and a richer engine-native catalogue underneath. The standard layer travels across systems; the native layer gives you what the standard omits.

QuestionANSI information_schemaEngine-native catalogue
List tables and columnsYes, portableYes, richer types
Index definitionsNoYes
View definition textNoYes
Row counts and statisticsNoYes
Permissions and grantsLimitedYes
Foreign keys and constraintsYesYes
Query historyNoYes
Partition layoutNoYes

The practical consequence: write portable discovery queries against information_schema and accept that anything about performance, security, or physical layout needs the native layer. PostgreSQL uses pg_catalog, SQL Server uses sys views, Oracle uses ALL_ and DBA_ dictionaries, MySQL uses information_schema for everything plus performance_schema. Knowing which layer you are in prevents the classic mistake of writing a query that works on one engine and returns nothing on another.

Finding every object that carries a column

The most common introspection task is rename safety: before changing or dropping a column, find every table, view, and procedure that references it. Without that, a "simple" cleanup breaks a report nobody remembered.

-- Every table and view with a column matching a name pattern
SELECT table_schema,
       table_name,
       column_name,
       data_type,
       is_nullable,
       character_maximum_length
  FROM information_schema.columns
 WHERE column_name ILIKE '%customer%ref%'
   AND table_schema NOT IN ('pg_catalog', 'information_schema')
 ORDER BY table_schema, table_name, ordinal_position;

-- Objects whose definition text mentions a table: the view and function layer
SELECT n.nspname  AS schema,
       c.relname  AS object_name,
       CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view'
                      WHEN 'r' THEN 'table' END AS object_type,
       pg_get_viewdef(c.oid, true) AS definition
  FROM pg_class c
  JOIN pg_namespace n ON n.oid = c.relnamespace
 WHERE c.relkind IN ('v', 'm')
   AND pg_get_viewdef(c.oid, true) ILIKE '%orders_fact%'
   AND n.nspname NOT LIKE 'pg_%'
 ORDER BY 1, 2;

-- Columns with no index anywhere: candidates for the next performance review
SELECT schemaname, tablename, column_name, data_type
  FROM information_schema.columns col
 WHERE NOT EXISTS (
       SELECT 1
         FROM pg_index i
         JOIN pg_class t ON t.oid = i.indrelid
         JOIN pg_namespace ns ON ns.oid = t.relnamespace
         JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY (i.indkey)
        WHERE ns.nspname = col.table_schema
          AND t.relname  = col.table_name
          AND a.attname  = col.column_name
 )
   AND col.table_schema = 'public'
 ORDER BY 1, 2, col.ordinal_position;

Note the exclusion of system schemas in the first query — without it, you will spend time reading the catalogue's own tables. And the second query shows a general technique: rendering definition text with the catalogue's helper functions, which turns a binary object back into SQL you can read, diff, and search.

Building a dependency graph for lineage

Lineage is a directed graph assembled from recorded dependencies. Views reference tables, views reference views, and materialized views add refresh relationships; the catalogue already holds these edges, so the work is extracting and joining them.

-- Direct dependencies: what each view reads
WITH edges AS (
    SELECT DISTINCT
           dependent.relname  AS downstream,
           source.relname     AS upstream,
           dependent.oid      AS dependent_oid
      FROM pg_depend d
      JOIN pg_rewrite  r ON r.oid = d.objid
      JOIN pg_class dependent ON dependent.oid = r.ev_class
      JOIN pg_class source    ON source.oid    = d.refobjid
     WHERE dependent.relkind IN ('v', 'm')
       AND source.relkind   IN ('r', 'm', 'v')
       AND dependent.oid   <> source.oid
       AND d.deptype = 'n'
)
SELECT downstream, upstream
  FROM edges
 ORDER BY downstream, upstream;

-- Direct and transitive upstreams for one subject table
WITH RECURSIVE upstream(name, depth) AS (
    SELECT 'orders_fact', 0
    UNION
    SELECT e.upstream, u.depth + 1
      FROM edges e
      JOIN upstream u ON e.downstream = u.name
     WHERE u.depth < 10
)
SELECT name, min(depth) AS depth
  FROM upstream
 GROUP BY name
 ORDER BY depth, name;

The recursive query is where lineage becomes useful: given one table, everything upstream that could have introduced a defect, ordered by distance. In practice you persist the edge set into a table, refresh it on a schedule or as part of deployment, and serve both impact analysis and the dashboard from that snapshot. Keeping the graph in the database also means the lineage can be queried with the same SQL used to query the data itself.

Query history and cost from execution statistics

Catalogues also record what has been running. Execution statistics turn introspection into performance work: which indexes are unused, which queries dominate, and where the planner's estimates diverge from reality.

-- Slowest statements by mean execution time, with call counts
SELECT calls,
       round(total_exec_time::numeric, 1)      AS total_ms,
       round(mean_exec_time::numeric, 2)       AS mean_ms,
       round((100 * shared_blks_hit
              / nullif(shared_blks_hit + shared_blks_read, 0))::numeric, 1) AS hit_pct,
       left(query, 120)                        AS query_preview
  FROM pg_stat_statements
 WHERE calls > 100
 ORDER BY mean_exec_time DESC
 LIMIT 15;

-- Indexes that have never been used for a read
SELECT schemaname, relname AS table_name, indexrelname AS index_name,
       idx_scan, pg_size_pretty(pg_relation_size(indexrelid)) AS size
  FROM pg_stat_user_indexes
 WHERE idx_scan = 0
   AND indexrelname NOT LIKE '%_pkey'
 ORDER BY pg_relation_size(indexrelid) DESC;

Two readings matter. A high call count with modest mean time can dominate total cost, so sort by both columns before deciding what to tune. And an unused index is not automatically deletable — it may serve rare monthly reports or a replication path — so treat the list as a review queue rather than a work order.

Statistics also expose misestimates: compare the planner's row estimate against the actual rows read, and wide divergence points at stale statistics, correlated columns, or expressions the planner cannot model. That diagnosis is available from a single EXPLAIN ANALYZE plus a glance at the stats tables.

Portability patterns across engines

The same questions recur on every platform, but the catalogue names change. Keeping the portable layer as the default and isolating native calls behind small views makes an introspection suite move with you. A useful convention is to create a reporting view that normalises the engine's columns into a stable shape, then write all downstream reports against that view.

-- SQL Server: normalise object metadata into one shape
SELECT s.name  AS schema_name,
       t.name  AS object_name,
       t.type_desc,
       p.rows AS approx_rows
  FROM sys.tables t
  JOIN sys.schemas s ON s.schema_id = t.schema_id
  JOIN sys.partitions p ON p.object_id = t.object_id AND p.index_id IN (0, 1);

-- MySQL: table sizes and engine from information_schema alone
SELECT table_schema, table_name, engine,
       table_rows, round(data_length / 1024 / 1024, 1) AS data_mb,
       round(index_length / 1024 / 1024, 1) AS index_mb
  FROM information_schema.tables
 WHERE table_schema NOT IN ('mysql', 'information_schema', 'performance_schema', 'sys')
 ORDER BY data_length + index_length DESC;

Two portability traps deserve special mention. First, case sensitivity differs: PostgreSQL folds unquoted identifiers to lower case, SQL Server to the collation's rules, MySQL depends on the file system. Always quote identifiers in introspection queries and match the catalogue's stored case. Second, system schema names differ (pg_catalog, sys, mysql, performance_schema), so every exclusion list must be parameterised per engine. A small configuration table mapping engine to system schemas keeps these lists in one reviewed place instead of scattered through dozens of queries.

Finally, treat catalogue access as a privileged operation in production. Some engines allow row-level security over catalogue views; at minimum, run introspection under a dedicated role whose grants are documented, and log who ran which catalogue query when the results feed compliance reporting.

Discovering drift and unused objects

The catalogue makes structural hygiene measurable. Tables with no recent access, columns that are always null, views referencing objects that no longer exist, and grants wider than intended all show up as queries rather than opinions.

-- Relations not accessed in 90 days
SELECT schemaname, relname, n_live_tup,
       last_vacuum, last_autoanalyze
  FROM pg_stat_user_tables
 WHERE coalesce(last_seq_scan, last_idx_scan, '1970-01-01'::timestamptz)
           < CURRENT_TIMESTAMP - INTERVAL '90 days'
 ORDER BY n_live_tup DESC;

-- Privileges granted beyond the intended roles
SELECT grantee, table_schema, table_name, privilege_type
  FROM information_schema.table_privileges
 WHERE table_schema = 'public'
   AND grantee IN ('PUBLIC', 'analyst_ext')
 ORDER BY table_name, grantee;

Automating these checks turns introspection into governance: scheduled queries with thresholds, results written to a review table, and an owner assigned per finding. The queries are short; the value comes from running them repeatedly and acting on the diff.

💡Catalogue queries belong in version control

Store your introspection and lineage queries alongside the application code. They are the only tests you have for structural assumptions — referential integrity, grant hygiene, index usage — and they should be reviewed and executed on the same schedule as everything else.

Common Mistakes

Searching for column usage by grepping application code only

Fix: Query the catalogue for every view, function, and constraint referencing the object

Building lineage by hand in a spreadsheet

Fix: Extract edges from pg_depend or the equivalent and refresh them on a schedule

Deleting every index with zero scans

Fix: Treat usage stats as a review queue and check for rare but critical readers first

Writing engine-specific introspection and assuming it travels

Fix: Use information_schema for discovery and keep native catalogue calls isolated and labelled

Best Practices

  • Persist the dependency graph and serve impact analysis from a refreshed snapshot
  • Exclude system schemas explicitly in every discovery query
  • Pair mean and total execution cost before tuning anything
  • Schedule catalogue hygiene checks and record findings with owners
  • Keep introspection SQL in source control next to the migrations it describes

Interview Questions

Q1: information_schema versus native catalogue?

information_schema is portable and covers structure; native catalogues expose indexes, definitions, statistics, grants, and history that the standard omits.

Q2: How would you find all views that depend on a table?

Join the rewrite and dependency catalogues to resolve view definitions to their underlying relations, or render definitions with the engine's helper function.

Q3: How do you build data lineage from a database?

Extract view-to-table edges into a graph, then run recursive traversal from a subject table to get transitive upstreams.

Q4: What does an index with zero scans tell you?

Possibly that it is unused, possibly that its reader is rare; it is a review signal rather than an instruction to drop it.

Key Takeaways

  • The catalogue is queryable data, and most introspection questions are one join away
  • Use the portable layer for discovery and the native layer for performance, security, and layout
  • Lineage is an edge extraction problem plus a recursive traversal
  • Execution statistics convert guessing into measurement, for cost and for planner accuracy
  • Automate structural hygiene checks so drift shows up as a diff instead of an incident
🔒

Premium Content

Metadata Queries for Lineage and Introspection

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

đŸŽ¯End-to-end Projects
đŸ’ŧInterview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement