Lessons › SQL › Chapter 7: Creating and changing tables
SQL lesson
CREATE TABLE AS SELECT
Sometimes you want to keep a query's answer, like this month's totals, without running it again. CREATE TABLE … AS runs the SELECT once and saves its rows as a new table. The new table is a copy. If orders changes later, the copy stays the same.
Try this lesson free →Example
Save a query's results as a new table
CREATE TABLE category_totals AS
SELECT category, SUM(revenue) AS total
FROM orders
GROUP BY category| category | total |
|---|---|
| Electronics | 598.99 |
| Clothing | 299.00 |
Step by step
- The new table's name, then AS.
CREATE TABLE category_totals AS SELECT category, SUM(revenue) AS total FROM orders GROUP BY category - It runs once. Its rows become the new table.
CREATE TABLE category_totals AS SELECT category, SUM(revenue) AS total FROM orders GROUP BY category
Practice
1. Save each category's total revenue from orders as a new table called category_totals. Name the total column total.
CREATE TABLE category_totals AS SELECT category, SUM(revenue) AS total FROM orders GROUP BY category2. Save the orders over 100 as a new table called big_orders.
CREATE TABLE big_orders AS SELECT * FROM orders WHERE revenue > 1003. Save each customer's total revenue from orders as a new table called customer_totals. Name the total column total.
CREATE TABLE customer_totals AS SELECT customer_id, SUM(revenue) AS total FROM orders GROUP BY customer_id4. Save only the Clothing orders from orders as a new table called clothing_orders.
CREATE TABLE clothing_orders AS SELECT * FROM orders WHERE category = 'Clothing'5. Save the number of orders in each category as a new table called category_counts. Name the count column order_count.
CREATE TABLE category_counts AS SELECT category, COUNT(*) AS order_count FROM orders GROUP BY categoryLearn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →