Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
17 views

Complete SQL Guide

Uploaded by

seezrat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Complete SQL Guide

Uploaded by

seezrat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 129

Data

S
o Data refers to any information or facts
that can be recorded, stored, and
processed.

Q o It can be in various forms, such as text,


numbers, images, audio, or video.
o Examples of data include customer
names, product prices, temperature
L readings, and more.
S Database
o A database is a structured collection of data
that is organized for efficient storage,

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.

Q o It provides tools for creating,


modifying, querying, and maintaining
databases.
o Examples of DBMS include MySQL,
Microsoft SQL Server, Oracle, and
L PostgreSQL.
S

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 o SQL (Structured Query Language) is


used to manipulate data in RDBMS.
S

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

L each record, and rows represent individual


entries.
SQL Vs NOSQL Databases
S SQL (Relational Databases) NoSQL (Non-Relational Databases)

• Uses structured query language (SQL) • May support SQL-like queries but not strictly SQL

• Has a predefined schema • Has a dynamic schema for unstructured data


• Data is stored in tables with rows and columns • Data can be stored in various formats like key-
Q value, document, graph, or wide-column stores

• 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 are ideal for multi-row


freely.

Excel is commonly used for small-scale data analysis,


transactions (e.g., accounting systems). calculations, and reporting.

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).

SQL: MySQL, PostgreSQL, Oracle, SQL Server,


Excel is a standalone application widely used for data
Examples SQLite. NoSQL: MongoDB, Cassandra, Redis,
manipulation and analysis.
Neo4j.
S

Q SQl Data Types


L
Data Types Description Example
CREATE TABLE products (
o CHAR(n) : Fixed-length character strings (e.g., storing
employee codes). product_id INT PRIMARY KEY,

o VARCHAR(n) : Variable-length character strings (e.g., storing product_name VARCHAR(50),


Character/String
S o TEXT
names).
: Large text data (e.g., storing descriptions).
description TEXT,
category CHAR(20)
);

CREATE TABLE sample_data (


o INT : Stores whole numbers (e.g., employee IDs).
id INT PRIMARY KEY,

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,

stock prices). price DECIMAL(10, 2)


);

CREATE TABLE Orders (

L o DATE : Stores dates (e.g., order dates).


order_id INT PRIMARY KEY,
order_date DATE,
Date and Time o TIME : Stores time of day (e.g., appointment times).
delivery_time TIME,
o DATETIME or TIMESTAMP : Stores both date and time.
created_at DATETIME
);
S

Q SQL CONSTRAINTS
L
Constraints Description Example

CREATE TABLE Customers (


customer_id INT NOT NULL,
NOT NULL Ensures a column cannot have NULL values.
S customer_name VARCHAR(100)
o

NOT NULL
);

CREATE TABLE Products (


product_id INT PRIMARY KEY,

Q UNIQUE o Requires all values in a column to be unique.


product_code VARCHAR(20)
UNIQUE,
product_name VARCHAR(100)
);

L o Uniquely identifies each row in a table.


CREATE TABLE Students (
student_id INT PRIMARY KEY,
PRIMARY KEY o Combination of NOT NULL and UNIQUE student_name VARCHAR(50)
constraints. NOT NULL
);
Constraints Description Example
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name VARCHAR(50) 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)
);

Q CREATE TABLE Employees (


emp_id INT PRIMARY KEY,
o Validates column values against specific
CHECK salary DECIMAL(10, 2) CHECK
conditions.
(salary >= 30000)
);

L CREATE TABLE Settings (


setting_id INT PRIMARY KEY,
DEFAULT o Sets a default value if no value is specified. theme VARCHAR(20) DEFAULT
'light'
);
SQL Command Types

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 CREATE ▪ Creates a new table.


EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Salary DECIMAL(10, 2)
);

Q ALTER • Modifies an existing table (e.g., ALTER TABLE Employees


ADD Department VARCHAR(50);
adding columns).

L DROP • Deletes a table. DROP TABLE Employees;


COMMANDS Description Example

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 SELECT name, age


FROM employees
WHERE department = 'sales';

Q SELECT Retrieves data from one or more tables. SELECT *


FROM customers;

L SELECT c.*, co.CountryName


FROM customer c
JOIN Country co
ON c.CountryID = co.CountryID
WHERE co.CountryName = 'Germany';
S
DATA MANIPULATION LANGUAGE (DML)
Q
DML commands manipulate data within tables.
L
COMMANDS Description Example

S INSERT • Adds new records to a table.


INSERT INTO Employees
(EmployeeID, FirstName, LastName,
Salary)
VALUES (101, 'John', 'Doe', 60000);

Q UPDATE • Modifies existing records.


UPDATE Employees
SET Salary = 65000
WHERE EmployeeID = 101;

L DELETE • Removes records from a table.


DELETE FROM Employees
WHERE EmployeeID = 101;
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

L MERGE `DELETE` operations based on a


condition.
UPDATE SET T.description =
S.description
WHEN NOT MATCHED THEN
INSERT (ID, description) VALUES
(S.id, S.description);
S

Q DATA CONTROL LANGUAGE (DCL)

DCL commands manage user access and permissions.


L
COMMANDS Description Example

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

• Saves changes made during a


S
COMMIT;
COMMIT transaction.

ROLLBACK • Reverts changes if an error occurs.


ROLLBACK;

Q • A point within a transaction where


SAVE POINT you can roll back to a specific state SAVEPOINT savepoint_name;
without affecting the entire
transaction.

L SET • Allows you to configure transaction SET TRANSACTION ISOLATION LEVEL


TRANSACTION properties. READ COMMITTED;
S

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,

1. Equal to (=) : Checks if two values are equal.


2. Not equal to (<> or !=) : Checks if two values are not equal.
3. Greater than (>) : Checks if the value on the left is greater than the value on the right.

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

S 1 . Fetch all records where subject name


is Mathematics from SUBJECTS
SELECT * FROM SUBJECTS WHERE
SUBJECT_NAME = 'Mathematics';

table

Q 2. Fetch all records where subject name


is not Mathematics from SUBJECTS
table.
SELECT * FROM SUBJECTS WHERE
SUBJECT_NAME <> 'Mathematics';

L 3. Fetch all records where salary is


greater than 10000 from
SELECT * FROM STAFF_SALARY
WHERE SALARY > 10000;
STAFF_SALARY table.
COMPARISON OPERATORS
PROBLEM QUERY RESULT TABLE

S 4 . Fetch all records where salary is


less than 10000 and the output is SELECT * FROM STAFF_SALARY
WHERE SALARY < 10000 ORDER BY
sorted in ascending order of salary
SALARY;
from STAFF_SALARY table.

Q 5. Fetch all records where salary is less


than 10000 and the output is sorted in
descending order of salary from
SELECT * FROM STAFF_SALARY
WHERE SALARY < 10000 ORDER BY
SALARY DESC;
STAFF_SALARY table.

L 6. Fetch all records where salary is SELECT * FROM STAFF_SALARY


greater than or equal to 10000. WHERE SALARY >= 10000;
COMPARISON OPERATORS
PROBLEM QUERY RESULT TABLE

S 7. Fetch all records where salary is


between 5000 and 10000 from
SELECT * FROM STAFF_SALARY
WHERE SALARY BETWEEN 5000 AND
10000;
STAFF_SALARY table.

Q 8. Fetch all records where subjects is


either Mathematics, Science or Arts from
SUBJECTS table.
SELECT * FROM SUBJECTS WHERE
SUBJECT_NAME IN ('Mathematics',
'Science', 'Arts’);

9.Fetch records from SUBJECTS table SELECT * FROM SUBJECTS


where subject name has Computer as WHERE SUBJECT_NAME LIKE
'Computer%';.

L prefixed.

10. Fetch STAFF_ID, FIRST_NAME, SELECT STAFF_ID, FIRST_NAME,


LAST_NAME , GENDER FROM LAST_NAME , GENDER FROM STAFF
STAFF where first name of staff starts WHERE FIRST_NAME LIKE 'A%' AND
LAST_NAME LIKE 'S%';
with "A" AND last name starts with "S".
LOGICAL OPERATORS
Logical operators in SQL are used to combine multiple conditions in a SQL statement's WHERE
S clause. They help refine the selection criteria for queries, allowing more complex and specific data
retrieval. The primary logical operators in SQL are

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 1. Fetch STAFF_ID, FIRST_NAME,


LAST_NAME ,AGE, GENDER from SELECT STAFF_ID, FIRST_NAME,
LAST_NAME ,AGE, GENDER FROM
STAFF table where staff is female and
STAFF WHERE AGE > 50 AND
is over 50 years of age. GENDER = 'F';

Q 2. Fetch STAFF_ID, FIRST_NAME,


LAST_NAME ,AGE, GENDER from
STAFF table where staff is male or is
SELECT STAFF_ID, FIRST_NAME,
LAST_NAME ,AGE, GENDER FROM
STAFF WHERE AGE > 50 OR GENDER
= 'M';
over 50 years of age.

L 3. Fetch all records where subjects is not


Mathematics, Science or Arts from
SELECT * FROM SUBJECTS
WHERE SUBJECT_NAME NOT IN
('Mathematics', 'Science', 'Arts');
SUBJECTS table.
ARITHMETIC OPERATORS
Arithmetic operators in SQL are used to perform mathematical operations on numerical data. These

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 :

1. Addition (+) : Adds two numerical values.

Q 2. Subtraction (-)

3. Multiplication (*)
: Subtracts one numerical value from another.

: Multiplies two numerical values.

4. Division (/) : Divides one numerical value by 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

S 1. Add 2 numbers SELECT (5+2) AS ADDITION;

Q 2. Multiply 2 numbers SELECT (5*2) AS MULTIPLY;

3. Divide 2 numbers and returns the


remainder. SELECT (5%2) AS MODULUS;

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

S to return different values based on specific conditions, similar to an IF-THEN-ELSE structure in


programming languages. This can be particularly useful for generating custom output, transforming
data, or performing complex calculations within your SELECT statements.
Syntax of CASE Statement :
There are two forms of the CASE statement in SQL:

• 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 :

Q Fetch all the class name where Music is thought as a subject.

Query : Result table :


SELECT C.CLASS_NAME, S.SUBJECT_NAME
FROM CLASSES C, SUBJECTS S
WHERE C.SUBJECT_ID = S.SUBJECT_ID
L AND S.SUBJECT_NAME = "Music";
EXPLICIT JOINS
Explicit joins use the JOIN keyword along with ON to specify the joining
S condition. This approach is clearer and preferred for complex queries as it
separates the join conditions from the filtering conditions.

Example :

Q Fetch all the class name where Music is thought as a subject.

Query : Result table :


SELECT C.CLASS_NAME, S.SUBJECT_NAME
FROM CLASSES C
JOIN SUBJECTS S
L ON C.SUBJECT_ID = S.SUBJECT_ID
WHERE S.SUBJECT_NAME = "Music";
TYPES OF EXPLICIT JOINS

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.

UNION ALL OPERATOR


• The UNION ALL operator also combines the results of two or more SELECT queries.
Q • Unlike UNION, it includes all rows, including duplicates.

𝐊𝐞𝐲 𝐃𝐢𝐟𝐟𝐞𝐫𝐞𝐧𝐜𝐞𝐬:
1. 𝐷𝑢𝑝𝑙𝑖𝑐𝑎𝑡𝑒 𝐻𝑎𝑛𝑑𝑙𝑖𝑛𝑔:
• `𝑈𝑁𝐼𝑂𝑁`: 𝑅𝑒𝑚𝑜𝑣𝑒𝑠 𝑑𝑢𝑝𝑙𝑖𝑐𝑎𝑡𝑒𝑠.
• `𝑈𝑁𝐼𝑂𝑁 𝐴𝐿𝐿`: 𝐾𝑒𝑒𝑝𝑠 𝑑𝑢𝑝𝑙𝑖𝑐𝑎𝑡𝑒𝑠.

L 2. 𝑃𝑒𝑟𝑓𝑜𝑟𝑚𝑎𝑛𝑐𝑒:

• `𝑈𝑁𝐼𝑂𝑁`: 𝑆𝑙𝑖𝑔ℎ𝑡𝑙𝑦 𝑠𝑙𝑜𝑤𝑒𝑟 𝑑𝑢𝑒 𝑡𝑜 𝑡ℎ𝑒 𝑛𝑒𝑒𝑑 𝑡𝑜 𝑟𝑒𝑚𝑜𝑣𝑒 𝑑𝑢𝑝𝑙𝑖𝑐𝑎𝑡𝑒𝑠.


• `𝑈𝑁𝐼𝑂𝑁 𝐴𝐿𝐿`: 𝐹𝑎𝑠𝑡𝑒𝑟 𝑎𝑠 𝑖𝑡 𝑠𝑖𝑚𝑝𝑙𝑦 𝑐𝑜𝑛𝑐𝑎𝑡𝑒𝑛𝑎𝑡𝑒𝑠 𝑡ℎ𝑒 𝑟𝑒𝑠𝑢𝑙𝑡 𝑠𝑒𝑡𝑠.
𝐖𝐡𝐞𝐧 𝐭𝐨 𝐔𝐬𝐞:
UNION AND UNION ALL OPERATOR
Feature UNION UNION ALL
S Functionality
Combines results from multiple SELECT queries and Combines results from multiple SELECT queries
removes duplicates. and keeps duplicates.
Removes duplicate rows from the final result set. Includes all rows from each SELECT query, keeping
Duplicate Handling duplicates.
Slightly slower due to the overhead of removing Faster as it simply concatenates the result sets
Performance duplicates. without removing duplicates.

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:

L SELECT name FROM students UNION SELECT


name FROM alumni;
Ensures that each row in the result is unique. Useful
SELECT name FROM students UNION ALL
SELECT name FROM alumni;
Keeps all duplicates in the final result set. Useful for
when merging lists with potentially overlapping performance-critical scenarios or when duplicates
Key Points entries. are required for analysis.
UNION 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
SELECT CONCAT(S.FIRST_NAME," ",S.LAST_NAME) AS FULL_NAME, SELECT column1, column2, ...
S.STAFF_TYPE, S.GENDER, S.AGE FROM table2;
FROM CLASSES C

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

L SELECT CONCAT(FIRST_NAME," ",LAST_NAME) AS FULL_NAME,


STAFF_TYPE, GENDER,AGE
FROM STAFF
WHERE STAFF_TYPE="Non-Teaching";

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

L SELECT CONCAT(FIRST_NAME," ",LAST_NAME) AS FULL_NAME,


STAFF_TYPE, GENDER,AGE
FROM STAFF
WHERE STAFF_TYPE="Non-Teaching";

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;

Q Example : Result Table :


Count the no of students in each class.

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

S The HAVING clause filters the results of GROUP BY based on a


specified condition. Unlike the WHERE clause, which filters rows
SELECT column1,
AGGREGATE_FUNCTION
(column2)
before grouping, HAVING filters groups after the aggregation. FROM table_name
GROUP BY column1
HAVING condition;

Q Example : Result Table :


Return only those records where there are more than 100 students in each class.

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

S Aggregate functions perform a calculation on a set of values and return


a single value. Common aggregate functions include:
• COUNT() : Counts the number of rows in a group.
SELECT column1,
AGGREGATE_FUNCTION
(column2)
• SUM() : Calculates the sum of a numeric column. FROM table_name
• AVG() : Computes the average of a numeric column. GROUP BY column1
• MIN() : Finds the minimum value in a column. HAVING condition;
• MAX()
Q Example :
: Retrieves the maximum value in a column.

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

S Calculates the total salary paid to each


staff type.
SELECT S.STAFF_TYPE,
SUM(SAL.SALARY) AS TOTAL_SALARY
FROM STAFF S J
OIN STAFF_SALARY SAL
ON S.STAFF_ID = SAL.STAFF_ID
GROUP BY S.STAFF_TYPE;

Q Calculate the minimum salary paid to


SELECT S.STAFF_TYPE,
MIN(SAL.SALARY) AS MIN_SALARY
FROM STAFF S
each staff type. JOIN STAFF_SALARY SAL
ON S.STAFF_ID = SAL.STAFF_ID
GROUP BY S.STAFF_TYPE;

L Calculate the maximum salary paid to


SELECT S.STAFF_TYPE,
MAX(SAL.SALARY) AS MAX_SALARY
FROM STAFF S
each staff type. JOIN STAFF_SALARY SAL
ON S.STAFF_ID = SAL.STAFF_ID
GROUP BY S.STAFF_TYPE;
S

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 .

SELECT * FROM EMPLOYEE


WHERE SALARY> (SELECT AVG(salary) AS
avg_salary
FROM employee);

• Here the subquery calculates the average salary.


• The outer query selects the employee details from employees where the salary is greater than
the average salary.
DIFFERENT TYPES OF SUBQUERIES
Subqueries can be classified into different types based on their usage
and return values:

• Single-Row Subquery : Returns a single row and column.

• Multi-Row Subquery : Returns multiple rows and columns.

• Correlated Subquery : References columns from the outer query and is


executed once for each row processed by the outer
query.

• Nested Subquery : A subquery within another subquery.


SCALAR SUBQUERY
• A scalar subquery returns a single value (one row and one column).
• Commonly used in the WHERE clause to filter results based on a specific condition.

EXAMPLE :
Find the employees who's salary is more than the average salary earned by all employees .

SELECT *FROM EMPLOYEE E


JOIN (SELECT AVG(salary) AS avg_salary
FROM employee) AVERAGE
ON E.SALARY > AVERAGE.avg_salary;

• 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 EMPLOYEE E1


WHERE SALARY > (SELECT AVG(SALARY)
FROM EMPLOYEE E2
WHERE E1.DEPT_NAME = E2.DEPT_NAME);

1. First the subquery will return average salary of every department


2. Then the outer query filter data from employee tables based on avg salary from above result.
NESTED SUBQUERIES
• A nested subquery contains another subquery within it.
• These can be scalar, multiple-row, or multiple-column subqueries.
EXAMPLE :
-- Find stores who's sales where better than the average sales accross all stores .

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.

• WHERE Clause : To filter records based on conditions evaluated by the subquery.

• 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.

DELETE FROM department


WHERE dept_name IN
( SELECT dept_name FROM
( SELECT dept_name FROM department d
WHERE NOT EXISTS
( SELECT 1 FROM employee e
WHERE e.dept_name = d.dept_name
)) AS derived_table);

• The inner subquery identifies departments without employees


• The outer query then deletes all rows from the department table where dept_name matches any of the department names in the derived table.
S

Q COMMON TABLE EXPRESSION

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.

Key Features of CTEs :

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.

• Modularity : Each CTE can be written, debugged, and tested independently.

• Reusability : Avoid redundancy by referencing the same CTE multiple times


in the main query.

• 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.

• Staging Data : Use CTEs to store intermediate results temporarily during


multi-step transformations.

• 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

WITHOUT WINDOW FUNCTIONS WITH WINDOW FUNCTIONS

QUERY WITHOUT WINDOW FUNCTIONS:


Purpose : This query calculates the maximum salary for each department and returns one row per department.
Usage : It is typically used when you need a summary of data grouped by a specific column.

QUERY WITH WINDOW FUNCTIONS:


Purpose : This query calculates the maximum salary for each department but returns all rows from the EMPLOYEE
table along with the maximum salary as an additional column.
Usage : It is used when you need detailed row-level data along with an aggregated value computed over a specified partition.
RANKING FUNCTIONS
RANKING FUNCTIONS
VALUE FUNCTIONS
VALUE FUNCTIONS
ANALYTIC FUNCTIONS
ANALYTIC FUNCTIONS
S

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

Here after granting access to user


“TESTINGVIEW” for using the view
“ORDER_SUMMARY” , it could fetch
all the records from it.

CHECKING THE ACCESS FOR OTHER TABLES FROM THE DATABASE “VIEWS”

Here since the user was not given


access to the table
“PRODUCT_INFO”, his query to fetch
the records from the table was
denied.
CREATE OR REPLACE
When you create a view using the `CREATE VIEW` command, you define its structure (columns and their data types) and the query that
populates it. Suppose you want to modify the view's definition without dropping and recreating it. This is where `CREATE OR REPLACE
VIEW` comes in handy. When you use `CREATE OR REPLACE VIEW`, it checks if the view already exists. If it does, it updates the view
definition based on the specified query. This preserves any view privileges granted to users or roles. Different database systems (such as Oracle,
MySQL, or SQL Server) may have slight variations in syntax, but the concept remains consistent.
RENAMING A VIEW
UPDATING A VIEW
UPDATING A VIEW CREATED USING MULTIPLE TABLES

UPDATING A VIEW CREATED USING SINGLE TABLE


R U L E S F O R U P D AT I N G A V I E W
1. While updating a view ,the column list along with its name and data type should
be same as used when creation of the view.

2. New columns can be added only to end of the column list

3. Query with JOINS, table list, Order by clause can be changed.

4. View created using just one table or view can be updated.

5. The query while creating view should not contain distinct clause, or group by
clause

6. It Should not also contain window functions and WITH clause.

7. Have no subqueries in the SELECT statement.


WITH CHECK OPTION
The WITH CHECK OPTION clause in SQL views ensures the consistency of data when inserting or updating rows
through the view. The WITH CHECK OPTION clause restricts modifications (inserts or updates) to rows that conform to
the original query used to create the view.
S

Q RECURSIVE SQL QUERIES

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

Here I am using SQL queries to leverage multiple CTEs to:


1. Prepare and clean the data (SALES).
2. Aggregate sales per customer for each month and total
(SALES_PER_CUST).
3. Aggregate total sales for each month across all customers
(SALES_PER_MONTH).
4. Combine these aggregates (FINAL_DATA).
5. Format the final output with appropriate signs and dollar
symbols.
PIVOTING
CTE “SALES” :

• 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

FINAL OUTPUT TABLE :


S

Q PROCEDURES

L
PROCEDURE WITHOUT PARAMETER
PROCEDURE WITHOUT PARAMETER

TABLES BEFORE PROCEDURE


PROCEDURE WITHOUT PARAMETER
This procedure is designed to process the sale of an "iPhone 13 Pro Max" by:
• Retrieving its product code and price.
• Inserting a sale record.
• Updating the inventory to reflect the sale.
• Returning a confirmation message.
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.

• Two variables are declared:


• V_PRODUCT_CODE : To store the product code of 'iPhone 13 Pro Max'.
• V_PRICE : To store the price of the 'iPhone 13 Pro Max’.

• 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.

• INSERT statement adds a new record into the SALES table

• UPDATE statement updates the PRODUCTS table:


• It decreases the QUANTITY_REMAINING by 1.
• It increases the QUANTITY_SOLD by 1.
• The update is applied to the product with the PRODUCT_CODE equal to V_PRODUCT_CODE

• The last SELECT statement returns the message 'PRODUCT SOLD' to indicate that the procedure has completed successfully.

• END $$ marks the end of the procedure definition.


PROCEDURE WITHOUT PARAMETER
CALLING THE PROCEDURE

UPON CALLING THE


PROCEDURE , A
SUCCESSFUL MESSAGE
“PRODUCT SOLD” WAS
RETURNED.

TABLES AFTER PROCEDURE

THE SALES TABLE IS UPDATED QUANTITY_REMAINING IS REDUCED FROM


5 TO 4 AND THE QUANTITY_SOLD COLUMN
WITH A NEW RECORD
IS INCREMENTED FROM 195 TO 196.
PROCEDURE WITH PARAMETER
PROCEDURE WITH PARAMETER

TABLES BEFORE PROCEDURE


PROCEDURE WITH PARAMETER
The BUY_PRODUCTS_NW procedure is designed to:
• Check if the specified quantity of a product is available.
• If available, retrieve the product details and insert a sale record.
• Update the product inventory to reflect the sale.
• Return a confirmation message 'PRODUCT SOLD'.
• If not available, return the message 'INSUFFICIENT QUANTITY'
• A new stored procedure called BUY_PRODUCTS_NW is created which takes two input parameters:
• P_PRODUCT_NAME : The name of the product to be purchased.
• P_QUANTITY : The quantity of the product to be purchased.

• Three variables are declared:


• V_COUNT : To store the count of products matching the criteria.
• V_PRODUCT_CODE : To store the product code of the specified product.
• V_PRICE : To store the price of the specified product.

• The SELECT statement checks if there are enough products available:


• It counts the number of products in the PRODUCTS_NW table that match the P_PRODUCT_NAME and have a
QUANTITY_REMAINING greater than P_QUANTITY.
• The count is stored in V_COUNT.

• The IF statement checks if the count (V_COUNT) is greater than 0, indicating that there is sufficient quantity available.

• If sufficient quantity is available:


• The product code and price are retrieved for the specified product and stored in V_PRODUCT_CODE and V_PRICE.
• A new sale record is inserted into the SALES table with:
• ORDER_DATE : The current date.
• PRODUCT_CODE : The code of the product.
• QUANTITY_ORDERED : The quantity ordered (P_QUANTITY).
• SALE_PRICE : The total sale price (price per unit multiplied by the quantity).

The UPDATE statement adjusts the inventory:

• Decreases the QUANTITY_REMAINING by the ordered quantity (P_QUANTITY).


• Increases the QUANTITY_SOLD by the ordered quantity.
• This update is applied to the product with the retrieved PRODUCT_CODE.

• 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

HERE THE PROCEDURE


RETURNED THE MESSAGE
“INSUFFICIENT QUANTITY”
AS FOR THE PRODUCT “IPAD
AIR” ONLY 1 QUANTITY WAS
AVAILABLE

TABLES AFTER PROCEDURE

QUANTITY OF “AIRPODS PRO “ IS REDUCED


THE SALES_NW TABLE IS FROM 10 TO 7 AND THE QUANTITY_SOLD
UPDATED WITH A NEW RECORD COLUMN IS INCREMENTED FROM 90 TO 93.
S

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

You might also like