INFORMATION_SCHEMA Schema Introspection

Discover table structure through INFORMATION_SCHEMA columns and table_constraints instead of hardcoding column names into migrations.

SqlData Fetching

Code

snippet
-- 查一张表的列清单:标准 SQL 的 information_schema,跨库可移植
SELECT
    column_name,
    data_type,
    is_nullable,
    column_default
FROM information_schema.columns
WHERE table_schema = 'public' AND table_name = 'orders'
ORDER BY ordinal_position;

-- 外键关系同样可查:谁引用了谁一目了然
SELECT
    tc.constraint_name,
    kcu.column_name,
    ccu.table_name  AS referenced_table,
    ccu.column_name AS referenced_column
FROM information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu
  ON tc.constraint_schema = kcu.constraint_schema
 AND tc.constraint_name  = kcu.constraint_name
JOIN information_schema.constraint_column_usage AS ccu
  ON ccu.constraint_schema = tc.constraint_schema
 AND ccu.constraint_name  = tc.constraint_name
WHERE tc.constraint_type = 'FOREIGN KEY'
  AND tc.table_schema = 'public'
  AND tc.table_name = 'orders';

How it works

Several statements share this file — SELECT, with information_schema.columns, information_schema.table_constraints, information_schema.key_column_usage and information_schema.constraint_column_usage among the objects involved.

In terms of clauses, the statements use: 2 JOINs combining rows across tables; a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order.

What to watch for

  • 2 joins multiply the intermediate row count; confirm the join keys are indexed before pointing this at production-sized tables.

Applying it

The information_schema.columns table is the working surface here.

Statements that matter

SELECT
column_name,
data_type,
is_nullable,
column_default
FROM information_schema.columns
WHERE table_schema = 'public' AND table_name = 'orders'
ORDER BY ordinal_position;

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
`information_schema.columns`, `information_schema.table_constraints`, `information_schema.key_column_usage`, `information_schema.constraint_column_usage`, combined through 2 joins.