20 Basic SQL Query Examples for Beginners
Table of Contents
- What Is SQL?
- Dataset
- 1. Selecting All Columns From One Table
- 2. Selecting One Column From One Table
- 3. Selecting Two Columns From One Table
- 4. Selecting Two (or More) Columns From One Table and Filtering Using Numeric Comparison in WHERE
- 5. Selecting Two Columns and Filtering Using an Equality Condition in WHERE
- 6. Selecting Two Columns and Ordering by One Column
- 7. Selecting Two Columns and Ordering Descendingly by One Column
- 8. Selecting Two Columns From One Table and Ordering Descendingly by Two Columns
- 9. Selecting Two Columns With a Complex Logical Condition in WHERE
- 10. Simple Computations on Columns
- 11. Using SUM() and GROUP BY
- 12. Using COUNT() and GROUP BY
- 13. Using AVG() and GROUP BY
- 14. Using MIN() and GROUP BY
- 15. Using MAX() and GROUP BY
- 16. Using SUM(), WHERE, and GROUP BY
- 17. Using COUNT(), WHERE, and GROUP BY
- 18. Accessing Data in Two Tables Using INNER JOIN
- 19. Accessing Data in Two Tables Using INNER JOIN and Filtering Using WHERE
- 20. Accessing Data in Two Tables Using INNER JOIN, Filtering Using WHERE, and Sorting With ORDER BY
- From Basic SQL Queries to SQL Master
These 20 basic queries are a must in a starter pack for every SQL beginner. These examples will get you going on your journey to mastering SQL.
You’ve set your mind on learning SQL, googled ‘basic sql query examples’ or something similar, and here you are staring at this article. Now what? All learning starts with the basics, so let’s start with the most basic question:
What Is SQL?
SQL, or Structured Query Language, is a programming language. Like any language – programming or natural – it is used to communicate, to talk. SQL is designed to talk to a database. We do that using sentences that we call queries, which are SQL commands for retrieving data from the database.
We’ll soon show you 20 basic SQL query examples to start talking with the database. All these queries are taught in our SQL Basics course. This course will give you even more structure, examples, and challenges to solve. It has 129 interactive exercises on querying one or more tables, aggregating and grouping data, JOINs, subqueries, and set operations. Even with the 20 upcoming examples, we won’t show all the details or even all the basic-level queries. That’s why we recommend using the course as a platform for practicing the fundamentals we’ll discuss here.
Also, most of our examples are nicely presented in our SQL Basics Cheat Sheet. Feel free to have it by your side – it might help you better understand what follows next.
Dataset
Our dataset consists of two tables. The first table is called employees
.
id | first_name | last_name | department | salary |
---|---|---|---|---|
1 | Paul | Garrix | Corporate | 3,547.25 |
2 | Astrid | Fox | Private Individuals | 2,845.56 |
3 | Matthias | Johnson | Private Individuals | 3,009.41 |
4 | Lucy | Patterson | Private Individuals | 3,547.25 |
5 | Tom | Page | Corporate | 5,974.41 |
6 | Claudia | Conte | Corporate | 4,714.12 |
7 | Walter | Deer | Private Individuals | 3,547.25 |
8 | Stephanie | Marx | Corporate | 2,894.51 |
9 | Luca | Pavarotti | Private Individuals | 4,123.45 |
10 | Victoria | Pollock | Corporate | 4,789.53 |
The columns and data in the above table are:
id
– The unique ID of the employee and the table’s primary key.first_name
– The employee’s first name.last_name
– The employee’s last name.department
– The employee’s department.salary
– The employee’s monthly salary, in USD.
All this tells us that this table is a list of a company’s employees and their salaries. There is also data on the employees’ departments. All employees work in the sales division, where the department can be either Corporate or Private Individuals. In other words, the employees sell the company’s products to companies and private individuals.
The other table in the dataset is named quarterly_sales
.
employee_id | q1_2022 | q2_2022 | q3_2022 | q4_2022 |
---|---|---|---|---|
8 | 3,471.41 | 14,789.25 | 3,478.34 | 1,254.23 |
4 | 5,417.81 | 12,846.23 | 8,741.54 | 3,589.99 |
10 | 1,547.52 | 1,269.66 | 1,478.65 | 2,474.33 |
1 | 8,715.55 | 8,465.65 | 24,747.82 | 3,514.36 |
3 | 12,774.51 | 24,784.31 | 12,223.34 | 8,451.51 |
2 | 4,989.23 | 5,103.22 | 4,897.98 | 5,322.05 |
7 | 18,415.66 | 15,279.37 | 14,634.44 | 14,445.12 |
6 | 2,498.63 | 8,741.45 | 3,997.65 | 2,497.21 |
5 | 6,349.74 | 7,555.55 | 6,944.35 | 7,788.01 |
9 | 4,485.36 | 4,101.50 | 8,787.45 | 7,648.90 |
The columns are:
employee_id
– The unique ID of the employee. Also, a foreign key referencing the column id from the tableemployees
.q1_2022
– The sales made by that employee in the first quarter of 2022.q2_2022
– The sales made by that employee in the second quarter of 2022.q3_2022
– The sales made by that employee in the third quarter of 2022.q4_2022
– The sales made by that employee in the fourth quarter of 2022.
In general, this table is a list of each quarter’s sales made by every employee shown in the first table.
Now, let’s start writing SQL queries.
1. Selecting All Columns From One Table
This query is useful when you want to quickly get all the columns from a table without writing every column in the SELECT statement.
Query
SELECT * FROM employees; |
Explanation
Whenever you want to select any number of columns from any table, you need to use the SELECT
statement. You write it, rather obviously, by using the SELECT
keyword.
After the keyword comes an asterisk (*
), which is shorthand for “all the columns in the table”.
To specify the table, use the FROM
clause and write the table’s name afterward.
Output
The query’s output is the whole table employees
, as shown below.
id | first_name | last_name | department | salary |
---|---|---|---|---|
1 | Paul | Garrix | Corporate | 3,547.25 |
2 | Astrid | Fox | Private Individuals | 2,845.56 |
3 | Matthias | Johnson | Private Individuals | 3,009.41 |
4 | Lucy | Patterson | Private Individuals | 3,547.25 |
5 | Tom | Page | Corporate | 5,974.41 |
6 | Claudia | Conte | Corporate | 4,714.12 |
7 | Walter | Deer | Private Individuals | 3,547.25 |
8 | Stephanie | Marx | Corporate | 2,894.51 |
9 | Luca | Pavarotti | Private Individuals | 4,123.45 |
10 | Victoria | Pollock | Corporate | 4,789.53 |
2. Selecting One Column From One Table
You can use this query when you only need one column from the table..
Query
SELECT first_name FROM employees; |
Explanation
The approach is similar to the previous query. However, this time, instead of an asterisk, we write the specific column name in SELECT
. In this case, it’s the column first_name
.
The second line of the query is the same: it references the table in the FROM
clause.
Output
The query returns the list of employees’ first names.
first_name |
---|
Paul |
Astrid |
Matthias |
Lucy |
Tom |
Claudia |
Walter |
Stephanie |
Luca |
Victoria |
3. Selecting Two Columns From One Table
This query is useful when selecting two (or more) columns from one table.
Query
SELECT first_name, last_name FROM employees; |
Explanation
Again, the approach is similar to earlier examples. To select two columns, you need to write their names in SELECT
. The important thing is that the columns need to be separated by a comma. You can see in the example that there’s a comma between the columns first_name
and last_name
.
Then, as usual, reference the table employees
in FROM
.
Output
Now the query shows the employees’ full names.
first_name | last_name |
---|---|
Paul | Garrix |
Astrid | Fox |
Matthias | Johnson |
Lucy | Patterson |
Tom | Page |
Claudia | Conte |
Walter | Deer |
Stephanie | Marx |
Luca | Pavarotti |
Victoria | Pollock |
4. Selecting Two (or More) Columns From One Table and Filtering Using Numeric Comparison in WHERE
Knowing this SQL query will allow you to filter data according to numeric values. You can do that using comparison operators in the WHERE
clause.
Here’s the overview of the SQL comparison operators.
Comparison Operator | Description |
---|---|
= | Is equal to |
> | Is greater than |
< | Is less than |
>= | Is greater than or equal to |
<= | Is less than or equal to |
<> | Is not equal to |
Query
SELECT first_name, last_name, salary FROM employees WHERE salary > 3800; |
Explanation
The query actually selects three, not two columns. It’s the same as with two columns: simply write them in SELECT
and separate them with commas.
Then we reference the table in FROM
.
Now, we need to show only employees with a salary above 3,800. To do this, you need to use WHERE
. It’s a clause that accepts conditions and is used for filtering the output. It goes through the table and returns only the data that satisfies the condition.
In our case, we’re looking for salaries ‘greater than’ a certain number. In other words, a condition using the > comparison operator.
To set the condition, we write the column name in WHERE
. Then comes the comparison operator, and after that, the value that the data has to be greater than. This condition will now return all the salaries that are above 3,800.
Output
The query returns four employees and their salaries. As you can see, they all have salaries above 3,800.
first_name | last_name | salary |
---|---|---|
Tom | Page | 5,974.41 |
Claudia | Conte | 4,714.12 |
Luca | Pavarotti | 4,123.45 |
Victoria | Pollock | 4,789.53 |
5. Selecting Two Columns and Filtering Using an Equality Condition in WHERE
Once again, this basic SQL query example is useful when you want to select several columns but not all the rows from the table. Now you want to find the values that are the same as the value from the condition. For that, you need the equality condition (=
).
Query
SELECT first_name, last_name FROM employees WHERE first_name = 'Luca' ; |
Explanation
The query selects employees’ first and last names.
However, we want to show only employees whose name is Luca. For this, we again use WHERE
. The approach is similar to the previous example: we use WHERE, write the column name, and use the comparison operator. This time, our condition uses the equal sign (=
).
In other words, the values in the column first_name
have to be equal to Luca. Also, when the condition is not a number but a text or a date/time, it has to be written in single quotes (''
). That’s why our condition is written as 'Luca
', not simply Luca
.
Output
The output shows there’s only one employee named Luca, and his full name is Luca Pavarotti.
first_name | last_name |
---|---|
Luca | Pavarotti |
6. Selecting Two Columns and Ordering by One Column
Here’s another basic SQL query example that you’ll find useful. It can be used whenever you have to order the output in a certain way to make it more readable.
Ordering or sorting the output is done using the ORDER BY
clause. By default, it orders the output in ascending order. This works alphabetically (for text data), from the lowest to the highest number (for numerical data), or from the oldest to the newest date or time (for dates and times).
Query
SELECT first_name, last_name FROM employees ORDER BY last_name; |
Explanation
We again select employees’ first and last names. But now we want to sort the output in a specific way. In this example, it’s by employees’ surname. To do that, we use ORDER BY
. In it, we simply write the column name.
We might add the keyword ASC
after that to sort the output ascendingly. However, that’s not mandatory, as ascending sorting is a default in SQL.
Output
The query returns a list of employees ordered alphabetically by their last names.
first_name | last_name |
---|---|
Claudia | Conte |
Walter | Deer |
Astrid | Fox |
Paul | Garrix |
Matthias | Johnson |
Stephanie | Marx |
Tom | Page |
Lucy | Patterson |
Luca | Pavarotti |
Victoria | Pollock |
7. Selecting Two Columns and Ordering Descendingly by One Column
This example is similar to the previous one and has the same purpose: sorting your SQL query output. However, in this case, the data is ordered in descending order (Z to A, 10 to 1).
Query
SELECT first_name, last_name FROM employees ORDER BY last_name DESC ; |
Explanation
The query is almost exactly the same as in the previous example. The only difference is we’re ordering the output by the employee’s name descendingly.
To do that, put the keyword DESC
after the last_name
column in the ORDER BY
clause.
Output
first_name | last_name |
---|---|
Victoria | Pollock |
Luca | Pavarotti |
Lucy | Patterson |
Tom | Page |
Stephanie | Marx |
Matthias | Johnson |
Paul | Garrix |
Astrid | Fox |
Walter | Deer |
Claudia | Conte |
You can see that the output is ordered the way we wanted.
8. Selecting Two Columns From One Table and Ordering Descendingly by Two Columns
Sorting an SQL query can get more sophisticated. It’s common to sort data by two or more columns, which you’re probably already familiar with as an Excel or Google Sheets user. The same can be done in SQL.
Query
SELECT first_name, last_name, salary FROM employees ORDER BY salary DESC , last_name ASC ; |
Explanation
With this query, we’re building on the previous example; we want to sort the output by the employee’s salary and their last name. This time, we sort by salary descending and then by last name ascendingly.
We reference the column salary in ORDER BY
and follow it with the keyword DESC
. The DESC
keyword indicates descending order. Before the second ordering criteria, we need to put a comma. After it comes the second criteria/column, which is last_name
in this case. You can add or omit the keyword ASC to sort the output in ascending order.
Note: The order of the columns in ORDER BY is important! The query written as it is above will first sort by salary descendingly and then by the last name ascendingly. If you wrote ORDER BY last_name ASC, salary DESC
, it would sort by last name first and then by salary in descending order.
Output
first_name | last_name | salary |
---|---|---|
Tom | Page | 5,974.41 |
Victoria | Pollock | 4,789.53 |
Claudia | Conte | 4,714.12 |
Luca | Pavarotti | 4,123.45 |
Walter | Deer | 3,547.25 |
Paul | Garrix | 3,547.25 |
Lucy | Patterson | 3,547.25 |
Matthias | Johnson | 3,009.41 |
Stephanie | Marx | 2,894.51 |
Astrid | Fox | 2,845.56 |
The output is ordered by salary. When the salary is the same (green rows), the data is ordered alphabetically by last name.
9. Selecting Two Columns With a Complex Logical Condition in WHERE
This example will again demonstrate how to filter output using WHERE. It will be a bit more advanced this time, as we’ll use a logical operator. In SQL, logical operators allow you to test if the filtering condition is true or not. They also allow you to set multiple conditions.
The three basic logical operators in SQL are AND, OR, and NOT. In the query below, we’ll use OR to get salaries below 3,000 or above 5,000.
Query
SELECT first_name, last_name, salary FROM employees WHERE salary > 5000 OR salary < 3000; |
Explanation
We use this query to select the employee’s first name, last name, and salary from the table employees
.
However, we want to show only those employees whose salaries are either above $5,000 or below $3,000. We do that by using the logical operator OR and the comparison operators in WHERE
.
We write the first condition in WHERE
, where we reference the salary
column and set the condition that the values must be above 5,000. Then we use the OR
operator, followed by the second condition. The second condition again references the salary column and uses the ‘less than’ operator to return the values below 3,000.
Output
first_name | last_name | salary |
---|---|---|
Astrid | Fox | 2,845.56 |
Tom | Page | 5,974.41 |
Stephanie | Marx | 2,894.51 |
The query returns only three employees and their salaries, as they are the only ones that satisfy the conditions.
10. Simple Computations on Columns
In this example, we’ll show how you can perform simple mathematical operations on the table’s columns.
We’ll use one of SQL’s arithmetic operators.
Arithmetic Operator | Description |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Modulo, i.e. returns the remainder of the integer division. |
Query
SELECT employee_id, q1_2022 + q2_2022 AS h1_2022 FROM quarterly_sales; |
Explanation
In the above query, we want to find the sales in the first half of 2022 for each employee.
We do it by first selecting the column employee_id
from the table quarterly_sales
.
Then we select the column q1_2022
and use the addition arithmetic operator to add the q2_2022
column. We also give this new calculated column an alias of h1_2022
using the AS
keyword.
Output
employee_id | h1_2022 |
---|---|
8 | 18,260.66 |
4 | 18,264.04 |
10 | 2,817.18 |
1 | 17,181.20 |
3 | 37,558.82 |
2 | 10,092.45 |
7 | 33,695.03 |
6 | 11,240.08 |
5 | 13,905.29 |
9 | 8,586.86 |
The output shows all the employees’ IDs and their respective sales in the first half of 2022.
11. Using SUM() and GROUP BY
This query uses the aggregate function SUM()
with GROUP BY. In SQL, aggregate functions work on groups of data; for example, SUM(sales)
shows the total of all the values in the sales
column. It’s useful to know about this function when you want to put data into groups and show the total for each group.
Query
SELECT department, SUM (salary) AS total_salaries FROM employees GROUP BY department; |
Explanation
The purpose of the above query is to find the total salary amount for each department. This is achieved in the following way.
First, select the column department from the table employees
. Then, use the SUM()
function. As we want to add the salary values, we specify the column salary in the function. Also, we give this calculated column the alias total_salaries
.
Finally, the output is grouped by the column department.
Note: Any non-aggregated column appearing in SELECT must also appear in GROUP BY. But this is logical – the whole purpose is to group data by department, so of course we’ll put it in GROUP BY
.
Output
department | total_salaries |
---|---|
Corporate | 21,919.82 |
Private Individuals | 17,072.92 |
The output shows all the departments and the sum of total monthly salary costs by department.
12. Using COUNT() and GROUP BY
Here’s another basic SQL query that uses an aggregate function. This time, it’s COUNT()
. You can use it if you want to group data and show the number of occurrences in each group.
Query
SELECT department, COUNT (*) AS employees_by_department FROM employees GROUP BY department; |
Explanation
We want to show the number of employees by department.
Select the department from the table employees
. Then, use the COUNT()
aggregate function. In this case, we use the COUNT(*)
version, which counts all the rows. We give the column the alias employees_by_department
.
As a final step, we group the output by the department.
Note: COUNT(*)
counts all the rows, including those with the NULL
values. If you don’t want to include the possible NULL values in your output, use the COUNT(column_name)
version of the function. We can use COUNT(*)
here because we know no NULL
values are in the table.
Output
department | employees_by_department |
---|---|
Corporate | 5 |
Private Individuals | 5 |
There are two departments, each with five employees.
13. Using AVG() and GROUP BY
The AVG()
function calculates the average value. You can use this query whenever you want to group data and show the average value for each group.
Query
SELECT department, AVG (salary) AS average_salary FROM employees GROUP BY department; |
Explanation
The query is the same as the last one, only this time we use the AVG()
function, as we want to calculate the average salary by department.
We select the department, use AVG()
with the salary
column, and group the output by department.
Output
department | average_salary |
---|---|
Corporate | 4,383.96 |
Private Individuals | 3,414.58 |
The output shows two departments and their average salaries.
14. Using MIN() and GROUP BY
This is another query that combines an aggregate function with GROUP BY
. Use it whenever you want to find the minimum values for each group.
Query
SELECT department, MIN (salary) AS minimum_salary FROM employees GROUP BY department; |
Explanation
Again, we use the same query and change only the aggregate function.
The query calculates the minimum salary by department.
Output
department | minimum_salary |
---|---|
Corporate | 2,894.51 |
Private Individuals | 2,845.56 |
The output shows the departments and the lowest salary in each department.
15. Using MAX() and GROUP BY
This example shows how to use the MAX()
aggregate function to show the highest value within each group.
Query
SELECT department, MAX (salary) AS maximum_salary FROM employees GROUP BY department; |
Explanation
We use the query to show the highest salary in each department, together with the department’s name.
You already know how this works. The query is the same as in the previous example, but now it uses the MAX()
function.
Output
department | maximum_salary |
---|---|
Corporate | 5,974.41 |
Private Individuals | 4,123.45 |
The output shows us the highest salaries in the Corporate and Private Individuals department.
16. Using SUM(), WHERE, and GROUP BY
This one might seem more complicated, but it’s still a basic SQL query. It is used when you want to show the total values for each group but you want to include only specific rows in the sum.
Query
SELECT department, SUM (salary) AS total_salary FROM employees WHERE salary > 3500 GROUP BY department; |
Explanation
The query will show the total salary by department, but it will include only individual salaries above $3,500 in the sum. Here’s how it works.
First, of course, select the departments and use SUM()
with the salary column from the table employees
. You learned that already.
Then use the WHERE
clause to specify the values you want included in the sum. In this case, it’s where the column salary is higher than 3,500. In other words, the query will now sum only values above 3,500.
Finally, group by department.
Output
department | total_salary |
---|---|
Private Individuals | 11,217.95 |
Corporate | 19,025.31 |
These totals now include only salaries above $3,500. Compare this to the output from the eleventh example (shown below; mind the different sorting), and you’ll see that the totals are lower. It’s logical, as the below output also includes salaries equal to or less than $3,500.
department | total_salaries |
---|---|
Corporate | 21,919.82 |
Private Individuals | 17,072.92 |
17. Using COUNT(), WHERE, and GROUP BY
This is also one of the queries we advise you to include in your SQL toolbox. It’s similar to the previous one, as it uses an aggregate function. This type of query can be used when you want to show the number of occurrences for each group.
Query
SELECT department, COUNT (*) AS number_of_employees FROM employees WHERE salary > 3500 GROUP BY department; |
Explanation
This is similar to the previous query, only it uses the COUNT()
aggregate function. Its goal is to show the department name and the number of employees in that department, but it counts only the employees with a salary above $3,500.
To achieve that, first select the department. Then use COUNT(*)
to count all the rows within each department. Each row equals one employee. We are free to use this version of the COUNT()
function because we know there are no NULL
rows.
Now, use WHERE
to include only employees with salaries higher than $3500 in the counting.
In the end, you only need to group data by department.
Output
department | number_of_employees |
---|---|
Private Individuals | 3 |
Corporate | 4 |
The output shows there are three employees in the Private Individuals department paid above $3,500 and there are four such employees in the Corporate department.
Some employees are obviously missing, as they should be. We learned in one of the previous examples that there are five employees in each department.
18. Accessing Data in Two Tables Using INNER JOIN
This type of query is used whenever you want to access data from two or more tables. We’ll show you INNER JOIN, but it’s not the only join type you can use.
Here’s a short overview of join types in SQL. These are the full join names. What’s shown in the brackets can be omitted in the query and the join will work without it.
SQL Join Type | Description |
---|---|
(INNER) JOIN | Returns the matching values from both tables. |
LEFT (OUTER) JOIN | Returns all the values from the left table and only the matching values from the right table. |
RIGHT (OUTER) JOIN | Returns all the values from the right table and only the matching values from the left table. |
FULL (OUTER) JOIN | Returns all the rows from both tables. |
CROSS JOIN | Returns all combinations of all rows from the first and second table, i.e. the Cartesian product. |
Query
SELECT e.id, e.first_name, e.last_name, qs.q1_2022 + qs.q2_2022 + qs.q3_2022 + qs.q4_2022 AS total_sales_2022 FROM employees e JOIN quarterly_sales qs ON e.id = qs.employee_id; |
Explanation
This query wants to show each employee’s ID and name, together with their total sales in 2022.
For that, it uses JOIN
, as the required data is in both tables of our dataset.
Let’s start explaining the query with the FROM
clause. This is familiar: to use the data from the table employees
, you need to reference it in FROM
. We also give this table an alias (‘e’), so that we don’t have to write the table’s full name later on.
After that, we use the JOIN
keyword to join the second table. We do that by referencing the table
in quarterly_sales
JOIN
and giving it the alias ‘qs’.
Now comes the ON
condition. It is used to specify the columns on which the two tables will be joined. Usually, those are the columns that store the same data in both tables. In other words, we join the tables on the primary and foreign keys. A primary key is a column (or columns) that uniquely defines each row in the table. A foreign key is a column in the second table that refers to the first table. In our example, the column id
from the table employees
is its primary key. The column employee_id
from the table quarterly_sales
is the foreign key, as it contains the value of the column id
from the first table.
So we’ll use these columns in ON
, but we also need to specify which table each column is from. Remember, we gave our tables aliases. This will come in handy here, as we won’t need to write the tables’ full names – only one letter for each table. We write the first table’s alias (instead of its full name), separate them with a dot, and then the column name. We put the equal sign, the second table’s alias, and the column name.
Now that we have two tables joined, we are free to select any column from both tables. We select id
, first_name
, and last_name
from employees
. Then we add each column from the table quarterly_sales showing the quarterly sales and name it total_sales_2022
. Each column in SELECT
also has the table alias before it, with the alias and the column name separated by a dot.
Note: When joining tables, using the table names in front of the column names in SELECT
is advisable. This will make it easier to determine which column comes from which table. Also, the tables can have columns of the same name. However, table names can become wordy, so giving them aliases in JOIN
is also advisable. That way, you can use much shorter aliases (instead of the full table names) in front of the column names.
Output
id | first_name | last_name | total_sales_2022 |
---|---|---|---|
8 | Stephanie | Marx | 22,993.23 |
4 | Lucy | Patterson | 30,595.57 |
10 | Victoria | Pollock | 6,770.16 |
1 | Paul | Garrix | 45,443.38 |
3 | Matthias | Johnson | 58,233.67 |
2 | Astrid | Fox | 20,312.48 |
7 | Walter | Deer | 62,774.59 |
6 | Claudia | Conte | 17,734.94 |
5 | Tom | Page | 28,637.65 |
9 | Luca | Pavarotti | 25,023.21 |
The output lists each employee and shows their total sales in 2022.
19. Accessing Data in Two Tables Using INNER JOIN and Filtering Using WHERE
Of course, you can filter data in joined tables the same way as you can with only one table. You’ll again need the WHERE
clause.
Query
SELECT e.id, e.first_name, e.last_name, qs.q4_2022-qs.q3_2022 AS sales_change FROM employees e JOIN quarterly_sales qs ON e.id = qs.employee_id WHERE qs.q4_2022-qs.q3_2022 < 0; |
Explanation
We tweaked the previous query to show the decrease in sales between the third and the fourth quarter.
Here’s how we did it. Just as we did earlier, we selected the employee’s ID and name.
We subtracted one quarter from another to calculate the change between the quarters. In this case, it’s the column with the fourth quarter sales minus the third quarter sales. This new column is named sales_change
.
The tables are joined exactly the same way as in the previous example.
To show only the sales decrease, we use the WHERE
clause. In it, we again subtract the third quarter from the fourth and set the condition that the result has to be below zero, i.e. a decrease. As you noticed, WHERE
comes after the tables are joined.
Output
id | first_name | last_name | sales_change |
---|---|---|---|
8 | Stephanie | Marx | -2,224.11 |
4 | Lucy | Patterson | -5,151.55 |
1 | Paul | Garrix | -21,233.46 |
3 | Matthias | Johnson | -3,771.83 |
7 | Walter | Deer | -189.32 |
6 | Claudia | Conte | -1,500.44 |
9 | Luca | Pavarotti | -1,138.55 |
The output shows all the employees who had a sales decrease in the last quarter and the amount of that decrease.
20. Accessing Data in Two Tables Using INNER JOIN, Filtering Using WHERE, and Sorting With ORDER BY
You probably noticed that outputs in our two latest examples are sorted a bit randomly. This is not something you have to put up with – you can order data with ORDER BY
even when using two tables.
Query
SELECT e.id, e.first_name, e.last_name, qs.q4_2022 FROM employees e JOIN quarterly_sales qs ON e.id = qs.employee_id WHERE qs.q4_2022 > 5000 ORDER BY qs.q4_2022 DESC ; |
Explanation
The query is not much different from the previous one. We again select the employee’s ID and name. We also add the sales in the last quarter of the year. The tables are then joined the same way as earlier. We use the WHERE
clause to show only quarterly sales above $5,000.
Also, we want to sort the output. This is not different from what we learned earlier: simply write the column name in ORDER BY
and sort it the way you want. In our example, we are sorting from the highest to the lowest quarterly sales.
Output
id | first_name | last_name | q4_2022 |
---|---|---|---|
7 | Walter | Deer | 14,445.12 |
3 | Matthias | Johnson | 8,451.51 |
5 | Tom | Page | 7,788.01 |
9 | Luca | Pavarotti | 7,648.90 |
2 | Astrid | Fox | 5,322.05 |
The output shows all five employees whose sales were above $5,000 in the last three months of 2022.
From Basic SQL Queries to SQL Master
If you want to master SQL, you must be comfortable using these 20 basic SQL queries. These are the fundamentals that will allow you to build solid SQL knowledge.
This kind of knowledge is achieved by a lot of practice and experience. You need to write the queries on your own. Our interactive SQL Basics course is brimming with basic SQL query examples! It contains over 100 interactive SQL exercises for you to solve on your own. Try it, and we’re sure you won’t regret it!