NOT Operator
SELECT * FROM Customers WHERE CustomerName NOT LIKE 'A%';
SELECT * FROM Customers WHERE CustomerID NOT BETWEEN 10 AND 60;
SELECT * FROM Customers WHERE City NOT IN ('Paris', 'London');
(Not Greater Than)SELECT * FROM Customers WHERE NOT CustomerID > 50;
(Not Less Than)SELECT * FROM Customers WHERE NOT CustomerId < 50;
INSERT Into
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode,
Country)
VALUES
('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway'),
('Greasy Burger', 'Per Olsen', 'Gateveien 15', 'Sandnes', '4306', 'Norway'),
('Tasty Tee', 'Finn Egan', 'Streetroad 19B', 'Liverpool', 'L1 0AA', 'UK');
Update Clause
UPDATE Customers SET ContactName='Juan' WHERE Country='Mexico';
Delete Clause
Delete specific record:- DELETE FROM Customers WHERE CustomerName='Alfreds
Futterkiste';
Delete All record (but structure, attributes, indexes will be intact):-
DELETE FROM Customers ;
Delete the Table structure also:- DROP TABLE Customers;
Truncate Table : It is same as Delete All which means table structure remains
intact.Works fater than Delete All
Alter table table_name add column column_name
Select Top10
SQL Server/MS Access MySQL Oracle
SELECT TOP 3|Top 50 percent * SELECT * FROM Customers SELECT * FROM Customers
FROM Customers; LIMIT 3; FETCH FIRST 3 ROWS ONLY;
SELECT TOP 3 * FROM Customers SELECT * FROM Customers SELECT * FROM Customers
ORDER BY CustomerName DESC; ORDER BY CustomerName DESC ORDER BY CustomerName DESC
LIMIT 3; FETCH FIRST 3 ROWS ONLY;
SELECT TOP 30
percent * FROM Customers
ORDER BY CustomerName DESC;
The percent sign % represents zero, one, or multiple characters
SELECT * FROM Customers WHERE CustomerName LIKE 'a%';
LIKE 'a%', ‘%ab%’, ’%ab ’ ;
The IN operator is a shorthand for multiple OR conditions.
SELECT * FROM Customers WHERE Country IN ('Germany', 'France', 'UK'); same as below
SELECT * FROM Customers WHERE Country = 'Germany', OR 'France', OR 'UK';
Group BY
The GROUP BY statement groups rows that have the same values in specified columns and then applies
aggregate functions(SUM,MAX,MIN,COUNT,AVG,) to each group.
GROUP BY must come after FROM and before ORDER BY.
Only aggregated columns and GROUP BY columns can be in the SELECT statement.
( All non-aggregated columns in the SELECT clause must appear in the GROUP BY.)
Use HAVING instead of WHERE to filter grouped results.
Multiple columns can be used in GROUP BY for detailed grouping.
SELECT CustomerID, SUM(TotalAmount) AS TotalSpent
FROM Orders
WHERE TotalAmount > 1000
GROUP BY CustomerID;
Use This To
Filter individual rows before
WHERE
grouping
GROUP
Summarize data into groups
BY
HAVING Filter groups after aggregation
UNION
The UNION operator is used to combine the result-set of two or more SELECT statements.
Every SELECT statement within UNION must have the same number of columns
The columns must also have similar data types
The columns in every SELECT statement must also be in the same order
Note: If some customers or suppliers have the same city, each city will only be listed once,
because UNION selects only distinct values. Use UNION ALL to also select duplicate values!
Select Into Cluase
SELECT *
INTO EmployeesBackup
FROM Employees;
The new table EmployeesBackup is created and filled with all employees' data.This table is not
present before and it is created at run time and data is copied into this table.
But if table is already present then
User Insert into EmployeeBackup Select * from Employee where <condition>
User Insert into EmployeeBackup column (column1,column2) Select column1,column2 from
Employee where <condition>
Stored Procedure
✅ A Stored Procedure is a set of SQL statements that are precompiled and stored in the
database.
🔹 Code Reusability – Write once, use multiple times.
🔹 Performance Optimization – Precompiled and cached execution.
🔹 Security – Can restrict access to data by giving controlled execution.
🔹 Reduces Network Traffic – Since logic runs inside the database.
Step 1) Create Procedure
Step 2) Execute Procedure
Creating a Stored Procedure to Get All Employees
1. CREATE PROCEDURE GetAllEmployees
AS
BEGIN
SELECT * FROM Employees;
END;
Execute Procedure
EXEC GetAllEmployees;
Stored Procedure with Parameters
2. Creating a Procedure to Get Employees by Department
CREATE PROCEDURE GetEmployeesByDepartment
@DeptName VARCHAR(50)
AS
BEGIN
SELECT * FROM Employees WHERE Department = @DeptName;
END;
Execute it: EXEC GetEmployeesByDepartment 'IT';
For Dropping a Procedure: DROP PROCEDURE GetAllEmployees;
Table and View
A View in SQL is a virtual table that is created based on the result of a SQL query. Unlike tables, a
view does not store data physically; it dynamically retrieves data from the underlying tables
whenever it is queried.
📌 Why Use a View?
✅ Data Security – Restricts access to specific columns or rows.
✅ Query Simplification – Stores complex queries for easy reuse.
✅ Data Abstraction – Hides table structure details from users.
✅ Performance Optimization – Can improve query performance (especially indexed views).
Table creation
CREATE TABLE Employees (
EmpID INT PRIMARY KEY,
Name VARCHAR(100),
Department VARCHAR(50),
Salary DECIMAL(10,2)
);
INSERT INTO Employees VALUES (101, 'John Doe', 'IT', 60000);
INSERT INTO Employees VALUES (102, 'Jane Smith', 'HR', 50000);
View Creation
CREATE VIEW v_IT_Employees AS
SELECT EmpID, Name, Salary
FROM Employees
WHERE Department = 'IT';
SELECT * FROM v_IT_Employees;
The following constraints are commonly used in SQL:
NOT NULL - Ensures that a column cannot have a NULL value
UNIQUE - Ensures that all values in a column are different
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a
table
FOREIGN KEY - Prevents actions that would destroy links between tables
CHECK - Ensures that the values in a column satisfies a specific condition
DEFAULT - Sets a default value for a column if no value is specified
CREATE INDEX - Used to create and retrieve data from the database very quickly
AUTO INCREMENT
CREATE TABLE Persons (
Personid int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (Personid)
);
Type Function Use Case
Ranking Functions ROW_NUMBER(), RANK(), Assigns ranks to rows
DENSE_RANK(), NTILE(n)
Aggregate Functions SUM(), AVG(), COUNT(), Computes aggregates
MIN(), MAX() within a window
Value Functions LEAD(), LAG(), Accesses previous/next
FIRST_VALUE(), row values
LAST_VALUE()
Cumulative Functions CUME_DIST(), Calculates percent
PERCENT_RANK() distribution
Difference Between GROUP BY and WINDOW FUNCTION (PARTITION BY)
Both GROUP BY and window functions (PARTITION BY) are used for aggregation, but they work
differently. Let’s break it down with a clear comparison, examples, and key differences.
GROUP BY: Aggregation with Row Reduction
Summarizes data into fewer rows.
Each group returns only one row.
You cannot retain individual row details in the result.
SELECT Department, SUM(Salary) AS TotalSalary
FROM Employees
GROUP BY Department;
Output:
✅ Key Takeaway: The original employee details (like EmpID, Name) are lost because the
aggregation merges all rows into one per department.
Department TotalSalary
IT 15000
HR 11000
PARTITION BY: Window Function (Keeps All Rows)
Performs aggregation but retains all individual rows.
Does not reduce the number of rows (unlike GROUP BY).
Can be used with ranking functions (ROW_NUMBER(), RANK()) and
cumulative aggregations (SUM() OVER()).
Example: Cumulative Salary by Department Using PARTITION BY
SELECT EmpID, Name, Department, Salary,
SUM(Salary) OVER (PARTITION BY Department ORDER BY Salary) AS
CumulativeSalary
FROM Employees;
Output:
EmpID Name Department Salary CumulativeSal
ary
1 Alice IT 4000 4000
2 Bob IT 5000 9000
3 Charlie IT 6000 15000
4 David HR 3000 3000
5 Emma HR 3500 6500
6 Frank HR 4500 11000
✅ Key Takeaway: The result keeps all original employees but adds an extra
calculated column (CumulativeSalary).
Side-by-Side Comparison
Feature GROUP BY PARTITION BY
(Window Function)
Reduces Rows? ✅ Yes ❌ No
Keeps Original Rows? ❌ No ✅ Yes
Used for Cumulative ❌ No ✅ Yes
Aggregations?
Used for Ranking? ❌ No ✅ Yes (e.g., RANK()
OVER())
Example Aggregations SUM(), AVG(), COUNT() SUM() OVER(), COUNT()
OVER()
𝗦𝗤𝗟 𝗕𝗮𝘀𝗶𝗰 𝗖𝗼𝗻𝗰𝗲𝗽𝘁𝘀:
1. Introduction to SQL
2. Basic SQL Syntax
3. Data Types in SQL
4. SQL Sub-languages (DDL, DML, DCL, TCL, DQL)
5. Data Manipulation (INSERT, UPDATE, DELETE)
6. Data Definition (CREATE, ALTER, DROP, TRUNCATE)
7. Data Aggregation (COUNT, SUM, AVG, MIN, MAX, GROUP BY, HAVING)
8.SQL Joins (INNER, LEFT, RIGHT, FULL, CROSS)
9. SQL Subqueries and Correlated Subqueries
10. Data Integrity in SQL
𝗦𝗤𝗟 𝗔𝗱𝘃𝗮𝗻𝗰𝗲𝗱 𝗖𝗼𝗻𝗰𝗲𝗽𝘁𝘀:
1. Window Functions (ROW_NUMBER, RANK, DENSE_RANK)
2. Common Table Expressions (CTE)
3. Recursive Queries
4. Indexes
5. Pivot & Unpivot
6. JSON Functions
7. Stored Procedures & Functions
8. Dynamic SQL
9. Materialized Views
10. Query Optimization Techniques