SQL Practicle Notes
SQL Practicle Notes
DML
Project
College Management System
Students
Teachers
Departments
Courses
Employees
Fees
Marks
USE CollegeManagementSystem;
Database Structure
CollegeManagementSystem
│
├── Student
├── Teacher
├── Department
├── Course
├── Employee
├── Fees
└── Marks
Department Table
Every student, teacher and employee belongs to one department.
Insert Records
Department Table
Student Table
CREATE TABLE Student
(
StudentID INT PRIMARY KEY,
StudentName VARCHAR(50),
Age INT,
Gender VARCHAR(10),
DepartmentID INT,
Year INT,
Semester INT,
City VARCHAR(30),
Phone VARCHAR(15),
FOREIGN KEY (DepartmentID)
REFERENCES Department(DepartmentID)
);
Insert Students
Student Table
Insert Records
Employee Table
Non-teaching staff
Insert Data
INSERT INTO Employee
VALUES
(301,'Mahesh',1,'Lab Assistant',35000,'Bangalore'),
(302,'Suresh',2,'Clerk',30000,'Delhi'),
(303,'Ramesh',3,'Accountant',45000,'Mumbai'),
(304,'Ganesh',5,'System Admin',60000,'Hyderabad'),
(305,'Naresh',4,'Office Assistant',28000,'Pune');
Course Table
CREATE TABLE Course
(
CourseID INT PRIMARY KEY,
CourseName VARCHAR(50),
DepartmentID INT,
Credits INT,
TeacherID INT,
FOREIGN KEY(DepartmentID)
REFERENCES Department(DepartmentID),
FOREIGN KEY(TeacherID)
REFERENCES Teacher(TeacherID)
);
Insert Courses
Fees Table
CREATE TABLE Fees
(
ReceiptNo INT PRIMARY KEY,
StudentID INT,
TotalFees DECIMAL(10,2),
PaidAmount DECIMAL(10,2),
PendingAmount DECIMAL(10,2),
FOREIGN KEY(StudentID)
REFERENCES Student(StudentID)
);
Insert Records
Marks Table
CREATE TABLE Marks
(
MarkID INT PRIMARY KEY,
StudentID INT,
CourseID INT,
InternalMarks INT,
ExternalMarks INT,
TotalMarks INT,
Grade CHAR(2),
FOREIGN KEY(StudentID)
REFERENCES Student(StudentID),
FOREIGN KEY(CourseID)
REFERENCES Course(CourseID)
);
Insert Records
USE DATABASE
CREATE TABLE
Next (Page 2)
[‘]
SELECT
WHERE
ORDER BY
DISTINCT
LIMIT
TOP (SQL Server)
LIKE
BETWEEN
IN
NOT IN
IS NULL
IS NOT NULL
Database Tables
CollegeManagementSystem
Department
Student
Teacher
Employee
Course
Fees
Marks
1. SELECT Statement
The SELECT statement is used to retrieve data from one or more tables.
Syntax
SELECT column_name
FROM table_name;
Output
SELECT StudentName
FROM Student;
Syntax
SELECT *
FROM Student
WHERE condition;
SELECT *
FROM Student
WHERE City='Bangalore';
Output
StudentName City
Akash Bangalore
Kiran Bangalore
SELECT *
FROM Student
WHERE Age>21;
DepartmentID = 5
SELECT *
FROM Student
WHERE DepartmentID=5;
SELECT *
FROM Student
WHERE Year=4;
Students in Semester 5.
SELECT *
FROM Student
WHERE Semester=5;
SELECT *
FROM Teacher
WHERE Salary>90000;
SELECT *
FROM Employee
WHERE City='Bangalore';
3. Comparison Operators
Operator Meaning
= Equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
!= Not equal
<> Not equal
SELECT *
FROM Employee
WHERE Salary>=60000;
SELECT *
FROM Student
WHERE DepartmentID<>5;
4. AND Operator
Both conditions must be true.
Students from Bangalore AND studying in Year 3.
SELECT *
FROM Student
WHERE City='Bangalore'
AND Year=3;
SELECT *
FROM Employee
WHERE City='Bangalore'
AND Salary>30000;
5. OR Operator
Either condition can be true.
SELECT *
FROM Student
WHERE City='Bangalore'
OR City='Delhi';
Teachers with salary greater than ₹95,000 OR experience greater than 15 years.
SELECT *
FROM Teacher
WHERE Salary>95000
OR Experience>15;
6. NOT Operator
Reverse the condition.
SELECT *
FROM Student
WHERE NOT City='Bangalore';
SELECT *
FROM Employee
WHERE NOT DepartmentID=1;
7. ORDER BY
Sorts the data.
SELECT *
FROM Student
ORDER BY StudentName;
Descending order.
SELECT *
FROM Student
ORDER BY StudentName DESC;
SELECT *
FROM Teacher
ORDER BY Salary DESC;
SELECT *
FROM Employee
ORDER BY City ASC;
SELECT *
FROM Student
ORDER BY Year, Semester;
8. DISTINCT
Removes duplicate values.
Output
City
Bangalore
Delhi
Hyderabad
Mumbai
Pune
Chennai
9. LIMIT (MySQL)
Returns only a specified number of rows.
SELECT *
FROM Student
LIMIT 3;
SELECT *
FROM Teacher
ORDER BY Salary DESC
LIMIT 2;
SELECT *
FROM Student
LIMIT 2,3;
This means:
SELECT TOP 3 *
FROM Student;
Starts with A
SELECT *
FROM Student
WHERE StudentName LIKE 'A%';
Ends with h.
SELECT *
FROM Student
WHERE StudentName LIKE '%h';
Contains "ha".
SELECT *
FROM Student
WHERE StudentName LIKE '%ha%';
Second letter is k.
SELECT *
FROM Student
WHERE StudentName LIKE '_k%';
SELECT *
FROM Student
WHERE StudentName LIKE '_____';
Wildcards
Wildcard Meaning
% Any number of characters
_ Exactly one character
11. BETWEEN
Inclusive range.
SELECT *
FROM Student
WHERE Age BETWEEN 20 AND 22;
SELECT *
FROM Teacher
WHERE Salary BETWEEN 85000 AND 100000;
12. IN Operator
Checks multiple values.
SELECT *
FROM Student
WHERE City IN ('Bangalore','Delhi','Pune');
SELECT *
FROM Employee
WHERE DepartmentID IN (1,5);
13. NOT IN
Students not from Bangalore or Delhi.
SELECT *
FROM Student
WHERE City NOT IN ('Bangalore','Delhi');
14. IS NULL
Find missing values.
SELECT *
FROM Student
WHERE Phone IS NULL;
SELECT [Link],
[Link]
FROM Student S;
SELECT EmployeeName,
Salary,
Salary+5000 AS NewSalary
FROM Employee;
Summary
Clause Purpose
SELECT Retrieve data
WHERE Filter rows
ORDER BY Sort rows
DISTINCT Remove duplicates
LIMIT Restrict rows (MySQL)
TOP Restrict rows (SQL Server)
LIKE Pattern matching
BETWEEN Range filtering
IN Multiple values
NOT IN Exclude values
IS NULL Find NULL values
IS NOT NULL Find non-NULL values
AS Alias for column/table
Practice Questions
1. Display all students.
2. Display only student names and cities.
3. Find students from Delhi.
4. Find students older than 21.
5. Find teachers earning more than ₹90,000.
6. Display employees sorted by salary (highest first).
7. Show all unique student cities.
8. Display the first five students.
9. Find students whose names start with 'A'.
10. Find students whose names end with 'a'.
11. Find students aged between 20 and 22.
12. Find students from Bangalore, Delhi, or Hyderabad.
13. Find students not from Bangalore.
14. Display students whose phone number is not NULL.
15. Show employee salaries increased by ₹5,000 using an alias.
SQL Complete Notes (College Management System)
Page 3 – Aggregate Functions (MRF), GROUP BY, HAVING
This page covers one of the most frequently asked SQL interview topics.
Almost every SQL interview includes questions on COUNT, SUM, AVG, MIN,
MAX, GROUP BY, and HAVING.
Execution
Clause Purpose
Order
GROUP
3 Create groups
BY
ORDER
6 Sort output
BY
Return limited
7 LIMIT
rows
Remember:
FROM
↓
WHERE
↓
GROUP BY
↓
HAVING
↓
SELECT
↓
ORDER BY
↓
LIMIT
Functio
Purpose
n
COUNT(
Count rows
)
AVG() Average
Smallest
MIN()
value
Largest
MAX()
value
COUNT()
Count total students.
SELECT COUNT(*)
FROM Student;
Output
COUNT(
*)
Count employees.
SELECT COUNT(*)
FROM Employee;
Count teachers.
SELECT COUNT(*)
FROM Teacher;
SUM()
Total salary of all teachers.
SELECT SUM(Salary)
FROM Teacher;
AVG()
Average teacher salary.
SELECT AVG(Salary)
FROM Teacher;
Average marks.
SELECT AVG(TotalMarks)
FROM Marks;
MAX()
Highest teacher salary.
SELECT MAX(Salary)
FROM Teacher;
MIN()
Lowest teacher salary.
SELECT MIN(Salary)
FROM Teacher;
Lowest marks.
SELECT MIN(TotalMarks)
FROM Marks;
GROUP BY
GROUP BY groups rows having the same value.
Syntax
SELECT column_name,
aggregate_function(column_name)
FROM table_name
GROUP BY column_name;
Count students department-wise
SELECT DepartmentID,
COUNT(*) AS TotalStudents
FROM Student
GROUP BY DepartmentID;
Example Output
Departmen TotalStude
tID nts
1 2
2 1
3 1
4 1
5 3
HAVING Clause
HAVING filters groups, while WHERE filters rows.
Syntax
SELECT column_name,
aggregate_function(column_name)
FROM table_name
GROUP BY column_name
HAVING condition;
Departmen COUNT(
tID *)
1 2
5 3
WHERE vs HAVING
WHERE
Filters rows before grouping.
SELECT *
FROM Student
WHERE Age>20;
HAVING
Filters groups after grouping.
SELECT DepartmentID,
COUNT(*)
FROM Student
GROUP BY DepartmentID
HAVING COUNT(*)>1;
Lowest marks
SELECT MIN(TotalMarks)
FROM Marks;
Summary
Clause /
Purpose
Function
Total of numeric
SUM()
values
Clause /
Purpose
Function
Filter grouped
HAVING
results
Practice Questions
1. Count total students.
2. Count students in each department.
3. Count students in each city.
4. Find the average age of students in each department.
5. Find the total salary of employees in each department.
6. Find the highest-paid teacher.
7. Find the lowest-paid employee.
8. Find the average marks for each department.
9. Show departments having more than two students.
[Link] cities having more than one student.
[Link] qualifications with more than one teacher.
[Link] departments where the average employee salary is greater than
₹40,000.
[Link] the department with the highest number of students.
[Link] the total pending fees.
[Link] the maximum and minimum student marks.
SQL Complete Notes (College Management System)
Page 4 – SQL Joins (Most Important Interview Topic)
Joins are used to combine data from two or more tables using a related
column (usually a Primary Key and Foreign Key).
In our College Management System, we have these relationships:
Department (DepartmentID)
↑
│
┌──────┼────────┐
│ │ │
Student Teacher Employee
│
│ StudentID
▼
Marks
│
│ CourseID
▼
Course
Departmen DepartmentNa
tID me
Computer
1
Science
2 Mechanical
3 Electrical
4 Civil
AI & Data
5
Science
Student
101 Akash 5
102 Rahul 1
103 Priya 2
104 Neha 5
105 Rohit 3
106 Sneha 4
107 Kiran 1
108 Anjali 5
What is a JOIN?
Suppose you want to display:
Student Name Department Name
The Student table only contains DepartmentID, not the department name.
Student
StudentNa Departmen
me tID
Akash 5
Department
Departmen DepartmentNa
tID me
AI & Data
5
Science
To get:
StudentNa DepartmentNa
me me
AI & Data
Akash
Science
we use a JOIN.
Types of Joins
Join Purpose
FULL OUTER
All rows from both tables
JOIN
1. INNER JOIN
Returns only matching records.
Syntax
SELECT columns
FROM Table1
INNER JOIN Table2
ON [Link] = [Link];
AI & Data
101 Akash
Science
Computer
102 Rahul
Science
AI & Data
104 Neha
Science
Computer
107 Kiran
Science
AI & Data
108 Anjali
Science
Using Aliases
SELECT [Link],
[Link]
FROM Student S
INNER JOIN Department D
ON [Link] = [Link];
************* *************
*************======*************
*************
Only the common (matching) rows are returned.
2. LEFT JOIN
Returns:
All rows from the left table
Matching rows from the right table
If no match exists, returns NULL
Syntax
SELECT columns
FROM Table1
LEFT JOIN Table2
ON [Link] = [Link];
DepartmentNa
StudentName
me
AI & Data
Akash
Science
Unknown
NULL
Student
*************======*************
*************
*************
Everything from the left table is returned.
3. RIGHT JOIN
Returns:
All rows from the right table
Matching rows from the left table
SELECT [Link],
[Link]
FROM Student S
RIGHT JOIN Department D
ON [Link] = [Link];
Suppose a department has no students:
DepartmentNa StudentNa
me me
Finance NULL
*************
*************======*************
*************
Everything from the right table is returned.
Note: MySQL supports RIGHT JOIN, but many developers prefer LEFT JOIN by
reversing the table order because it is often easier to read.
MySQL Note
MySQL does not support FULL OUTER JOIN directly.
Equivalent using UNION:
SELECT [Link],
[Link]
FROM Student S
LEFT JOIN Department D
ON [Link] = [Link]
UNION
SELECT [Link],
[Link]
FROM Student S
RIGHT JOIN Department D
ON [Link] = [Link];
Example
Stude Cours
nt e
Akash Java
Akash ML
Rahul Java
Rahul ML
6. SELF JOIN
A table joined with itself.
Suppose the Employee table has:
Employ Manag
ee er
Mahesh Ganesh
Suresh Ganesh
Ganesh NULL
Four-Table Join
Student + Department + Marks + Course
SELECT [Link],
[Link],
[Link],
[Link]
FROM Student S
INNER JOIN Department D
ON [Link] = [Link]
INNER JOIN Marks M
ON [Link] = [Link]
INNER JOIN Course C
ON [Link] = [Link];
Five-Table Join
Student + Department + Marks + Course + Teacher
SELECT [Link],
[Link],
[Link],
[Link],
[Link]
FROM Student S
INNER JOIN Department D
ON [Link] = [Link]
INNER JOIN Marks M
ON [Link] = [Link]
INNER JOIN Course C
ON [Link] = [Link]
INNER JOIN Teacher T
ON [Link] = [Link];
Summary
Join Returns
FULL OUTER All rows from both tables (not directly supported
JOIN in MySQL)
Practice Questions
1. Display student names with department names.
2. Display teacher names with department names.
3. Display employee names with department names.
4. Display courses with teacher names.
5. Display student names with total marks.
6. Display student names with fee details.
7. Display student, department, course, and marks using four tables.
8. Display student, department, course, teacher, and marks using five tables.
9. Write a LEFT JOIN to show all departments even if no students belong to
them.
[Link] a SELF JOIN to display employees and their managers.
1. Subqueries
A subquery is a query inside another query.
Outer Query
|
|---- Inner Query (Subquery)
Types of Subqueries
1. Single Row Subquery
2. Multiple Row Subquery
3. Correlated Subquery
Student StudentNa Ag
ID me e
105 Rohit 23
Example 2
Find the teacher earning the highest salary.
SELECT *
FROM Teacher
WHERE Salary = (
SELECT MAX(Salary)
FROM Teacher
);
Example 3
Find employees earning more than the average salary.
SELECT *
FROM Employee
WHERE Salary >
(
SELECT AVG(Salary)
FROM Employee
);
Example
Find students belonging to departments where teachers have more than 15
years of experience.
SELECT *
FROM Student
WHERE DepartmentID IN
(
SELECT DepartmentID
FROM Teacher
WHERE Experience>15
);
Using ANY
SELECT *
FROM Employee
WHERE Salary >
ANY
(
SELECT Salary
FROM Employee
WHERE DepartmentID=1
);
Using ALL
SELECT *
FROM Employee
WHERE Salary >
ALL
(
SELECT Salary
FROM Employee
WHERE DepartmentID=1
);
Correlated Subquery
The inner query depends on the outer query.
Example
SELECT StudentName
FROM Student S
WHERE EXISTS
(
SELECT *
FROM Fees F
WHERE [Link]=[Link]
);
EXISTS
Returns TRUE if the subquery returns at least one row.
SELECT *
FROM Department D
WHERE EXISTS
(
SELECT *
FROM Student S
WHERE [Link]=[Link]
);
NOT EXISTS
SELECT *
FROM Department D
WHERE NOT EXISTS
(
SELECT *
FROM Student S
WHERE [Link]=[Link]
);
LOWER
SELECT LOWER(StudentName)
FROM Student;
LENGTH
SELECT StudentName,
LENGTH(StudentName)
FROM Student;
CONCAT
SELECT CONCAT(StudentName,' - ',City)
FROM Student;
Output
Akash - Bangalore
Rahul - Delhi
SUBSTRING
SELECT SUBSTRING(StudentName,1,3)
FROM Student;
Output
Aka
Rah
Pri
REPLACE
SELECT REPLACE(StudentName,'a','@')
FROM Student;
TRIM
SELECT TRIM(' SQL ');
Numeric Functions
ROUND
SELECT ROUND(98.567,2);
Output
98.57
CEIL
SELECT CEIL(98.2);
Output
99
FLOOR
SELECT FLOOR(98.9);
Output
98
ABS
SELECT ABS(-45);
Output
45
MOD
SELECT MOD(20,3);
Output
2
Date Functions
Current date
SELECT CURDATE();
Current time
SELECT CURTIME();
Current timestamp
SELECT NOW();
Year
SELECT YEAR(CURDATE());
Month
SELECT MONTH(CURDATE());
CASE Statement
Acts like an IF-ELSE.
Example
SELECT StudentName,
CASE
WHEN TotalMarks>=90 THEN 'Outstanding'
WHEN TotalMarks>=80 THEN 'Excellent'
WHEN TotalMarks>=70 THEN 'Good'
WHEN TotalMarks>=60 THEN 'Average'
ELSE 'Needs Improvement'
END AS Performance
FROM Student
JOIN Marks
ON [Link]=[Link];
Output
Stude Performan
nt ce
Akash Excellent
Outstandin
Neha
g
UNION
Combines two result sets.
Duplicate rows removed.
SELECT City
FROM Student
UNION
SELECT City
FROM Employee;
UNION ALL
Keeps duplicates.
SELECT City
FROM Student
UNION ALL
SELECT City
FROM Employee;
Views
A View is a virtual table.
Create
CREATE VIEW StudentDetails
AS
SELECT StudentName,
DepartmentID,
City
FROM Student;
Display
SELECT *
FROM StudentDetails;
Delete
DROP VIEW StudentDetails;
Index
Improves searching speed.
Create
CREATE INDEX idx_studentname
ON Student(StudentName);
Delete
DROP INDEX idx_studentname
ON Student;
Constraints Review
PRIMARY KEY
FOREIGN KEY
NOT NULL
UNIQUE
CHECK
DEFAULT
Example
CREATE TABLE Example
(
ID INT PRIMARY KEY,
Name VARCHAR(50) NOT NULL,
Email VARCHAR(50) UNIQUE,
Age INT CHECK(Age>=18),
City VARCHAR(30) DEFAULT 'Bangalore'
);
COMMIT
Save changes permanently.
UPDATE Fees
SET PaidAmount=100000
WHERE StudentID=101;
COMMIT;
ROLLBACK
Undo changes before commit.
UPDATE Fees
SET PaidAmount=0
WHERE StudentID=101;
ROLLBACK;
SAVEPOINT
Create a rollback point.
SAVEPOINT BeforeUpdate;
Example
UPDATE Employee
SET Salary=70000
WHERE EmployeeID=301;
SAVEPOINT S1;
UPDATE Employee
SET Salary=80000
WHERE EmployeeID=302;
ROLLBACK TO S1;
GRANT
GRANT SELECT
ON Student
TO User1;
REVOKE
REVOKE SELECT
ON Student
FROM User1;
Stored Procedure
Reusable SQL block.
Create
DELIMITER //
BEGIN
SELECT *
FROM Student;
END //
DELIMITER ;
Execute
CALL GetStudents();
BEGIN
SELECT *
FROM Student
WHERE DepartmentID=dept;
END //
DELIMITER ;
Execute
CALL GetDepartmentStudents(5);
Trigger
Automatically executes after an event.
Suppose we maintain a salary log.
Log Table
CREATE TABLE SalaryLog
(
EmployeeID INT,
OldSalary DECIMAL(10,2),
NewSalary DECIMAL(10,2)
);
Trigger
DELIMITER //
AFTER UPDATE
ON Employee
BEGIN
(
[Link],
[Link],
[Link]
);
END //
DELIMITER ;
Interview Questions
Highest salary
SELECT MAX(Salary)
FROM Teacher;
Catego
Commands
ry
DQL SELECT
Function Example
UPPER UPPER(Name)
Function Example
LOWER LOWER(Name)
LENGTH LENGTH(Name)
CONCAT CONCAT(A,B)
SUBSTRIN SUBSTRING(Name,1
G ,3)
REPLACE(Name,'a','
REPLACE
@')
ROUND ROUND(Number,2)
CEIL CEIL(Number)
FLOOR FLOOR(Number)
ABS ABS(Number)
Functio
Purpose
n
Count
COUNT
rows
SUM Total
AVG Average
MIN Smallest
MAX Largest
o RANK()
o DENSE_RANK()
o LEAD()
o LAG()
o NTILE()
o Recursive CTEs
3. Advanced SQL Interview Questions
o Top N per group
o Duplicate records
o Pivot/Unpivot
o Running totals
These topics are frequently asked in companies like TCS, Infosys, Accenture,
Capgemini, Cognizant, Wipro, Deloitte, Amazon, Microsoft, and Google.