Complete SQL Guide
Complete SQL Guide
S
o Data refers to any information or facts
that can be recorded, stored, and
processed.
Q o
retrieval, and management.
It provides a way to store and manage large
amounts of data in a systematic manner.
o Databases can be relational (using tables) or
L non-relational (using other data models).
DBMS (Database Management System):
S
o A DBMS is software that allows users
to interact with databases.
L
RDBMS (Relational Database Management
System):
S o An RDBMS is a type of DBMS that
follows the relational model.
o It organizes data into tables with rows
Q (records) and columns (attributes).
o Relationships between tables are
defined using keys (e.g., primary keys
and foreign keys).
L
Tables
S o Tables are fundamental components of an
RDBMS.
o A table represents a collection of related
data entries.
Q o Each table consists of columns (fields) and
rows (records).
o Columns hold specific information about
• Uses structured query language (SQL) • May support SQL-like queries but not strictly SQL
• Best suited for complex queries • Suited for unstructured data and rapid
development
• Vertically scalable (increase server capacity) • Horizontally scalable (add more servers)
L • ACID properties (Atomicity, Consistency, Isolation, • Focus on performance and flexibility, may not
Durability) strictly adhere to ACID
• Ideal for multi-row transactions • Good for large sets of distributed data
• Examples: MySQL, PostgreSQL, Oracle, SQL Server, • Examples: MongoDB, Cassandra, Couchbase, Redis
SQLite
Databases vs Excel
Aspect Databases (SQL/NoSQL) Excel
S Type
Databases can be relational (SQL) or non-
relational (NoSQL).
Excel is a spreadsheet application for organizing and
analyzing data.
Databases store data in tables, rows, and Excel uses worksheets with cells arranged in rows and
Data Structure
columns. columns.
SQL databases have a predefined schema; Excel does not enforce a strict schema; you can add data
Schema
Q Use Cases
NoSQL databases have a dynamic schema.
SQL databases handle complex queries and Excel is simpler and suited for individual users or small
Complexity
large datasets. teams.
L Structured vs.
Unstructured
Databases structure data; NoSQL databases
handle unstructured data (e.g., documents).
Excel works with structured and semi-structured data
(e.g., tables, charts).
Q Numeric
o
o
DECIMAL(p, s) : Fixed-point decimal numbers (e.g., salary
with precision and scale).
FLOAT or REAL : Approximate floating-point numbers (e.g.,
age INT,
height FLOAT,
Q SQL CONSTRAINTS
L
Constraints Description Example
NOT NULL
);
S FOREIGN KEY
o
o
References a record in another table.
Ensures referential integrity.
department_id INT,
FOREIGN KEY (department_id)
REFERENCES departments(id)
);
S
DDL DQL DML DCL TCL
Q •
•
•
CREATE
DROP
ALTER
• SELECT •
•
•
INSERT
DELETE
UPDATE
• GRANT
• REVOKE
•
•
•
COMMIT
ROLLBACK
SAVEPOINT
• TRUNCATE • LOCK • SET TRANSACTION
• COMMENT • MERGE
• RENAME
L
S
DATA DEFINITION LANGUAGE (DDL)
Q
DDL commands are used to define and manage the structure of database objects
(tables, indexes, views, etc.).
L
COMMANDS Description Example
CREATE TABLE Employees (
S TRUNCATE
• Removes all records from a table
while preserving the table's
structure.
TRUNCATE TABLE student;
Q COMMENT
• Adds descriptive comments to the data
dictionary for a table.
COMMENT ON TABLE students_info IS
'Stores student information.';
L RENAME
• Allows you to change the name of an
existing database object (e.g., table,
RENAME TABLE student TO
students_info;
column, index).
S
DATA QUERY LANGUAGE (DQL)
Q
DQL commands allow you to retrieve data from the database.
L
COMMANDS Description Example
S UPDATE Employees
• Ensures data consistency and SET Salary = Salary * 1.1
LOCK WHERE Department = 'Sales'
prevents concurrent access issues. WITH (TABLOCKX);
Q
MERGE INTO target_table AS T
USING source_table AS S
ON T.id = S.id
• Combines `INSERT`, `UPDATE`, and WHEN MATCHED THEN
S
• Grants specific privileges to users. GRANT SELECT, INSERT ON Employees
GRANT TO AnalystUser;
Q
REVOKE DELETE ON Employees FROM
• Removes privileges from users. InternUser;
L REVOKE
S
TRANSACTION CONTROL LANGUAGE (DCL)
Q
TCL commands manage transactions.
L
COMMANDS Description Example
Q SQL OPERATORS
L
COMPARISON OPERATORS
Comparison operators in SQL are used to compare two expressions and return a Boolean value (TRUE,
S FALSE, or NULL) based on the result of the comparison. These operators are commonly used in SQL
queries to filter data based on specific conditions. Here are the main comparison operators in SQL,
Q 4.
5.
Less than (<)
Greater than or equal to (>=)
: Checks
: Checks
right.
if the value on the left is less than the value on the right.
if the value on the left is greater than or equal to the value on the
6. Less than or equal to (<=) : Checks if the value on the left is less than or equal to the value on the right.
7. BETWEEN : Checks if a value is within a range (inclusive).
8. IN : Checks if a value matches any value in a list.
9. LIKE : Checks if a value matches a pattern.
L 10.
11.
IS NULL
IS NOT NULL
: Checks
: Checks
if a value is NULL.
if a value is not NULL.
Comparison operators are essential tools for PROBLEMing and managing data in SQL databases,
allowing for precise and flexible data retrieval based on specific criteria.
COMPARISON OPERATORS
PROBLEM QUERY RESULT TABLE
table
L prefixed.
1. AND : Combines two or more conditions and returns true only if all the conditions are true.
Q 2. OR : Combines two or more conditions and returns true if at least one of the conditions is true.
3. NOT : Reverses the result of a condition. It returns true if the condition is false, and vice versa.
L Logical operators are crucial for creating sophisticated queries in SQL, allowing you to filter and
retrieve data based on multiple, specific conditions. They enable the development of powerful, detailed,
and precise data retrieval strategies.
LOGICAL OPERATORS
PROBLEM QUERY RESULT TABLE
S operators allow you to execute calculations directly within your SQL queries, facilitating tasks like
summing values, computing averages, and more. The primary arithmetic operators in SQL are :
Q 2. Subtraction (-)
3. Multiplication (*)
: Subtracts one numerical value from another.
5. Modulus (%) : Returns the remainder of one numerical value divided by another.
L Arithmetic operators are essential tools in SQL for performing calculations directly within your
queries, allowing for real-time data analysis and reporting. They enhance the flexibility and power of
SQL in managing and manipulating numerical data.
ARITHMETIC OPERATORS
PROBLEM QUERY RESULT TABLE
L
4. Divides 2 numbers and returns
SELECT (5/2) AS DIVIDE;
whole number.
CASE STATEMENT
The CASE statement in SQL is used to implement conditional logic within your queries. It allows you
• Simple CASE Statement : This compares an expression to a set of simple expressions to determine the result.
Q CASE expression
WHEN value1 THEN result1
WHEN value2 THEN result2
...
ELSE default_result
END
L • Searched CASE Statement : This evaluates a set of Boolean expressions to determine the result.
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE default_result
END
CASE STATEMENT
PROBLEM:
S Fetch STAFF_ID, SALARY from STAFF_SALARY and find the range. in which salary falls. Condition
for the range is:
1. If salary>=10000 then range is “High Salary”
2. If salary between 5000 and 10000 then range is “Average Salary”
3. If salary<5000 then range is “Too Low”
Q QUERY :
SELECT STAFF_ID, SALARY,
RESULT TABLE:
CASE
WHEN SALARY >= 10000 THEN 'High Salary'
WHEN SALARY BETWEEN 5000 AND 10000 THEN 'Average Salary'
WHEN SALARY < 5000 THEN 'Too Low’
L END AS SALARY_RANGE
FROM STAFF_SALARY;
DIFFERENT WAYS TO WRITE SQL JOINS
S When writing SQL joins, there are two primary ways to express them:
1. Implicit joins
2. Explicit joins
Each method has its own style and use cases.
Key Differences:
1. Syntax and Structure:
Q • Implicit Join : Combines tables in the FROM clause and specifies conditions in the WHERE clause.
• Explicit Join : Uses specific JOIN keywords to combine tables and specifies join conditions in the ON
clause.
2. Readability:
• Implicit Join : Can become cluttered and harder to read with complex queries and multiple conditions.
• Explicit Join : More readable and maintainable, as the join logic is clearly separated from filtering
L 3. Functionality:
conditions.
• Implicit Join : Limited to INNER JOIN logic. Achieving LEFT JOIN, RIGHT JOIN, or FULL JOIN
functionality requires more complex and less intuitive queries.
• Explicit Join : Supports various types of joins (INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL JOIN),
making it more versatile and powerful.
IMPLICIT JOINS
Implicit joins use a comma-separated list of tables in the FROM clause and
S specify the join condition in the WHERE clause. This method was more
common in older SQL syntax but is less preferred now due to its potential for
ambiguity and decreased readability.
Example :
Example :
S 1. INNER JOIN : Retrieves records that have matching values in both tables
2. LEFT JOIN : Retrieves all records from the left table and the matched
records from the right table. Records from the left table
without a match in the right table will have NULL values for
Q the right table columns.
3. RIGHT JOIN : Retrieves all records from the right table and the matched
records from the left table. Records from the right table
without a match in the left table will have NULL values for the
left table columns.
L 4. FULL JOIN : Retrieves records when there is a match in either left or right
table. Records without a match in the other table will have
NULL values for the columns of the table without a match.
INNER JOIN
S • An INNER JOIN returns only the matching rows from both tables.
• It uses the ON keyword to specify the join condition.
• Inner Join can be represented as either "JOIN" or as "INNER JOIN".
Both are correct and mean the same.
• Resulting rows = Intersection of rows from TableA and TableB.
Q Example :
Fetch the details of the those staff who have matching records in
STAFF_SALARY table.
Query :
SELECT S.STAFF_ID,
CONCAT(S.FIRST_NAME," ",S.LAST_NAME) AS FULL_NAME,
SAL.SALARY
L FROM STAFF S
JOIN STAFF_SALARY SAL
ON S.STAFF_ID = SAL.STAFF_ID;
Here we fetched the staff_id and name of the staff from STAFF table and
salary from the STAFF_SALARY table by joining the 2 tables using the matching rows
LEFT JOIN (LEFT OUTER JOIN)
S • A LEFT JOIN returns all rows from the left table and matching rows
from the right table.
• If there’s no match in the right table, it fills with null values.
• Resulting rows = All rows from TableA + Matching rows from TableB.
Q Example :
Fetch the details of the staff from STAFF table and their matching salary from
STAFF_SALARY table.
Query :
SELECT S.STAFF_ID,
CONCAT(S.FIRST_NAME," ",S.LAST_NAME) AS FULL_NAME,
SAL.SALARY
L FROM STAFF S
LEFT JOIN STAFF_SALARY SAL
ON S.STAFF_ID = SAL.STAFF_ID;
Here for the staffs who don’t have matching rows in STAFF_SALARY table was filled with
NULL values.
RIGHT JOIN (RIGHT OUTER JOIN)
S • A RIGHT JOIN returns all rows from the right table and matching rows
from the left table.
• If there’s no match in the left table, it fills with null values.
• Resulting rows = All rows from TableB + Matching rows from TableA.
Q Example :
Fetch the salary details of the staff from STAFF_SALARY table and their
matching records from STAFF table.
Query :
SELECT S.STAFF_ID,
CONCAT(S.FIRST_NAME," ",S.LAST_NAME) AS FULL_NAME,
SAL.SALARY
L FROM STAFF S
RIGHT JOIN STAFF_SALARY SAL
ON S.STAFF_ID = SAL.STAFF_ID;
Here the non matching records from the right STAFF table is filled with null values
FULL JOIN (FULL OUTER JOIN)
• A FULL JOIN returns all rows from both tables (union of left and right
S joins).
• If there’s no match, it fills with null values.
• Resulting rows = All rows from TableA + All rows from TableB.
Example :
Fetch all the rows from both the STAFF and STAFF_SALARY table.
Query :
Q SELECT S.STAFF_ID,
CONCAT(S.FIRST_NAME," ",S.LAST_NAME) AS FULL_NAME,
SAL.SALARY
FROM STAFF S
LEFT JOIN STAFF_SALARY SAL
ON S.STAFF_ID = SAL.STAFF_ID
UNION
L SELECT S.STAFF_ID,
CONCAT(S.FIRST_NAME," ",S.LAST_NAME) AS FULL_NAME,
SAL.SALARY
FROM STAFF S
RIGHT JOIN STAFF_SALARY SAL
ON S.STAFF_ID = SAL.STAFF_ID;
Here we have all the records from both the tables and non matching records are filled with NULL values.
UNION AND UNION ALL OPERATOR
UNION OPERATOR
S • The UNION operator combines the results of two or more SELECT queries into a single result set.
• It removes duplicate rows from the combined result.
𝐊𝐞𝐲 𝐃𝐢𝐟𝐟𝐞𝐫𝐞𝐧𝐜𝐞𝐬:
1. 𝐷𝑢𝑝𝑙𝑖𝑐𝑎𝑡𝑒 𝐻𝑎𝑛𝑑𝑙𝑖𝑛𝑔:
• `𝑈𝑁𝐼𝑂𝑁`: 𝑅𝑒𝑚𝑜𝑣𝑒𝑠 𝑑𝑢𝑝𝑙𝑖𝑐𝑎𝑡𝑒𝑠.
• `𝑈𝑁𝐼𝑂𝑁 𝐴𝐿𝐿`: 𝐾𝑒𝑒𝑝𝑠 𝑑𝑢𝑝𝑙𝑖𝑐𝑎𝑡𝑒𝑠.
L 2. 𝑃𝑒𝑟𝑓𝑜𝑟𝑚𝑎𝑛𝑐𝑒:
Q Use Case
When you need a unique set of results and want to
avoid duplicates. Ideal for merging lists of unique
identifiers.
When duplicates are acceptable or necessary. Ideal
for scenarios where performance is critical, and you
know there are no duplicates or you need to keep
them for analysis.
Using UNION: Suppose you have two tables, Using UNION ALL: Using the same students and
students and alumni, and you want to list all unique alumni tables, if you want to list all names, including
Practical Example names from both tables. duplicates:
Q JOIN STAFF S
ON C.TEACHER_ID = S.STAFF_ID
WHERE C.CLASS_NAME IN ("Grade 8","Grade 9","Grade 10")
Result Table :
AND S.STAFF_TYPE="Teaching“
UNION
Here the query returned 16 rows removing the duplicate values from the table
UNION ALL OPERATOR
Syntax:
S Example :
Fetch all staff who teaches grade 8, 9, 10 and also fetch all the non-teaching
staff.
SELECT column1, column2, ...
FROM table1
Query : UNION ALL
SELECT column1, column2, ...
SELECT CONCAT(S.FIRST_NAME," ",S.LAST_NAME) AS FULL_NAME, FROM table2;
S.STAFF_TYPE, S.GENDER, S.AGE
Q FROM CLASSES C
JOIN STAFF S
ON C.TEACHER_ID = S.STAFF_ID Result Table :
WHERE C.CLASS_NAME IN ("Grade 8","Grade 9","Grade 10")
AND S.STAFF_TYPE="Teaching“
UNION ALL
Here the query returned 28 rows including the duplicate values from both the table
GROUP BY CLAUSE
S • The GROUP BY clause groups rows that have the same values in
specified columns into summary rows. It’s typically used with
Syntax:
SELECT column1,
AGGREGATE_FUNCTION
aggregate functions like COUNT, SUM, AVG, MAX, and MIN to (column2)
perform operations on each group. FROM table_name
GROUP BY column1;
Query :
SELECT CLASS_ID, COUNT(CLASS_ID) AS NO_OF_STUDENTS
FROM CLASSES
L GROUP BY CLASS_ID;
Here the query grouped same class_id together and counted the total no.of students.
HAVING CLAUSE
Query :
SELECT CLASS_ID,COUNT(1) AS NO_OF_STUDENTS
FROM STUDENT_CLASSES
L GROUP BY CLASS_ID
HAVING NO_OF_STUDENTS >100;
Here the query returned only the details of those class where no.of students >100.
AGGREGATE FUNCTIONS
Result Table :
FIND THE AVERAGE SALARY OF STAFFS.
Query :
SELECT S.STAFF_TYPE, ROUND(AVG(SAL.SALARY),2) AS AVG_SALARY
FROM STAFF S
L JOIN STAFF_SALARY SAL
ON S.STAFF_ID = SAL.STAFF_ID
GROUP BY S.STAFF_TYPE;
Here the query returned the average salary of staffs based on the staff type.
AGGREGATE FUNCTIONS
PROBLEM QUERY RESULT TABLE
Q SQL SUBQUERIES
L
SUBQUERY
A subquery, also known as an inner query or nested query, is a query embedded within another SQL query. The
subquery executes first, and its result is used by the outer query.
Subqueries can be used in various parts of an SQL statement, including the `SELECT`,
`FROM`, `WHERE`, and `HAVING` clauses.
EXAMPLE :
Find the employees who's salary is more than the average salary earned by all employees .
EXAMPLE :
Find the employees who's salary is more than the average salary earned by all employees .
• First, the subquery is executed. This subquery calculates the average salary of all employees in the EMPLOYEE table
• After calculating the average salary, the main query performs a join between the EMPLOYEE table (E) and the result of the subquery (AVERAGE).
The join condition ON E.SALARY > AVERAGE.avg_salary ensures that only employees whose salary is greater than the average salary are selected.
MULTIPLE ROW SINGLE COLUMN SUB-QUERIES
• A multiple-row subquery returns a set of rows.
• Useful when you need to compare values across multiple rows.
EXAMPLE :
-- Find department who do not have any employees
.
SELECT DEPT_NAME
FROM DEPARTMENT
WHERE DEPT_NAME NOT IN (SELECT DISTINCT
DEPT_NAME
FROM EMPLOYEE); The output table has a single column
with multiple rows
1. First the subquery will find out the departments where the employees are present.
2. Then the outer query will filter out the results of above query from the department table.
MULTIPLE ROW MULTIPLE COLUMN SUB-QUERIES
• Often used in complex queries where you need to retrieve additional columns from a subquery.
EXAMPLE:
-- Find the employees who earn the highest salary in each department.
SELECT *
FROM EMPLOYEE
WHERE (DEPT_NAME,SALARY) IN (SELECT
DEPT_NAME,
MAX(SALARY) AS MAX_SALARY
FROM EMPLOYEE
GROUP BY DEPT_NAME); The output table has multiple columns
with multiple rows
1. First the subquery will return the highest salary in each department.
2. Then the outer query will filter the employees based on above result.
CORRELATED SUBQUERIES
• A correlated subquery references columns from the outer query.
• It executes once for each row in the outer query.
EXAMPLE :
-- Find the employees in each department who earn more than the average salary in that department. .
SELECT *
FROM (SELECT store_name, SUM(price) AS total_sales
FROM sales
GROUP BY store_name) sales
JOIN (SELECT AVG(total.total_sales) AS avg_sales 1. First the total subquery will be calculated
FROM (SELECT store_name, SUM(price) AS total_sales to find the total sales of all stores
FROM sales 2. Then the average query will return the
GROUP BY store_name) total) average average sales of all stores based on above
result.
ON sales.total_sales > average.avg_sales;
3. Then the result from both the above queries will
be compared.
CLAUSES WHERE SUBQUERY CAN BE USED
Subqueries in SQL can be used in various clauses to perform complex operations. Here’s a
brief overview of where subqueries can be used:
• SELECT Clause : To return values that are included as part of the result set.
• FROM Clause : To create a temporary or derived table that the outer query can use.
• HAVING Clause : To filter groups based on aggregate values calculated by the subquery.
In the previous examples we have seen how to use subquery with FROM clause and WHERE clause.
SUBQUERY IN SELECT CLAUSE
Subqueries which return only 1 row and 1 column (scalar or correlated) is allowed with SELECT clause.
EXAMPLE :
Fetch all employee details and add remarks to those employees who earn more than the average pay.
SELECT E.*,
CASE WHEN E.SALARY > (SELECT
AVG(SALARY)
FROM EMPLOYEE)
THEN 'Above average salary'
ELSE NULL
END REMARKS
FROM EMPLOYEE E;
• The subquery calculates the average salary of all employees in the EMPLOYEE table.
• For each row in the EMPLOYEE table, the main query compares the employee's salary with the average salary obtained from the subquery.
• If the salary is greater than the average, 'Above average salary' is assigned to the REMARKS column otherwise, NULL is assigned to the REMARKS
column.
SUBQUERY IN HAVING CLAUSE
EXAMPLE :
Find the stores who have sold more units than the average units sold by all stores.
SELECT STORE_NAME,
SUM(QUANTITY) AS TOTAL_QTY
FROM SALES
GROUP BY STORE_NAME
HAVING TOTAL_QTY> (SELECT AVG(QUANTITY)
FROM SALES);
• The query groups the sales data by STORE_NAME and calculates the total quantity sold for each store.
• The subquery calculates the average quantity sold across all records in the SALES table.
• The HAVING clause filters the groups to include only those where the total quantity sold is greater than the average quantity sold across all sales,
as computed by the subquery.
SQL COMMANDS WHICH ALLOW A SUBQUERY
SQL commands that allow subqueries enable complex data retrieval and manipulation by
incorporating the results of one query within another. Here’s an overview of the primary
SQL commands that can incorporate subqueries
• INSERT COMMAND : To insert rows into a table based on the result of the subquery.
• UPDATE COMMAND : To update rows in a table based on conditions evaluated by the
subquery.
• DELETE COMMAND : To delete rows from a table based on conditions evaluated by the
subquery.
SUBQUERY WITH INSERT STATEMENT
• Subqueries can be used to insert rows based on the result of another query.
EXAMPLE :
-- Insert data to employee history table. Make sure not insert duplicate records
INSERT INTO EMPLOYEE_HISTORY
SELECT E.EMP_ID, E.EMP_NAME, D.DEPT_NAME,
E.SALARY, D.LOCATION
FROM EMPLOYEE E
JOIN DEPARTMENT D
ON E.DEPT_NAME = D.DEPT_NAME
WHERE NOT EXISTS (SELECT 1
FROM EMPLOYEE_HISTORY EH
WHERE EH.EMP_ID = E.EMP_ID);
• The main query joins the EMPLOYEE and DEPARTMENT tables based on the DEPT_NAME column.
• The NOT EXISTS subquery checks if an employee with the same EMP_ID already exists in the EMPLOYEE_HISTORY table. If the employee exists, the condition is false, and that
employee is excluded from the insert operation.
• Only those rows from the EMPLOYEE table that do not have a corresponding EMP_ID in the EMPLOYEE_HISTORY table are inserted.
SUBQUERY WITH UPDATE STATEMENT
• Subqueries can be used to update rows based on conditions evaluated by another query.
EXAMPLE :
-- Give 10% increment to all employees in Bangalore location based on the maximum salary earned by an
employee in each dept. Only consider employees in employee_history table.-
UPDATE EMPLOYEE E
SET SALARY = (SELECT MAX(SALARY)+ (MAX(SALARY)* 0.1)
FROM EMPLOYEE_HISTORY EH
WHERE EH.EMP_ID = E.EMP_ID)
WHERE DEPT_NAME IN (SELECT DEPT_NAME
FROM DEPARTMENT)
AND E.EMP_ID IN (SELECT EMP_ID
FROM EMPLOYEE_HISTORY);
• For each employee in the EMPLOYEE table, the subquery calculates the new salary.
• Where clause ensures that the employees belong to valid departments and employees exist in the EMPLOYEE_HISTORY table.
• The SALARY of each employee meeting the criteria is updated to the calculated new salary.
SUBQUERY WITH DELETE STATEMENT
• Subqueries can be used to delete rows based on conditions evaluated by another query.
EXAMPLE :
Delete all departments who do not have any employees.
L
What is a CTE?
The SQL WITH clause, also known as Common Table Expressions (CTEs), allows you to define
temporary result sets that can be referenced within a SELECT, INSERT, UPDATE, or DELETE
statement. It helps in organizing and structuring complex queries, making them more readable and
maintainable.
Temporary Scope : CTEs exist only for the duration of the query in which they are defined.
Readable Syntax : Using the WITH clause helps to simplify and clarify complex query logic.
Support for Recursion : Recursive CTEs are useful for hierarchical or recursive data structures.
Reusable Within a Query : You can reference a CTE multiple times within the same query.
Advantages of Using CTEs
• Improved Readability : Breaking down complex queries into simpler parts makes them
easier to understand and maintain.
• Hierarchical Data Handling : Recursive CTEs provide an elegant solution for querying
hierarchical data.
When to Use CTEs
• Simplifying Complex Queries : Break down complicated queries into smaller, more manageable
parts.
• Reusing Subqueries : Define a subquery once and reuse it multiple times within the
main query.
• Handling Hierarchical Data : Recursive CTEs are ideal for working with hierarchical data like
organizational charts.
• Improving Readability and Maintainability : Enhance the structure and clarity of your queries.
Syntax of a CTE
WITH cte_name AS (
SELECT column1, column2
FROM table_name
WHERE condition
)
SELECT column1, column2
FROM cte_name
WHERE another_condition;
Fetch employees who earn more than average salary of all employees
Find stores whose sales were better than the average sales across all the stores
S
Q WINDOW FUNCTIONS
L
AGGREGATE FUNCTIONS
FIND THE MAXIMUM SALARY IN EACH DEPARTMENT
Q SQL VIEWS
L
CREATING A VIEW
CREATING A NEW USER TO TEST FOR THE VIEW ACCESS
CREATING USER
CHECKING ACCESS
HERE FOR THE USER “TESTVIEW” THE ACCESS TO DATABASE AND VIEWS WAS NOT GRANTED , SO THE QUERY RETURNED AN
ERROR SAYING ACCESS DENIED
GRANTING ACCESS
CHECKING AFTER GRANTING ACCESS
CHECKING THE ACCESS FOR OTHER TABLES FROM THE DATABASE “VIEWS”
5. The query while creating view should not contain distinct clause, or group by
clause
L
PROBLEM 1:
Display number from 1 to 10 without using any in built functions.
PROBLEM 2:
Find the Hierarchy of employees under a given employee. Also displaying the manager name.
PROBLEM 3:
Find the Hierarchy of managers for a given employee.
S
Q PIVOTING IN SQL
L
PIVOTING
ORIGINAL TABLE :
PIVOTING
• This Common Table Expression (CTE) creates a temporary result set SALES.
• It selects customer ID, formats the sales date to 'Month_Year' format, and
removes the dollar sign from the amount.
PIVOTING
CTE “SALES_PER_CUST” :
• This CTE aggregates sales data per customer for each month in 2021.
• It uses CASE statements to sum amounts for each month and calculates the total sales
per customer.
PIVOTING
CTE “SALES_PER_MONTH” :
• This CTE calculates the total sales for each month across all customers.
• It labels this row with 'TOTAL' as the customer.
PIVOTING
CTE “FINAL_DATA” :
• This part combines the customer-wise monthly sales and the overall monthly totals
into a single result set..
PIVOTING
FINAL SELECTION AND FORMATTING:
• This part of the query selects from the FINAL_DATA and formats the amounts.
• It converts negative amounts to strings with parentheses and appends a dollar sign to
all amounts.
• The CASE statements handle the formatting, ensuring negative values are displayed
correctly.
PIVOTING
Q PROCEDURES
L
PROCEDURE WITHOUT PARAMETER
PROCEDURE WITHOUT PARAMETER
• The procedure BUY_PRODUCTS is defined here. The DELIMITER $$ statement changes the delimiter from ; to $$ to allow the procedure
definition to contain semicolons.
• The SELECT statement retrieves the PRODUCT_CODE and PRICE of the product named 'iPhone 13 Pro Max' from the PRODUCTS table
and stores these values into the variables V_PRODUCT_CODE and V_PRICE, respectively.
• The last SELECT statement returns the message 'PRODUCT SOLD' to indicate that the procedure has completed successfully.
• The IF statement checks if the count (V_COUNT) is greater than 0, indicating that there is sufficient quantity available.
• If the product was sold, the final SELECT statement returns the message 'PRODUCT SOLD’.
• If there was not enough quantity available (V_COUNT is 0), the procedure returns the message 'INSUFFICIENT QUANTITY’.
PROCEDURE WITH PARAMETER
CALLING THE PROCEDURE
Example 1 Example 2
Q FUNCTIONS IN SQL
L
CREATING A SALES TABLE FOR PRACTICE
CREATE INSERT
SALES TABLE
SCALAR FUNCTIONS
LENGTH UPPER
LOWER CONCAT
STRING FUNCTIONS
INSERT
SUBSTRING
LOCATE
REPLACE
DATE AND TIME FUNCTIONS
NOW
DATE_ADD
DATEDIFF
MATHEMATICAL FUNCTIONS
INSERT
ABS
ROUND
SQRT
S
Q COALESCE
L
EMPLOYEE TABLE
RETRIEVE FULL NAME OF EMPLOYEES
RETRIEVE SALARY WITH DEFAULT VALUE ‘0’
CONCATENATE FULL NAME OF EMPLOYEES
PROVIDE A DEFAULT VALUE FOR DEPARTMENT