diff --git a/README.md b/README.md index f4ba38d..c93f06f 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1215 TILs and counting..._ +_1216 TILs and counting..._ --- @@ -584,6 +584,7 @@ _1215 TILs and counting..._ - [Difference Between Explain And Explain Analyze](postgres/difference-between-explain-and-explain-analyze.md) - [Dump All Databases To A SQL File](postgres/dump-all-databases-to-a-sql-file.md) - [Dump And Restore A Database](postgres/dump-and-restore-a-database.md) +- [Dump The SQL Needed To Recreate A Table](postgres/dump-the-sql-needed-recreate-a-table.md) - [Duplicate A Local Database](postgres/duplicate-a-local-database.md) - [Edit Existing Functions](postgres/edit-existing-functions.md) - [Enable Logging Of Database Activity](postgres/enable-logging-of-database-activity.md) diff --git a/postgres/dump-the-sql-needed-recreate-a-table.md b/postgres/dump-the-sql-needed-recreate-a-table.md new file mode 100644 index 0000000..4cd740a --- /dev/null +++ b/postgres/dump-the-sql-needed-recreate-a-table.md @@ -0,0 +1,31 @@ +# Dump The SQL Needed To Recreate A Table + +The [`pg_dump`](https://www.postgresql.org/docs/current/app-pgdump.html) +command and its arsenal of flags can do a lot of things. This includes +producing the set of [DDL](https://www.postgresql.org/docs/current/ddl.html) +SQL commands needed to recreate a table and all of it sequences, constraints, +and indexes. + +The primary flags to know about for this scenario are `-t` (which lets you +specify a table) and `--schema-only` (which indicates that we want to exclude +data from the data). + +```bash +$ pg_dump -t 'users' --schema-only my_database > users.schema.sql +``` + +Run a command like to create a file `users.schema.sql` that will contain a +series of SQL commands that will: + +- create the table with its columns (including defaults, `not null` constraints, etc.) +- create and set the sequence on a serial ID column +- add any foreign key constraints +- create any indexes + +Then if you're ever wanting to recreate this table, you can hand that file +directly to `pg_restore`. Or, since it is in SQL, you can run those commands +manually. + +There are a ton of flags beyond the two covered here. Read about them in the +[`pg_dump` docs +pages](https://www.postgresql.org/docs/current/app-pgdump.html).