Code Editor

Query Results

Run a query to see results.

Database Schema

Schema undefined.
Multiple Tables

Combining Tables with SQL

Combinging tables manually is time-consuming. Luckily, SQL gives us an easy sequence for this: it's called a JOIN.

If we want to combine orders and customers, we would type:

SELECT * FROM orders JOIN customers ON orders.customer_id = customers.customer_id

Let's break down this command:

  1. The first line selects all columns from our combined table. If we only want to select certain columns, we can specify which ones we want.
  2. The second line specifies the first table that we want to look in, orders
  3. The third line uses JOIN to say that we want to combine information from orders with customers.
  4. The fourth line tells us how to combine the two tables. We want to match customer_id from orders with customer_id from customers.

Because column names are often repeated across multiple tables we use the syntax table_name.column_name to be sure that our requests for columns are unambiguous. In our example, we use this syntax in the ON statement, but we will also use it in the SELECT or any other statement where we refer to column names.

For example, if we only wanted to select the order_id from orders and the customer_name from customers, we could use the following query:

SELECT orders.order_id, customers.customer_name FROM orders JOIN customers ON orders.customer_id = customers.customer_id
Report a Bug
If you see a bug or any other issue with this page, please report it here.