BBampaa

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 →
About 5–10 minutes · no sign-up needed

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

Result:

categorytotal
Electronics598.99
Clothing299.00

Step by step

  1. The new table's name, then AS.
    CREATE TABLE category_totals AS SELECT category, SUM(revenue) AS total FROM orders GROUP BY category
  2. 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

Try each one in your head first, then open the answer.

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 category
2. Save the orders over 100 as a new table called big_orders.
CREATE TABLE big_orders AS SELECT * FROM orders WHERE revenue > 100
3. 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_id
4. 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 category

Learn 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 →
About 5–10 minutes · no sign-up needed