3 Notes of 3 Unit
3 Notes of 3 Unit
3 - NOtes of 3 unit
What Is SQL?
The first thing is to know what SQL is. 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.
dataset, and then we’re off to writing and explaining basic SQL queries.
Dataset
The dataset consists of two tables. The first one is shown below; you can create this table by copying and
running this query from GitHub.
Like any table, it has a name: employees. Each table has columns which also have names. They describe what
data each column contains.
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. It is shown below, and the query for creating it is here.
employee_id – The unique ID of the employee. Also, a foreign key referencing the column id from the
table employees.
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.
The basic form of an SQL query includes three clauses: SELECT, FROM, and WHERE.
The SELECT clause speci昀椀es the columns that you want to retrieve from the database. For example, if you
want to retrieve all columns from a table, you can use the asterisk (*) symbol.
The FROM clause speci昀椀es the table or tables from which you want to retrieve data.
The WHERE clause is used to 昀椀lter the data based on speci昀椀c conditions. For example, if you want to retrieve
only those records where the value in a particular column is greater than a certain value, you can use the
WHERE clause.
Here is an example of a basic SQL query:
SELECT *
FROM table_name
WHERE column_name = 'value';
This query retrieves all columns from the table named table_name where the value in the column
named column_name is equal to 'value'.
In SQL, UNION, INTERSECT, and EXCEPT are set operators that allow you to combine or exclude rows from
two or more tables
UNION: The UNION operator combines the results of two or more SELECT statements into a single result set. It
removes duplicate rows by default. If you want to include duplicates, you can use the UNION ALL operator
instead of UNION.
INTERSECT: The INTERSECT operator returns only the rows that are common to both SELECT statements. It
also removes duplicate rows by default.
EXCEPT: The EXCEPT operator returns only the rows that are unique to the 昀椀rst SELECT statement. It also
removes duplicate rows by default.
Here is an example of how to use these operators:
FROM table1
UNION [ALL]
FROM table2
[INTERSECT | EXCEPT]
FROM table3;
A nested query is a query that appears inside another query, and it helps retrieve data from multiple tables or
apply conditions based on the results of another query. There are two types of nested queries: independent and
correlated. In independent nested queries, the execution of the inner query is independent of the outer query,
but the result of the inner query is used in the execution of the outer query. In correlated nested queries, the
output of the inner query depends on the row that is currently being executed in the outer query.
Here is an example of a nested query that uses the WHERE clause
FROM table1
WHERE column1 IN (SELECT column1 FROM table2 WHERE condition);
This query retrieves all columns from table1 where the value in column1 is equal to any value returned by
the inner query.
Aggregation operators are used to perform calculations on a set of values and return a single value. The
most commonly used aggregation operators are:
COUNT: This operator returns the number of rows in a table or the number of non-null values in a column.
SUM: This operator returns the sum of all the values in a column.
AVG: This operator returns the average of all the values in a column.
MIN: This operator returns the minimum value in a column.
MAX: This operator returns the maximum value in a column.
NULL value is a 昀椀eld with no value. If a 昀椀eld in a table is optional, it is possible to insert a new record or
update a record without adding a value to this 昀椀eld. Then, the 昀椀eld will be saved with a NULL value. Note that a
NULL value is di昀昀erent from a zero value or a 昀椀eld that contains spaces 1.
To test for NULL values in SQL, you can use the IS NULL and IS NOT NULL operators instead of comparison
operators such as =, <, or > .
Here is an example of how to use these operators:
SELECT column_names
FROM table_name
WHERE column_name IS NULL;
SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;
integrity constraints are rules that help ensure the accuracy and reliability of data in the database. They
ensure that certain conditions are met when data is inserted, updated, or deleted. While primary key, unique,
and foreign key constraints are commonly discussed and used, SQL allows for more complex constraints
through the use of CHECK and custom triggers. Here are some examples of complex integrity constraints:
1. Using CHECK Constraints: Ensuring a range: You might want a column to only have values within a certain
range. Example: CREATE TABLE Employees ( ID INT PRIMARY KEY, Age INT CHECK (Age
>= 18 AND Age <= 30) ); Pattern matching: Ensure data in a column matches a particular format.
Example: CREATE TABLE Students ( ID INT PRIMARY KEY, Email VARCHAR(255) CHECK
(Email LIKE '%@%.%') );
2. Composite Primary and Foreign Keys: These are cases where the uniqueness or referential integrity
constraint is applied over more than one column. Example: CREATE TABLE OrderDetails ( OrderID
INT, ProductID INT, Quantity INT, PRIMARY KEY (OrderID, ProductID), FOREIGN
KEY (OrderID) REFERENCES Orders(OrderID), FOREIGN KEY (ProductID)
REFERENCES Products(ProductID) );
3. Using Stored Procedures: Sometimes, instead of direct data manipulation on tables, using stored procedures
can help maintain more complex integrity constraints by wrapping logic inside the procedure. For instance, you
could have a procedure that checks several conditions before inserting a record.
4. Using Triggers: A trigger is a procedural code in a database that automatically executes in response to certain
events on a particular table or view. Essentially, triggers are special types of stored procedures that run
automatically when an INSERT, UPDATE, or DELETE operation occurs. A trigger is a prede昀椀ned action that the
database automatically executes in response to certain events on a particular table or view. Triggers are
typically used to maintain the integrity of the data, automate data-related tasks, and extend the database
functionalities. When implementing complex constraints, it’s crucial to strike a balance. While they can ensure
data integrity, they can also add overhead to the database system and increase the complexity of the schema
and the operations performed on it. Proper documentation and understanding of each constraint’s purpose are
essential.
A trigger is a procedure which is automatically invoked by the DBMS in response to changes to the database, and is
specified by the database administrator (DBA). A database with a set of associated triggers is generally called an
active database.
Parts of trigger
A triggers description contains three parts, which are as follows −
Use of trigger
Triggers may be used for any of the following reasons −
To implement any complex business rule, that cannot be implemented using integrity constraints.
Triggers will be used to audit the process. For example, to keep track of changes made to a table.
Trigger is used to perform automatic action when another concerned action takes place.
Types of triggers
The different types of triggers are explained below −
Statement level trigger − It is 昀椀red only once for DML statement irrespective of number of rows a昀昀ected
by statement. Statement-level triggers are the default type of trigger.
Before-triggers − At the time of de昀椀ning a trigger we can specify whether the trigger is to be 昀椀red before a
command like INSERT, DELETE, or UPDATE is executed or after the command is executed. Before triggers are
automatically used to check the validity of data before the action is performed. For instance, we can use
before trigger to prevent deletion of rows if deletion should not be allowed in a given case.
After-triggers − It is used after the triggering action is completed. For example, if the trigger is associated
with the INSERT command then it is 昀椀red after the row is inserted into the table.
Row-level triggers − It is 昀椀red for each row that is a昀昀ected by DML command. For example, if an UPDATE
command updates 150 rows then a row-level trigger is 昀椀red 150 times whereas a statement-level trigger is
昀椀red only for once.
A database with a set of triggers is known as an active database. Due to the overall complexity involved
in understanding the impacts of different triggers, maintaining these databases is extremely tough.
Before executing the query in such a database, the DBMS checks to see if the specific trigger provided
in the query that updates the database is activated.
Multiple triggers can be activated within a single statement at once. If the trigger is active, the condition
section is executed first, followed by the action part if the stated condition is true.
In this case, the DBMS randomly executes each of the triggers. When an action phase of a trigger is
executed, it might either activate other triggers or the same trigger that initiated the action. The term
“recursive trigger” refers to a sort of trigger that triggers itself. Although the DBMS executes such
trigger chains in a predetermined manner, it has an impact on the idea of comprehension.
ACTIVE DATABASES
An active database is one that has an event-driven structure, which is typically implemented in the
process of Event Condition Action rules which can respond to events both inside and outside the
database.
An active database system (ADBS) monitors events of interest and, when they arise, initiates a prompt
response.
It’s commonly used for security monitoring, alerting, information gathering, and authorization.
It has all of the principles of a traditional database, such as data modeling capabilities, query
language, and so on.
It includes all typical database tasks such as data definition, data manipulation, storage
management, and so on.
It must be able to assess situations and carry out actions. This implies that rule execution must be
implemented.
TRIGGERS
Source: Triggers
PARTS OF TRIGGER-
Event
An event is a database change that activates the trigger. A triggering event is the SQL statement that
fires a trigger.
An INSERT, UPDATE, or DELETE statement are the example for a specific table that can be its
triggering event.
Restriction
A trigger restriction specifies a Boolean statement that must be TRUE for the trigger to activate. If the
trigger restriction is FALSE, the trigger action will not be executed. A trigger restriction is an option for
triggers which are activated for each row. Its goal is to govern the execution of a trigger on a conditional
basis. A trigger restriction is provided using a WHEN clause. It is an optional component of trigger.
Action
A trigger action is the technique that contains the SQL statements and PL/SQL code that will be
invoked when a triggering statement is delivered and the trigger restriction is TRUE.
TYPES OF TRIGGERS
A. Level triggers-
Level trigger has two types i.e. Row Level Trigger and Statement Level Trigger that are explained below
-
A row-level trigger triggers once for each row affected by the triggering event. Row level trigger uses
a FOR EACH ROW clause in its triggering statement always.
Data-related operations including data auditing and data validation derive from row-level triggers.
Statement level triggers are default triggers that can be created once a trigger is created without
requiring use for each row statement.
Statement level trigger fires for only once for each triggering event.
DEMO-
CODE:
OUTPUT:
B. Event Triggers -
Event triggers are categorized into three types that are DDL, DML and database triggers. Operations
performed by them are listed below -
1. DDL triggers
SQL Server’s DDL triggers are triggered by various data definition language (DDL) events such as
Create, Alter, Drop, Grant, etc,. DDL triggers are only activated once the DDL statements that set
them off have been executed.
Events that affect local or global temporary tables and stored procedures do not activate DDL
triggers.
2. DML triggers
DML triggers are a form of stored method that takes place automatically whenever a data
manipulation language (DML) event occurs that affects the table or view specified in the trigger.
3. DATABASE triggers
Database triggers are triggered by the execution of any database operation, such as LOGON,
LOGOFF, SHUTDOWN, SERVERERROR, and so on.
DEMO-
CODE:
CODE:
OUTPUT:
C. Timing Triggers -
1. Before trigger
A Before Trigger is a sort of trigger which executes automatically before a specific operation on the
table actually occurs.
Before triggers are used to validate data before it is accepted into the table and to evaluate values
before they are deleted from the table.
2. After trigger
An after trigger is a sort of trigger that fires automatically after a specific action on the table.
After triggers are used to update data in a table after a change occurs.
DEMO-
CODE:
OUTPUT:
ADVANTAGES
7. Triggers can be used to log an event and can also store the information on the table.
DISADVANTAGES
2. It only provides expanded validations; not all validations are available through SQL triggers.
3. If we activate the incorrect trigger by accident, we risk losing the original data.
5. Even if there is a minor inaccuracy in the query, it can generate logical issues in the application.
USESS OF TRIGGER-
3. Triggers are used to perform automatic actions when another action is triggered.
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
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
first_name
Paul
Astrid
Matthias
Lucy
Tom
Claudia
Walter
Stephanie
Luca
Victoria
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.
Output
first_name last_name
Paul Garrix
Astrid Fox
Matthias Johnson
Lucy Patterson
Tom Page
Claudia Conte
Walter Deer
Stephanie Marx
Luca Pavarotti
Victoria Pollock
= Is equal to
Query
SELECT
first_name,
last_name,
salary
FROM employees
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.
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.
Query
SELECT
first_name,
last_name
FROM employees
Explanation
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
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
Query
SELECT
first_name,
last_name
FROM employees
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.
Query
SELECT
first_name,
last_name,
salary
FROM employees
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
The output is ordered by salary. When the salary is the same (green rows), the data is ordered alphabetically by
last name.
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
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
The query returns only three employees and their salaries, as they are the only ones that satisfy the conditions.
+ Addition
- Subtraction
* Multiplication
/ Division
Query
SELECT
employee_id,
FROM quarterly_sales;
Explanation
In the above query, we want to find the sales in the first half of 2022 for each employee.
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
employee_id h1_2022
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.
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.
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
The output shows all the departments and the sum of total monthly salary costs by department.
Query
SELECT
department,
COUNT(*) AS employees_by_department
FROM employees
GROUP BY department;
Explanation
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.
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
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
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.
Output
department minimum_salary
Corporate 2,894.51
The output shows the departments and the lowest salary in each department.
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
The output shows us the highest salaries in the Corporate and Private Individuals department.
Query
SELECT
department,
SUM(salary) AS total_salary
FROM employees
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.
Output
department total_salary
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
Query
SELECT
department,
COUNT(*) AS number_of_employees
FROM employees
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.
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.
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.
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,
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 quarterly_sales in 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
The output lists each employee and shows their total sales in 2022.
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
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
The output shows all the employees who had a sales decrease in the last quarter and the amount of that
decrease.
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
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
The output shows all five employees whose sales were above $5,000 in the last three months of 2022.