// SQL snippet

Copy a table with its data

Copying a table with its rows gives you a snapshot to compare against or restore from before a risky change. The statement differs per engine, and so does what the copy keeps.

Main statement
PostgreSQL
还支持
SQL Server MySQL SQLite

The task

Before a bulk update or refactor, take a snapshot of the whole table, data included, that you can compare against or restore from.

The snippet

Written for PostgreSQL. Versions for SQL Server, MySQL and SQLite are under Variations.

PostgreSQL
CREATE TABLE users_backup AS
SELECT * FROM users;

工作原理

CREATE TABLE AS SELECT copies every row and takes column types from the SELECT, but none of the source's constraints, indexes, defaults or NOT NULL markers, so the copy is a plain table with the same data. That makes it quick to create, and also means nothing stops duplicates or NULLs from entering it later. When you need the constraints too, create the table with LIKE ... INCLUDING ALL (see create-empty-like-table) and INSERT ... SELECT into it.

Variations

MySQL

MySQL
CREATE TABLE users_backup LIKE users;
INSERT INTO users_backup SELECT * FROM users;
-- LIKE keeps indexes; INSERT ... SELECT copies the rows

SQL Server

SQL Server
SELECT * INTO dbo.Users_Backup FROM dbo.Users;
-- keeps nullability and IDENTITY; no indexes, keys,
-- defaults or checks on the copy

SQLite

SQLite
CREATE TABLE users_backup AS SELECT * FROM users;
-- declared types become affinities (varchar(50) -> TEXT);
-- primary key, NOT NULL, defaults and indexes are lost

Questions that come up

How do I copy a table and keep its indexes?

On MySQL and PostgreSQL: CREATE TABLE ... LIKE (or LIKE ... INCLUDING ALL on PostgreSQL) first, then INSERT INTO copy SELECT * FROM source. CREATE TABLE AS never creates indexes. For a large copy it is often faster to load the rows first and create the indexes afterwards, since building an index once is cheaper than maintaining it row by row.

Keep reading

// snippets are better with a schema brain

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.