CRUD
CRUD
1. CREATE
This operation adds new data (rows) to a database table. In SQL, the INSERT INTO statement is used for
this purpose.
Syntax:
Example:
2 Bob 25 Chicago
2. READ
This operation retrieves data from the database. In SQL, the SELECT statement is used for reading.
Syntax:
FROM table_name
WHERE condition;
Example:
Result:
2 Bob 25 Chicago
FROM Customers
Result:
Name Age
Bob 25
3. UPDATE
This operation modifies existing data in the database. In SQL, the UPDATE statement is used.
Syntax:
UPDATE table_name
WHERE condition;
Example:
UPDATE Customers
SET Age = 26
2 Bob 26 Chicago
4. DELETE
This operation removes data from the database. In SQL, the DELETE statement is used.
Syntax:
WHERE condition;
Example:
9. WHERE CustomerID = 3;
These techniques help refine the data retrieved from a database to get meaningful insights. Here's an in-
depth look with advanced use cases.
1. Filtering Data
Filtering is done using the WHERE clause, allowing you to retrieve specific rows based on conditions.
Advanced Filtering
Examples:
a) Filter Customers Based on Multiple Conditions Retrieve customers from Customers table who are
older than 25 and live in either New York or Chicago:
SELECT *
FROM Customers
b) Filter Using Wildcards Find all customers whose name starts with 'A':
SELECT *
FROM Customers
SELECT *
FROM Customers
2. Ordering Data
Ordering allows you to sort query results using the ORDER BY clause.
Advanced Ordering
Examples:
a) Order by Multiple Columns Sort customers first by City (alphabetically) and then by Age (descending):
SELECT *
FROM Customers
FROM Customers
3. Limiting Data
Limiting reduces the number of rows returned, often combined with ORDER BY.
Advanced Limiting
Examples:
FROM Customers
LIMIT 3;
b) Pagination Fetch data for page 2 where each page has 5 rows:
SELECT *
FROM Customers
ORDER BY CustomerID
LIMIT 5 OFFSET 5;
Retrieve the top 2 youngest customers from Chicago or New York, sorted by age:
SELECT *
FROM Customers
LIMIT 2;
Question:
Find the top 5 cities with the most customers and their total age sum, sorted by the total age sum in
descending order.
Solution:
FROM Customers
GROUP BY City
LIMIT 5;
Complex Filtering with Subqueries
Retrieve customers whose age is above the average age of all customers:
SELECT *
FROM Customers
SELECT AVG(Age)
FROM Customers
);
Grouping and aggregation are essential for analyzing data by categorizing it into groups and applying
aggregate functions like COUNT, SUM, AVG, MAX, and MIN.
1. GROUP BY Clause
The GROUP BY clause is used to group rows with the same values in specified columns into summary
rows, such as totals or averages.
Basic Syntax:
FROM table_name
GROUP BY column1;
Example:
FROM Customers
GROUP BY City;
2. Aggregate Functions
These functions perform calculations on a set of values and return a single result.
Example:
FROM Customers
GROUP BY City;
The HAVING clause filters groups after aggregation (similar to WHERE but for grouped data).
FROM Customers
GROUP BY City
Example: Find the total number of customers grouped by city and age:
FROM Customers
Calculate the percentage of customers in each city relative to the total number of customers.
Example:
SELECT City,
COUNT(*) AS CustomerCount,
FROM Customers
GROUP BY City;
Example: Find the difference between the maximum and minimum ages of customers in each city:
FROM Customers
GROUP BY City;
Example:
1 1 100
2 2 200
3 1 150
FROM Customers c
GROUP BY c.Name;
الجملةSQL
SELECT c.Name, SUM(o.Amount) AS TotalSpent
FROM Customers c
GROUP BY c.Name;
بيانات افتراضية
جدولCustomers:
2 Bob 25 Chicago
3 Charlie 28 Boston
جدولOrders:
1 1 100
2 1 200
3 2 150
4 3 300
5 1 50
نتيجة الجملة
وحساب المجموع اإلجمالي للمبالغ التي أنفقها كل عميل، يتم تجميع الطلبات حسب العمالء،بعد تطبيق الجملة.
Name TotalSpent
Alice 350
Bob 150
Charlie 300
5. GROUP BY with Subqueries
Example:
Find the top city with the highest average customer age:
FROM Customers
GROUP BY City
HAVING AVG(Age) = (
SELECT MAX(AVG(Age))
FROM Customers
GROUP BY City
);
Window functions allow performing aggregate calculations without collapsing rows, which provides a
more flexible alternative to GROUP BY.
Example:
Add a column showing the total number of customers in the same city:
FROM Customers;
Question:
Find the city with the highest total order amount, and list its total along with the number of customers.
Solution:
SELECT c.City,
SUM(o.Amount) AS TotalOrderAmount,
COUNT(DISTINCT c.CustomerID) AS CustomerCount
FROM Customers c
GROUP BY c.City
LIMIT 1;
In SQL, joins are used to combine rows from two or more tables based on a related column between
them. They are a cornerstone of relational database operations, enabling users to extract meaningful
insights from data spread across multiple tables.
There are several types of joins, each serving a specific purpose depending on the analysis requirements:
1. INNER JOIN
Definition: Returns only the rows where there is a match in both tables.
Use Case: When you need data that exists in both tables.
FROM employees
ON employees.department_id = departments.department_id;
Definition: Returns all rows from the left table and matched rows from the right table. If no
match exists, NULLs are returned for columns from the right table.
Use Case: When you want to include all records from the left table, regardless of whether
there's a match in the right table.
Example:
FROM employees
ON employees.department_id = departments.department_id;
Definition: Returns all rows from the right table and matched rows from the left table. If no
match exists, NULLs are returned for columns from the left table.
Use Case: When you want to include all records from the right table, regardless of whether
there's a match in the left table.
Example:
FROM employees
ON employees.department_id = departments.department_id;
Definition: Combines the results of both LEFT JOIN and RIGHT JOIN. Returns all rows when
there's a match in either table, and NULLs for unmatched rows in both.
Use Case: When you need a comprehensive dataset showing all records from both tables,
regardless of matches.
Example:
FROM employees
Output: All employees and all departments, showing NULLs where there is no match.
5. CROSS JOIN
Definition: Returns the Cartesian product of the two tables, meaning every row in the first table
is paired with every row in the second table.
Use Case: Rarely used directly but helpful for scenarios like generating test datasets or
combining every combination of items.
Example:
FROM employees
6. SELF JOIN
Definition: A table is joined with itself. Used when the table has a hierarchical or relational
structure within itself.
Example:
FROM employees e1
ON e1.manager_id = e2.employee_id;
3. FROM employees e
7. Handle NULLs: Be cautious with NULL values, especially in outer joins. Use COALESCE to replace
NULLs with default values.
9. FROM employees
employees Table
1 Alice 101
2 Bob 102
3 Charlie NULL
4 David 103
departments Table
department_id department_name
101 Sales
department_id department_name
102 Marketing
103 IT
1. INNER JOIN
FROM employees e
ON e.department_id = d.department_id;
Output:
1 Alice Sales
2 Bob Marketing
4 David IT
Explanation: Only employees with a matching department_id in the departments table are included.
2. LEFT JOIN
FROM employees e
ON e.department_id = d.department_id;
Output:
1 Alice Sales
employee_id name department_name
2 Bob Marketing
3 Charlie NULL
4 David IT
Explanation: All employees are listed, but Charlie has no matching department, so department_name is
NULL.
3. RIGHT JOIN
FROM employees e
ON e.department_id = d.department_id;
Output:
1 Alice Sales
2 Bob Marketing
4 David IT
Explanation: All departments are listed, even if no employees are assigned to them, as seen with
"Human Resources."
Query: List all employees and departments, showing unmatched rows from both tables.
FROM employees e
ON e.department_id = d.department_id;
Output:
1 Alice Sales
2 Bob Marketing
3 Charlie NULL
4 David IT
Explanation: Shows all employees and all departments. Missing matches are represented by NULLs.
5. CROSS JOIN
FROM employees e
Output:
employee_name department_name
Alice Sales
Alice Marketing
Alice IT
Bob Sales
Bob Marketing
Bob IT
Charlie Sales
Charlie Marketing
employee_name department_name
Charlie IT
David Sales
David Marketing
David IT
6. SELF JOIN
Query: Find employees and their managers (assuming manager_id is stored in employees table).
1 Alice 101 3
2 Bob 102 1
4 David 103 1
Query:
FROM employees e1
ON e1.manager_id = e2.employee_id;
Output:
employee_name manager_name
Alice Charlie
Bob Alice
employee_name manager_name
Charlie NULL
David Alice
A subquery (or nested query) is a query embedded within another SQL query. It allows you to perform
operations on the result of one query and use it in another query. Subqueries are often used in WHERE,
HAVING, FROM, or SELECT clauses to break down complex problems into manageable steps.
Types of Subqueries
1. Single-Row Subquery: Returns a single value (e.g., one row and one column).
3. Correlated Subquery: References a column from the outer query and is evaluated repeatedly.
Real Examples
Example Tables:
employees Table:
departments Table:
department_id department_name
101 Sales
department_id department_name
102 Marketing
103 IT
1. Single-Row Subquery
FROM employees
Subquery:
Output:
name salary
Bob 60000
Charlie 70000
2. Multi-Row Subquery
Problem: List all employees who work in departments with more than one employee.
FROM employees
WHERE department_id IN (
SELECT department_id
FROM employees
GROUP BY department_id
);
Subquery:
SELECT department_id
FROM employees
GROUP BY department_id
Output:
name department_id
Alice 101
Charlie 101
3. Correlated Subquery
Problem: Find employees whose salary is higher than the average salary of their respective department.
FROM employees e1
SELECT AVG(salary)
FROM employees e2
);
How It Works:
For each row in the outer query (e1), the subquery calculates the average salary of the
respective department (e2).
Output:
(SELECT d.department_name
FROM departments d
FROM employees e;
Output:
David 45000 IT
Problem: Find the average salary for each department and list departments where the average salary
exceeds 55000.
FROM (
FROM employees e
JOIN departments d
ON e.department_id = d.department_id
GROUP BY d.department_name
) AS dept_avg
Derived Table:
SELECT d.department_name, AVG(e.salary) AS avg_salary
FROM employees e
JOIN departments d
ON e.department_id = d.department_id
GROUP BY d.department_name;
o Sales: 60000
o Marketing: 60000
o IT: 45000
Main Query: Filter for departments where the average salary exceeds 55000.
Output:
department_name avg_salary
Sales 60000
Marketing 60000
6. EXISTS Subquery
SELECT department_name
FROM departments d
WHERE EXISTS (
SELECT 1
FROM employees e
);
Subquery:
SELECT 1
FROM employees e
Output:
department_name
Sales
Marketing
IT
Multi-Row Subqueries: Use with IN, ANY, or ALL to match multiple values.
Correlated Subqueries: Use when the subquery depends on data from the outer query.
Subqueries in FROM: Organize subquery results into temporary tables for further processing.
1. Ranking Functions
ROW_NUMBER(): Assigns a unique number to each row in the window, starting from 1.
SUM(), AVG(), MIN(), MAX(), COUNT(): Perform aggregations over the window.
3. Value Functions
LEAD(), LAG(): Fetch the next or previous value relative to the current row.
Example Tables
sales Table:
1. ROW_NUMBER()
Problem: Assign a unique number to each sale within each department, ordered by amount
(descending).
FROM sales;
Output:
Problem: Rank sales within each department, with ties handled differently.
Output:
Explanation:
3. NTILE(n)
FROM sales;
Output:
4. SUM()
Problem: Calculate a running total of sales for each department, ordered by sale_date.
SELECT employee_name, department, amount, sale_date,
FROM sales;
Output:
Problem: Compare each employee's sale with the next and previous sales in their department.
FROM sales;
Output:
Problem: Show the first and last sale amount in each department.
SELECT employee_name, department, amount,
FROM sales;
Output:
Summary
Window functions add new insights while preserving the original rows.