🔹 Basic SQL
Introduction to SQL (DDL, DML, DCL, TCL)
Data Types
SQL Constraints (NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT)
SQL Operators (Arithmetic, Comparison, Logical, IN, BETWEEN, LIKE)
🔹 SQL Queries
SELECT Statement
WHERE Clause
DISTINCT
ORDER BY
LIMIT / TOP
GROUP BY
HAVING
🔹 Functions
Aggregate Functions (COUNT, SUM, AVG, MIN, MAX)
String Functions (UPPER, LOWER, SUBSTRING, LENGTH, TRIM)
Date Functions (NOW, GETDATE, DATEADD, DATEDIFF)
Conversion Functions (CAST, CONVERT)
🔹 Joins
INNER JOIN
LEFT JOIN
RIGHT JOIN
FULL OUTER JOIN
SELF JOIN
CROSS JOIN
🔹 Subqueries & Clauses
Subqueries (Single-row, Multi-row, Correlated)
EXISTS / IN / ANY / ALL
🔹 Keys & Indexing
Primary Key
Foreign Key
Candidate Key
Composite Key
Indexes (Clustered & Non-clustered)
🔹 Advanced SQL
Views
Stored Procedures & Functions (basic idea)
Triggers (basic idea)
Transactions & ACID Properties
Normalization (1NF, 2NF, 3NF, BCNF)
SQL
SQL is the Structured Query Language
It is used to manage and manipulate relational databases.
Not Case sensitive and keywords are uppercase
Structed query language is programming language that stores
, manipulate and retrieve the data from the database
Data base is a system that’s allows users to store and organise
the data
Commands in sql
1) DATA TYPES IN SQL
Data Type Description
INT Integer
VARCHAR(n) String of variable length n
CHAR(n) Fixed-length string of n chars
DATE Date value
FLOAT, DECIMAL Decimal values
BOOLEAN True/FalsE
OPERATORES
Arithmetic → +, -, *, /, %
Comparison → =, !=, >, <, >=, <=
Logical → AND, OR, NOT
Special → BETWEEN, IN, LIKE, NULL, EXISTS
Bitwise → &, |, ^, ~, <<, >>
Concatenation → || or + depending on DB
STRING FUNCTION
Function Description Example Output
UPPER() Converts to uppercase SELECT UPPER('sql') SQL
LOWER() Converts to lowercase SELECT LOWER('SQL') sql
SELECT
SUBSTRING() Extracts part of a string Hello
SUBSTRING('HelloWorld',1,5)
LENGTH() Counts characters SELECT LENGTH('SQL') 3
Removes
TRIM() SELECT TRIM(' SQL ') SQL
spaces/characters
DATA FUNCTIONS
Function Purpose Example Output
NOW() Current system date SELECT NOW(); 2025-10-03 [Link]
DATEDIFF() Difference in days DATEDIFF('2025-12-31','2025-10-03') 89
DAY(), MONTH(), Get day, month, MONTH('2025-10-
10
YEAR() year 03')
DATEADD() Add/subtract units DATEADD(DAY,10,'2025-10-03') 2025-10-13
FORMAT(), Format TO_CHAR(NOW(),'DD-Mon- 03-Oct-
TO_CHAR() date YYYY') 2025
LAST_DAY() Last day of month LAST_DAY('2025-10-03') 2025-10-31
NEXT_DAY() Next weekday NEXT_DAY(SYSDATE,'FRIDAY') 2025-10-10
2)
DDL: data definition language
Command Description Example
Creates a new
CREATE table or CREATE TABLE student (...);
database
Modifies an ALTER TABLE student ADD
ALTER
existing table email VARCHAR(100);
Deletes a table
DROP DROP TABLE student;
or database
Deletes all
TRUNCATE data from a TRUNCATE TABLE student;
table (faster)
Renames a RENAME TABLE student TO
RENAME
table learners;
DML – Data Manipulation Language
These commands are used to manipulate data (insert, update, delete).
Command Description Example
INSERT Adds new rows INSERT INTO student VALUES (1, 'Ravi', 20);
UPDATE Modifies existing data UPDATE student SET age = 21 WHERE rollno = 1;
DELETE Deletes rows DELETE FROM student WHERE rollno = 1;
DQL – Data Query Language
Used to query data from the database.
Command Description Example
SELECT Retrieves data from tables SELECT * FROM student;
DCL – Data Control Language
Controls access permissions to data.
Command Description Example
GRANT Gives privileges to users GRANT SELECT ON student TO user1;
REVOKE Removes privileges from users REVOKE SELECT ON student FROM user1;
TCL – Transaction Control Language
Used to control transactions (like a set of operations).
Command Description Example
COMMIT Saves the changes made COMMIT;
ROLLBACK Undoes changes made ROLLBACK;
SAVEPOINT Sets a point to rollback to SAVEPOINT sp1;
SET TRANSACTION
Sets transaction SET TRANSACTION READ
properties ONLY;
……………………………………………………………………………………………………
Transactions & ACID Properties
What is a transaction?
A transaction is a sequence of one or more SQL statements treated as a single
logical unit of work. Either all statements succeed (and are made permanent
with COMMIT) or none take effect (using ROLLBACK).
Common uses: money transfers, booking/reservations, inventory changes.
-- Start a transaction
BEGIN TRANSACTION; -- SQL Server / standard
-- or
START TRANSACTION; -- MySQL / MariaDB
-- or in some clients simply:
BEGIN;
-- Make changes permanent
COMMIT;
-- Undo changes since transaction start (or since last SAVEPOINT)
ROLLBACK;
Atomicity
Description: The transaction is all-or-nothing. Either every operation inside the
transaction completes successfully, or none does.
BEGIN TRANSACTION;
UPDATE Accounts
SET Balance = Balance - 100
WHERE AccountID = 1;
UPDATE Accounts
SET Balance = Balance + 100
WHERE AccountID = 2;
-- if no errors
COMMIT;
-- if any error occurs -> ROLLBACK;
C — Consistency
Description: A transaction moves the database from one valid state to
another, preserving all rules: constraints, triggers, cascades, checks, unique
keys, foreign keys, etc.
I — Isolation
Description: Concurrent transactions must not interfere with each other in a
way that causes incorrect results. Each transaction should behave as if it were
running alone (to an extent determined by isolation level).
D — Durability
Description: Once a transaction commits, its changes are permanent and
survive subsequent system crashes, power failures, or errors
----------------------------------------------------------------------------------------------------
SQL Constraints
Constraint Description
PRIMARY KEY Unique identifier + NOT NULL
It is a COLUMN which can be
unqely identified(they may be
CANDIDATE KEY
multiple candidate keys) not
null , unique , not primary key
COMBINATION OF 2 COLUMNS
COMPOSIT KEYkm n
(UNIQUELY IDEFINED)
References primary key of
FOREIGN KEY
another table
UNIQUE Ensures all values are unique
NOT NULL Column cannot be NULL
CHECK Validates condition
DEFAULT Sets default value
Primary key :
CREATE TABLE student ( id INT PRIMARY KEY, name VARCHAR(100))
Foreign key :
Enforces a link between two tables.
foreign key in one table points to the primary key in another table.
CREATE TABLE department
(deptid INT PRIMARY KEY, deptname VARCHAR(100));
CREATE TABLE student
(id INT PRIMARY KEY,name VARCHAR(100), deptid INT,
FOREIGN KEY (deptid) REFERENCES department(deptid));
UNIQUE key:
Ensures all values in a column are different.
CREATE TABLE student (email VARCHAR(100) UNIQUE);
CHECK KEY :
Validates values based on a condition.
Rejects data that doesn't satisfy the condition.
CREATE TABLE student (id INT, age INT CHECK (age >= 18) );
DEFAULT KEY:
Assigns a default value if no value is provided.
CREATE TABLE student (id INT,status VARCHAR(20) DEFAULT 'active'));
RENAME / DROP Constraints
You can add/remove constraints after table creation.
Add:
ALTER TABLE student ADD CONSTRAINT chk_age CHECK (age >= 18);
Drop:
ALTER TABLE student DROP CONSTRAINT chk_age;
……………………………………………………………………………………………………..
Flow of execution in SQL
diff
DISTINCT → affects only the result of SELECT.
Removes duplicate rows from the result set.
SELECT DISTINCT City
FROM Students;
Returns each city only once, even if multiple students live in the
same city.
UNIQUE → affects the data in the table (constraint/ index).
No diff rows have same value
CREATE TABLE Employees (
EmpID INT PRIMARY KEY,
Email VARCHAR(100) UNIQUE
);
Clauses
WHERE – filter records
GROUP BY – group results
HAVING – filter groups
ORDER BY – sort results
DISTINCT – remove duplicates
LIMIT – limit rows
WHERE
Used to filter the records based on condition
We have to use this before any grouping by class
SELECT * FROM Employees
WHERE dept_id = 1 AND salary > 30000
GROUPING
It groups the rows which have the same values in specified columns
Often used with aggregate functions like SUM(), COUNT(), AVG().
Each ani vaste we will use grouping
SELECT dept_id, COUNT(*) AS total_employees
FROM Employees
GROUP BY dept_id;
Counts number of employees in each department.
HAVING Clause
Filter the groups after aggregate function
Similar to WHERE, but WHERE filters rows before grouping, HAVING
filters after grouping
SELECT dept_id, AVG(salary) AS avg_salary
FROM Employees
GROUP BY dept_id
HAVING AVG(salary) > 40000;
Shows departments with average salary > 40000.
ORDER BY
Sorts the result set by one or more columns.
Default order is ASC . use DESC for D.O
Lists employees from highest salary to lowest
SELECT emp_name, salary
FROM Employees
ORDER BY salary DESC;
DISTINCT Clause
Removes the duplates in result set
Returns a list of unique department IDs.
SELECT DISTINCT dept_id
FROM Employees;
LIMIT Clause
Used to limit the number of rows retuned by the query
SELECT * FROM Employees
LIMIT 5;
Returns first 5 rows of Employees.
INDEX -> An index in SQL is like the index of a book.
Instead of reading every page to find a word, you go directly to the
index → it speeds up search.
Similarly, an SQL index improves the speed of queries by allowing the
database to find rows more quickly.
Key Points
Purpose: Speeds up data retrieval (SELECT queries).
Downside: Slows down INSERT, UPDATE, and DELETE because the index
also has to be updated.
Storage: Takes up extra memory space.
CREATE INDEX index_name
ON table_name(column_name);
Types of Index
1. Primary Index
o Automatically created when you define a PRIMARY KEY.
o Ensures uniqueness.
2. Unique Index
o Ensures all values in a column are unique (similar to UNIQUE
constraint).
3. Clustered Index
o It defines the order in which the data is physically stored in table.
o Example : dictionary (letter)
o It has only one cluster
4. Non-Clustered Index
o Indexed data is stored in one place , actually data is stored in one
palce .
o Creates a separate structure from the table data.
o Table can have multiple non-clustered indexes.
-- Create an index
CREATE INDEX index_name
ON table_name(column_name);
-- Create a unique index
CREATE UNIQUE INDEX index_name
ON table_name(column_name);
-- Drop (delete) an index
DROP INDEX index_name;
-- Create a table
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
Name VARCHAR(50),
Age INT,
City VARCHAR(50)
);
-- Create an index on Name
CREATE INDEX idx_name
ON Students(Name);
-- Query using index
SELECT * FROM Students
WHERE Name = ‘Neeraj’;
………………………………………………………………………………..
Joins in SQL
Type Description
INNER JOIN Returns matching rows in both tables
LEFT JOIN All rows from left table + matched from right
RIGHT JOIN All rows from right table + matched from left
FULL JOIN All matched + unmatched rows from both tables
SELECT [Link], [Link]
FROM student s
INNER JOIN department d ON [Link] = [Link];
……………………………………………………………………………………..
Subquery
A query inside another query.
SELECT name FROM student WHERE age > (SELECT AVG(age) FROM
student):
TYPRS -> SINGLE ROW , MULTI ROW , CORELATED
IN , ANY , ALL , EXITS
EXISTS
Checks if the subquery returns at least one row.
SELECT name
FROM employees e
WHERE EXISTS (SELECT 1 FROM departments d WHERE e.dept_id =
d.dept_id);
2. IN
Compares a value with a list of values from the subquery.
SELECT name
FROM employees
WHERE dept_id IN (SELECT dept_id FROM departments WHERE
location='Delhi');
3. ANY
Returns true if the condition matches at least one value.
SELECT name
FROM employees
WHERE salary > ANY (SELECT salary FROM employees WHERE
dept_id=2);
👉 Salary greater than any one employee in dept 2.
4. ALL
Returns true if the condition matches all values.
SELECT name
FROM employees
WHERE salary > ALL (SELECT salary FROM employees WHERE
dept_id=2);
…………………………………………………………………….
Aggregate Functions
Function Description Syntax Example
COUNT() Counts rows SELECT COUNT(*) FROM Employees;
SUM() Total sum SELECT SUM(salary) FROM Employees;
AVG() Average SELECT AVG(salary) FROM Employees;
MIN() Minimum value SELECT MIN(salary) FROM Employees;
MAX() Maximum value SELECT MAX(salary) FROM Employees;
---------------------------------------------------------------------------------------
Aliases
Rename a column or table temporarily.
SELECT name AS student_name FROM student;
Views
A view is a virtual table created based on the result of a SQL query
We can reuse the view ,instead of full table
Creation of view
syntax
Create view view_name AS select col1 , col2 from table_name
condition
CREATE VIEW top_students AS
SELECT name, marks FROM student WHERE marks > 90;
Reuse of view
Syntax
Select * from view_name ;
Modify of view
Syntax
Create OR REPLACE VIEW view_name AS SELECT col1 , col2 FROM
table_name CONDITION;
DROP of view
syntax
DROP VIEW view_name ;
SETS IN SQL
Sets are used to combine the results of 2 or more sql queries
They are UNION , UNION all , INTERSECT , EXCEPT
UNION → Combines results, removes duplicates.
UNION ALL → Combines results, keeps duplicates.
INTERSECT → Returns only common records.
EXCEPT / MINUS → Returns records in first query but not in second.
UNION
Combines the result of 2 queries
Removes duplicates
Select col1 , col2 from stu
UNION
Select col1, col2 from stu1;
UNION ALL
Similar to UNION, but keeps duplicates.
Faster than UNION because it doesn’t check for duplicates.
Select col1 , col2 from stu
UNION ALL
Select col1, col2 from stu1;
INTERSECT
Returns only common rows from both queries.
Select col1 , col2 from stu
INTERSECT
Select col1, col2 from stu1;
EXCEPT
Returns rows from the first query that are not present in the second query.
SELECT column1, column2 FROM table1
EXCEPT
SELECT column1, column2 FROM table2;
What is a Trigger?
A Trigger is like an automatic action in a table.
A trigger is a database object that is automatically executed or fired when a specific event occurs in a
database table.
It runs automatically when you INSERT, UPDATE, or DELETE data.
You don’t call it ma nually.
Think of it like a doorbell: when someone presses the button (event), the bell rings (trigger runs).
🔹 Types of Triggers
1. BEFORE Trigger
Runs before the action happens.
Example: Check if salary is negative before inserting a row.
2. AFTER Trigger
Runs after the action happens.
Example: After adding a new employee, add a record in audit table.
3. INSTEAD OF Trigger
Runs instead of the action.
Example: When someone tries to update a table, do your own custom update instead.
Key Points
Trigger = automatic action
Types = Before, After, Instead Of
Common uses: check data, log changes, enforce rules
Conversion functions are used to change data from one type to another.
Useful when you need to convert numbers to strings, dates to strings, or strings to
numbers, etc.
🔹 1. CAST() Function
Definition:
CAST() converts a value from one data type to another.
Standard SQL function.
Convert()
Nf1 ->
Important Queries
-- >Find total students
SELECT COUNT(*) FROM student;
-- >Find max marks
SELECT MAX(marks) FROM student;
-- >Find students in specific department
SELECT * FROM student WHERE deptid = 2;
--> List students alphabetically
SELECT * FROM student ORDER BY name ASC;