iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

SQL SELECT INTO

SELECT INTO creates a new table and copies rows into it in one statement. It's a quick way to snapshot or stage data.

Snapshot a table

SQL
SELECT *
INTO customers_backup
FROM customers;

The new table customers_backup is created with the same columns and types, and populated with all rows from the source.

Subset of columns and rows

SQL
SELECT id, name, email
INTO customers_au
FROM customers
WHERE country = 'AU';

Vendor support

DBForm
SQL Server / MS AccessSELECT … INTO new_table FROM …
PostgreSQLSELECT … INTO new_table FROM … or CREATE TABLE new AS SELECT …
MySQL / MariaDBNo SELECT INTO for tables — use CREATE TABLE new AS SELECT …
SQLite / OracleCREATE TABLE new AS SELECT …

What does NOT get copied

Constraints, indexes, default values, and triggers are not carried over by SELECT INTO. If you need them in the snapshot, recreate them after the copy.

Tip: Use SELECT INTO for one-off snapshots and ad-hoc reporting. For production backups, use the database's native backup tools.

Example

Example
SELECT *
INTO customers_backup
FROM customers;
Try it Yourself »

Exercise

Copy customers into a brand-new snapshot table.

SELECT * customers_backup FROM customers;

Test yourself

Q1. SELECT INTO creates…
Q2. MySQL alternative is…
Q3. What does NOT carry over?

Discussion

Loading…