Công TH C SQL
Công TH C SQL
A nested query involves using multiple select statements to retrieve specific information. As we delve into more advanced query
writing, understanding nested queries becomes essential as they allow us to retrieve precise data by using the results from one select
statement to inform another.
Let's begin with an example. Consider the scenario where we need to find the names of all employees who have sold over $30,000
worth of products to a single client. We have a "works_with" table containing total sales, but it lacks employees' first and last names.
We can use a nested query to retrieve this information.
SELECT employee_id
FROM works_with
WHERE total_sales > 30000;
This query retrieves all the employee IDs with sales over $30,000 to any client.
Next, let's explore another example. We want to find all clients who are handled by the branch managed by Michael Scott. To do this,
we need to retrieve the branch ID managed by Michael and then find the clients associated with that branch.
SELECT branch_id
FROM branch
WHERE manager_id = 102;
This query finds the branch ID that Michael Scott manages. In this case, it returns the ID for the Scranton branch.
SELECT client_name
FROM client
WHERE branch_id = (
SELECT branch_id
FROM branch
WHERE manager_id = 102
)
LIMIT 1;
By using a nested query, we match the clients associated with the branch managed by Michael Scott. The "LIMIT 1" ensures we only
get one result, making it suitable for cases when the manager may handle multiple branches.
SELECT *
FROM products
WHERE category NOT IN ('Electronics', 'Appliances');
SELECT *
FROM orders
WHERE payment_status IS NULL;
SELECT *
FROM customers
WHERE email IS NOT NULL;
SELECT *
FROM employees
WHERE salary BETWEEN 30000 AND 50000;
The IF() function in MySQL allows us to perform conditional logic within our queries. It evaluates a specified condition and returns one
value if the condition is true, and another value if the condition is false.
Syntax:
IF(condition, value_if_true, value_if_false)
Syntax:
IFNULL(expression, value_if_null)
Syntax:
NULLIF(expression, value)
Case Statement
In this lesson, we will explore SQL Case Statements and their use cases. A Case Statement allows you to specify conditions and
determine what values to return when those conditions are met. We will be using the "Employee Demographics" table for our
examples.
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE default_result
END
It allows you to categorize or label data based on specified conditions.
Example 1: Categorizing Age
Let's start with a simple example to understand Case Statements. Assume we want to categorize employees based on their age as
"Young" or "Old."
Now, let's dive into a more complex use case. Assume we have an "Employee Salaries" table and we want to calculate the salary after
giving different raises to different job titles.
Window functions are advanced analytical functions in MySQL that allow you to perform calculations across a set of table rows related
to the current row. They are particularly useful for tasks that involve ranking, aggregation, and calculation of running totals without
affecting the overall query result. In this lesson, we'll explore several essential window functions in MySQL.
OVER() Function
The OVER() function defines the window or subset of rows for which a window function operates. It can include an ORDER BY clause
to specify the order of rows within the window.
Group By: The Group By statement reduces the number of rows in the output by grouping them based on specified columns.
Aggregate functions, such as SUM or COUNT, are then applied to each group.
Partition By: On the other hand, Partition By doesn't reduce the number of rows returned in the output. Instead, it divides the result
set into partitions and affects how window functions are calculated within each partition.
The syntax for using the Partition By clause is as follows:
Let's start by examining the tables and the data they contain:
Now, let's use the Partition By clause to analyze the data. We want to determine the count of male and female employees in each row
of the result set.
SELECT
first_name,
last_name,
gender,
salary,
COUNT(gender) OVER (PARTITION BY gender) AS total_gender
FROM employee;
SELECT
gender,
COUNT(gender) AS total_gender
FROM employee
GROUP BY gender;
RANK() Function
The RANK() function assigns a unique rank to each distinct value in a result set, similar to DENSE_RANK(). However, it does not skip
ranks in case of ties.
DENSE_RANK() Function
The DENSE_RANK() function assigns a unique rank to each distinct value in a result set. It handles ties by skipping ranks, ensuring that
consecutive ranks are not skipped.
PERCENT_RANK() Function
The PERCENT_RANK() function calculates the relative rank of a row within a result set as a percentage.
ROW_NUMBER() Function
The ROW_NUMBER() function assigns a unique sequential integer to each row within a result set.
These operators are used to determine whether a subquery returns any rows (EXISTS) or doesn't return any rows (NOT EXISTS).
They're particularly handy for performing complex queries involving multiple tables.
SELECT EmployeeName
FROM Employees
WHERE EXISTS (
SELECT *
FROM Assignments
WHERE Assignments.EmployeeID = Employees.EmployeeID
);
SELECT ClientName
FROM Clients
WHERE NOT EXISTS (
SELECT *
FROM Orders
WHERE Orders.ClientID = Clients.ClientID
);