Important SQL Queries – Notes
1. ORDER BY – Sorting Data
The ORDER BY clause is used to sort the result set in ascending or descending order.
Syntax:
SELECT column_name(s)
FROM table_name
ORDER BY column_name ASC | DESC;
Example:
SELECT * FROM Student
ORDER BY marks DESC;
2. DISTINCT – Removing Duplicate Values
DISTINCT is used to eliminate duplicate records from the result.
Syntax:
SELECT DISTINCT column_name
FROM table_name;
Example:
SELECT DISTINCT dept FROM Student;
3. BETWEEN – Range Query
BETWEEN is used to filter values within a specified range.
Syntax:
SELECT *
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Example:
SELECT * FROM Student
WHERE marks BETWEEN 60 AND 80;
4. IN – Multiple Value Matching
IN allows checking multiple values in a condition.
Syntax:
SELECT *
FROM table_name
WHERE column_name IN (value1, value2, ...);
Example:
SELECT * FROM Student
WHERE dept IN ('CSE', 'ECE');
5. Aggregate Functions
Aggregate functions perform calculations on multiple rows.
Functions:
COUNT() – Number of rows
SUM() – Total
AVG() – Average
MAX() – Highest value
MIN() – Lowest value
Example:
SELECT COUNT(*) FROM Student;
6. GROUP BY – Grouping Records
GROUP BY groups rows that have the same values.
Syntax:
SELECT column_name, aggregate_function(column_name)
FROM table_name
GROUP BY column_name;
Example:
SELECT dept, COUNT(*)
FROM Student
GROUP BY dept;
7. HAVING – Filtering Groups
HAVING is used to filter grouped records.
Syntax:
SELECT column_name, aggregate_function(column_name)
FROM table_name
GROUP BY column_name
HAVING condition;
Example:
SELECT dept, AVG(marks)
FROM Student
GROUP BY dept
HAVING AVG(marks) > 70;
8. JOIN – Combining Tables
JOIN is used to retrieve data from multiple tables.
INNER JOIN Syntax:
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON condition;
Example:
SELECT [Link], Course.course_name
FROM Student
INNER JOIN Course
ON Student.student_id = Course.student_id;
9. Subquery
A query inside another query.
Syntax:
SELECT *
FROM table_name
WHERE column_name = (SELECT column_name FROM table_name);
Example:
SELECT * FROM Student
WHERE marks > (SELECT AVG(marks) FROM Student);
10. EXISTS
EXISTS checks whether a subquery returns any records.
Syntax:
SELECT *
FROM table_name
WHERE EXISTS (subquery);
Example:
SELECT * FROM Student s
WHERE EXISTS (
SELECT * FROM Course c
WHERE s.student_id = c.student_id
);
11. LIMIT / TOP
Used to restrict number of rows.
MySQL:
SELECT * FROM Student LIMIT 5;
SQL Server:
SELECT TOP 5 * FROM Student;
12. IS NULL
Checks for NULL values.
Syntax:
SELECT *
FROM table_name
WHERE column_name IS NULL;
Example:
SELECT * FROM Student
WHERE marks IS NULL;
13. Summary
WHERE filters rows
GROUP BY groups rows
HAVING filters groups
ORDER BY sorts data
JOIN combines tables