Drag the edges to resize the window.

In Projects, you can keep track of your progress as you go throught the tasks. Check each item as you complete it!

Code Editor

Query Results

Run a query to see results.

Database Schema

Schema undefined.
Learn
Multiple Tables

With

Often times, we want to combine two tables, but one of the tables is the result of another calculation.

Let's return to our magazine order example. Our marketing department might want to know a bit more about our customers. For instance, they might want to know how many magazines each customer subscribes to. We can easily calculate this using our orders table:

SELECT customer_id, COUNT(subscription_id) as subscriptions FROM orders GROUP BY customer_id;

This query is good, but a customer_id isn't terribly useful for our marketing department, they probably want to know the customer's name.

We want to be able to join the results of this query with our customers table, which will tell us the name of each customer. We can do this by using a WITH clause.

WITH previous_results AS ( SELECT ... ) SELECT * FROM previous_results JOIN other_table ON ... = ...;
  • The WITH statement allows us to perform a separate query (such as aggregating customer's subscriptions)
  • previous_results is the alias that we will use to reference any columns from the query inside of the WITH clause
  • We can then go on to join our results with another table
Report a Bug
If you see a bug or any other issue with this page, please report it here.