VillageSQL is a drop-in replacement for MySQL with extensions.
All examples on this page work on VillageSQL. Install Now →
VALUES supplies rows you type. A SELECT in its place supplies rows the
server works out, so a summary you can query is a summary you can store. It is
how a report table gets filled and how rows move from one table to another.
These examples use the sakila_practice database from
INSERT. Run the setup block there again before you start,
then open the client with mysql -u root -p sakila_practice.
How INSERT SELECT works
TARGET_TABLE with the table being written to, COLUMN_LIST with its
columns, SOURCE_COLUMNS with what the query returns, and SOURCE_TABLE with
the table being read.
There is no VALUES keyword. The columns pair up by position, so the first
thing the SELECT returns goes into the first column named, whatever the 2 are
called. Every row the query returns becomes a row in the target table.
Examples
1) Store a summary
rating_count is empty and sakila.film holds the answer. Naming a table
database.table reads it from another database, so 1 statement can cross
between the 2.
GROUP BY produced 5 rows and 5 rows were written.
film changes.
2) Build values on the way in
TheSELECT can compute anything, so the rows going in do not have to exist
anywhere in that shape.
CONCAT and the date is a constant repeated on
every row.
ERROR 1136 means the 2 lists are different lengths
SELECT
that returns the right number of the wrong columns is accepted and writes
nonsense. Run the SELECT on its own first and read what comes back.
A second run meets the table’s keys
Every row the query returns is offered to the table, and the table’s rules still apply.rating is the primary key and G is already stored. A summary you want to
refresh rather than build once needs upsert, which updates
the stored row instead of failing.
Summary
- Put a
SELECTwhereVALUESwould go, and write noVALUESkeyword. - Expect the columns to pair up by position, never by name.
- Read
ERROR 1136as 2 lists of different lengths. - Name a table
database.tableto read from another database in the same statement. - Expect a second run to hit the target table’s keys, the same as any other insert.
See also
- INSERT — the form that takes typed values
- Insert multiple rows — many rows without a query
- Upsert — refreshing rows a second run would collide with
- Bulk inserts in MySQL — moving large volumes, and what it costs

