Example 1
Build a summary table of total spend per customer for completed orders
Dave is excluded because his order has status = 'pending'. Alice's two completed orders (100 + 200) are summed to 300. The newly created customer_totals table holds exactly the aggregated rows — no indexes or constraints are carried over from the source, so additional CREATE INDEX statements are needed if the summary will be queried frequently.
CREATE TABLE orders (
customer VARCHAR(50),
amount INT,
status VARCHAR(20)
);
INSERT INTO
orders
VALUES
('Alice', 100, 'completed'),
('Alice', 200, 'completed'),
('Bob', 150, 'completed'),
('Carol', 400, 'completed'),
('Dave', 300, 'pending');CREATE TABLE customer_totals AS
SELECT
customer,
SUM(amount) AS total_spent
FROM
orders
WHERE
status = 'completed'
GROUP BY
customer;
SELECT
customer,
total_spent
FROM
customer_totals
ORDER BY
total_spent DESC;| customer | total_spent |
|---|---|
| Carol | 400 |
| Alice | 300 |
| Bob | 150 |
CREATE TABLE orders (
customer VARCHAR(50),
amount INT,
status VARCHAR(20)
);
INSERT INTO
orders
VALUES
('Alice', 100, 'completed'),
('Alice', 200, 'completed'),
('Bob', 150, 'completed'),
('Carol', 400, 'completed'),
('Dave', 300, 'pending');SELECT
customer,
SUM(amount) AS total_spent INTO customer_totals
FROM
orders
WHERE
status = 'completed'
GROUP BY
customer;
SELECT
customer,
total_spent
FROM
customer_totals
ORDER BY
total_spent DESC;| customer | total_spent |
|---|---|
| Carol | 400 |
| Alice | 300 |
| Bob | 150 |
MySQL, MariaDB, PostgreSQL, and SQLite use `CREATE TABLE ... AS SELECT ...`. SQL Server uses `SELECT ... INTO new_table FROM ...` — the `INTO` clause names the destination table. The resulting rows are identical across engines.