INSERT from a query in SQL
The rows to insert can come from a query instead of a VALUES list.
INSERT INTO customer_totals (customer_id, lifetime_value)
SELECT
customer_id,
SUM(total)
FROM orders
WHERE status = 'paid'
GROUP BY customer_id;
How it works
- Column lists line up by position, so the SELECT order matters.
- This is how you backfill a table or snapshot a report.
- No round trip through the client: the rows never leave the engine.
Keywords and builtins used here
BYFROMGROUPINSERTINTOSELECTSUMWHERE
The run, in numbers
- Lines
- 7
- Characters to type
- 144
- Tokens
- 25
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 19 seconds.
Step 5 of 8 in Tables & rows, step 18 of 23 in Language basics.