Table dependency order for load and dump
Restore order matters: a row referencing a parent that is not there yet fails. This recipe maps each table to the tables its foreign keys depend on, the input for a load order.
The task
A seed or import script aborts on foreign-key violations because some tables land before the tables they reference. The fix is an explicit order derived from the dependency map.
The snippet
Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.
SELECT src.relname AS table_name,
string_agg(DISTINCT tgt.relname, ', ' ORDER BY tgt.relname) AS depends_on
FROM pg_constraint con
JOIN pg_class src ON src.oid = con.conrelid
JOIN pg_class tgt ON tgt.oid = con.confrelid
WHERE con.contype = 'f'
GROUP BY src.relname
ORDER BY src.relname;
工作原理
Every foreign key points from a child table to a parent table, so the child must be loaded after everything it lists here. Tables missing from this output have no foreign keys and can load first. A table that references itself, such as employees.manager_id, lists itself; load it in one pass with parents first or with the constraint deferred. Cycles between tables have no valid order, so break them as the FAQ describes.
Variations
SQL Server: depth-ordered load list
SQL Server-- load_order 0 = no foreign keys; load in ascending order.
-- T-SQL CTEs are recursive without the RECURSIVE keyword.
-- Self-references are skipped. Tables in a cycle are left
-- out, or, if the cycle hangs off a loadable table, the
-- query stops with the 100-level MAXRECURSION error.
WITH fk AS (
SELECT DISTINCT parent_object_id AS child_id,
referenced_object_id AS parent_id
FROM sys.foreign_keys
WHERE parent_object_id <> referenced_object_id),
depth AS (
SELECT t.object_id, 0 AS lvl FROM sys.tables t
WHERE NOT EXISTS (SELECT 1 FROM fk WHERE fk.child_id = t.object_id)
UNION ALL
SELECT fk.child_id, depth.lvl + 1
FROM fk JOIN depth ON depth.object_id = fk.parent_id)
SELECT OBJECT_SCHEMA_NAME(object_id) AS schema_name,
OBJECT_NAME(object_id) AS table_name,
MAX(lvl) AS load_order
FROM depth
GROUP BY object_id
ORDER BY load_order, table_name;
MySQL
MySQLSELECT kcu.table_name AS child_table,
kcu.referenced_table_name AS parent_table
FROM information_schema.key_column_usage kcu
WHERE kcu.table_schema = 'mydb'
AND kcu.referenced_table_name IS NOT NULL
ORDER BY kcu.table_name;
Questions that come up
How do I handle circular foreign keys?
Two tables that reference each other have no valid order. On PostgreSQL, declare the constraints DEFERRABLE and load both tables in one transaction after SET CONSTRAINTS ALL DEFERRED, so the check runs at COMMIT. Otherwise turn checking off for the load (SET FOREIGN_KEY_CHECKS = 0 on MySQL, ALTER TABLE ... NOCHECK CONSTRAINT on SQL Server, SET session_replication_role = replica on PostgreSQL, which needs superuser), or create the foreign keys after all the data is in.
Keep reading
Related on SQLly
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.