TExcelTAD
Home › MySQL › MySQL INSERT INTO SELECT

MySQL INSERT INTO SELECT

INSERT INTO ... SELECT copies the result of a query into an existing table. It is how you archive old rows, fill a summary table or move data between tables, all inside the server, without sending the rows to a client and back.

sql
INSERT INTO target_table (col1, col2, ...)
SELECT expr1, expr2, ...
FROM source_table
WHERE ...;

The SELECT must return as many columns as the column list names, in the same order. Column names don't need to match; positions do.

Copying rows into an archive

mysql · try it yourself
CREATE TABLE delivered_orders (
  order_id     INT PRIMARY KEY,
  customer_id  INT,
  order_date   DATE,
  shipped_date DATE
);

INSERT INTO delivered_orders (order_id, customer_id, order_date, shipped_date)
SELECT order_id, customer_id, order_date, shipped_date
FROM orders
WHERE status = 'delivered' AND order_date < '2025-02-01';

SELECT * FROM delivered_orders;
+----------+-------------+------------+--------------+
| order_id | customer_id | order_date | shipped_date |
+----------+-------------+------------+--------------+
|        1 |           1 | 2025-01-05 | 2025-01-07   |
|        2 |           2 | 2025-01-09 | 2025-01-10   |
|        3 |           4 | 2025-01-18 | 2025-01-20   |
|        4 |           1 | 2025-01-27 | 2025-01-29   |
+----------+-------------+------------+--------------+

Filling a summary table

The SELECT can join, group and calculate. Here we store one row per customer with their order count and total spending, a typical "pre-computed report" table:

mysql · try it yourself
CREATE TABLE customer_stats (
  customer_id INT PRIMARY KEY,
  orders      INT,
  spent       DECIMAL(10,2)
);

INSERT INTO customer_stats (customer_id, orders, spent)
SELECT o.customer_id,
       COUNT(DISTINCT o.order_id),
       SUM(d.quantity * d.unit_price * (1 - d.discount))
FROM orders AS o
JOIN order_details AS d ON d.order_id = o.order_id
WHERE o.status <> 'cancelled'
GROUP BY o.customer_id;

SELECT * FROM customer_stats ORDER BY spent DESC LIMIT 5;
+-------------+--------+--------+
| customer_id | orders | spent  |
+-------------+--------+--------+
|           1 |      3 | 128.01 |
|           4 |      2 |  55.92 |
|           5 |      2 |  53.45 |
|           2 |      2 |  50.75 |
|          12 |      2 |  42.24 |
+-------------+--------+--------+

The sums were rounded to two decimals when they were stored, because spent is DECIMAL(10,2).

Mixing constants and selected values

The select list can contain constants too, for example to tag where the rows came from:

mysql · try it yourself
CREATE TABLE contacts (name VARCHAR(80), country VARCHAR(40), source VARCHAR(10));

INSERT INTO contacts (name, country, source)
SELECT CONCAT(first_name, ' ', last_name), country, 'customer' FROM customers WHERE country = 'UK';

INSERT INTO contacts (name, country, source)
SELECT name, country, 'supplier' FROM suppliers WHERE country = 'UK';

SELECT * FROM contacts ORDER BY source, name;
+-------------------+---------+----------+
| name              | country | source   |
+-------------------+---------+----------+
| Ben Carter        | UK      | customer |
| Farah Khan        | UK      | customer |
| George Brown      | UK      | customer |
| Crunch & Co       | UK      | supplier |
| Highland Roasters | UK      | supplier |
+-------------------+---------+----------+

CREATE TABLE ... AS SELECT

To create the table and fill it in one step, use CREATE TABLE new_table AS SELECT .... The new table gets its column names and types from the query (but no primary key, indexes or other constraints):

mysql · try it yourself
CREATE TABLE cheap_products AS
SELECT product_id, name, unit_price
FROM products
WHERE unit_price < 2;

SELECT * FROM cheap_products ORDER BY unit_price;
+------------+------------------+------------+
| product_id | name             | unit_price |
+------------+------------------+------------+
|         14 | Avocado (each)   |       1.25 |
|          9 | Whole Milk 1L    |       1.45 |
|          6 | Butter Croissant |       1.60 |
|         16 | Sea Salt Crisps  |       1.99 |
+------------+------------------+------------+

Note: Other databases (SQL Server, PostgreSQL) have SELECT ... INTO new_table. MySQL doesn't: in MySQL, SELECT ... INTO stores a single row into variables (SELECT COUNT(*) INTO @n FROM orders;) or writes to a file. Use CREATE TABLE ... AS SELECT instead.

Test yourself

What must match between the INSERT column list and the SELECT?

  1. The column names
  2. The number and order of columns
  3. The table names
  4. Nothing

How do you create a new table from a query result in MySQL?

  1. SELECT ... INTO new_table
  2. CREATE TABLE new_table AS SELECT ...
  3. INSERT TABLE new_table SELECT ...
  4. COPY new_table FROM SELECT ...

Which constraints does CREATE TABLE t AS SELECT ... copy from the source table?

  1. Primary key and indexes
  2. Foreign keys
  3. None; only column names and types
  4. All of them