Chapter 03
SQL SELECT, WHERE & Clauses
7 topics · 1 sections · beginner-friendly study notes · Updated
SELECT reads data from tables.
WHERE, ORDER BY, GROUP BY and HAVING help us filter, sort and summarise it.
INSERT, UPDATE and DELETE change the data.
Aggregate functions like COUNT and SUM calculate totals.
About 80 percent of daily SQL work is SELECT with filters and groups.
This chapter is the most used part of SQL.
Reports like "total sales this month", "top 5 students" and "employees by department" all use these commands.
SELECT Statement
SELECT is used to read data from one or more tables. The result is shown as a new table called the result set.
In short: SELECT means "show me these columns from this table".
Think about it
SELECT is the most used command in SQL. Every report, search box and dashboard uses it. Asking the clerk: "Show me only the name and marks column of the student register".
Basic form: SELECT column1, column2 FROM table_name.
Use * to show every column, but in real projects it is better to name the columns you need.
LIMIT n (MySQL, PostgreSQL) or TOP n (SQL Server) restricts the number of rows.
SELECT can also calculate: SELECT marks + 5 shows the marks plus five without changing the table.
The order of writing is SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT.
The database runs them in a different order: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT.
Key points
- Result set: Rows returned by a
SELECT. - *: Short form for all columns.
- LIMIT: Restricts how many rows are returned.
SELECTdoes not change the table.- Avoid
SELECT* in big applications. Ask only for the columns you need.
Read more
Example
CodeSELECT examples: -- All columns SELECT * FROM student; -- Only two columns SELECT name, marks FROM student; -- First 5 rows SELECT name, marks FROM student LIMIT 5; -- Calculated column SELECT name, marks + 5 AS grace_marks FROM student;
WHERE, AND, OR
WHERE filters rows by a condition. AND needs all conditions true. OR needs at least one true.
In short: WHERE is a filter. AND means "both". OR means "either".
Think about it
Without WHERE we get every row. In UPDATE and DELETE, forgetting WHERE changes all rows. Asking the clerk: "Show students from Delhi AND with marks above 80".
Comparison operators: =, <> (or !
=), >, <, >=, <=.
BETWEEN a AND b checks a range, including both ends.
IN (a, b, c) checks a list.
LIKE searches patterns: % means any number of characters and _ means exactly one.
IS NULL checks for empty values; = NULL never works.
NOT reverses a condition.
When AND and OR are mixed, AND is evaluated first.
Use brackets to make the meaning clear.
Key points
Read more
Example
CodeFiltering rows:
SELECT * FROM student WHERE city = 'Delhi';
SELECT * FROM student WHERE city = 'Delhi' AND marks > 80;
SELECT * FROM student WHERE city = 'Delhi' OR city = 'Pune';
SELECT * FROM student WHERE city IN ('Delhi', 'Pune', 'Agra');
SELECT * FROM student WHERE marks BETWEEN 60 AND 80;
SELECT * FROM student WHERE name LIKE 'A%';
SELECT * FROM student WHERE email IS NULL;
-- Brackets make the meaning clear
SELECT * FROM student WHERE (city = 'Delhi' OR city = 'Pune') AND marks > 70;ORDER BY
ORDER BY sorts the result set in ascending (ASC) or descending (DESC) order.
In short: It arranges the rows, like making a merit list.
Think about it
Merit lists, top-10 reports and latest-first feeds all need sorting. A rank list of students by marks, highest first.
The default order is ASC (small to big, A to Z).
Use DESC for big to small.
We can sort by many columns: ORDER BY city ASC, marks DESC sorts by city first, then by marks inside each city.
We can sort by a column position (ORDER BY 2) or by an alias.
ORDER BY is the last step before LIMIT, so it can use the alias made in SELECT.
Without ORDER BY, the order of rows is not guaranteed.
Key points
Read more
Example
CodeSorting results: SELECT name, marks FROM student ORDER BY marks DESC; -- Sort by city, then by marks highest first SELECT name, city, marks FROM student ORDER BY city ASC, marks DESC; -- Top 3 students SELECT name, marks FROM student ORDER BY marks DESC LIMIT 3;
DISTINCT & Aliases
DISTINCT removes duplicate rows from the result. An alias gives a temporary new name to a column or table using AS.
In short: DISTINCT shows each value only once. An alias is a nickname.
Think about it
Reports need unique lists and readable column names. Listing which cities our students come from, without repeating a city again and again.
SELECT DISTINCT city FROM student shows each city once, even if many students live there.
DISTINCT works on the full combination of selected columns.
COUNT(DISTINCT city) counts different cities.
A column alias (marks AS total_marks) makes headings clear.
A table alias (student s) shortens long names and is needed in self joins.
The alias exists only for that query.
If an alias has spaces, put it in quotes.
Key points
Example
CodeDISTINCT and aliases: SELECT DISTINCT city FROM student; -- Unique pairs of city and department SELECT DISTINCT city, dept_id FROM student; -- Column alias SELECT name AS student_name, marks AS total_marks FROM student; -- Table alias SELECT s.name, s.city FROM student s WHERE s.marks > 75; SELECT COUNT(DISTINCT city) AS total_cities FROM student;
GROUP BY & HAVING
GROUP BY puts rows with the same value into groups so we can calculate on each group. HAVING filters those groups after they are made.
In short: GROUP BY makes piles. HAVING keeps only the piles you like.
Think about it
Summary reports such as "students per city" or "average salary per department" need grouping. Sorting the class into piles by city, and counting each pile. Then showing only the piles with more than 5 students.
GROUP BY is mostly used with aggregate functions.
For example, GROUP BY city with COUNT(*) gives the number of students in each city.
Every column in SELECT must either be in GROUP BY or be inside an aggregate function.
WHERE filters rows BEFORE grouping.
HAVING filters groups AFTER grouping, so HAVING can use aggregate functions and WHERE cannot.
Order of work: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY.
Key points
Example
CodeGrouping rows: -- Students in every city SELECT city, COUNT(*) AS total_students FROM student GROUP BY city; -- Only cities with more than 5 students SELECT city, COUNT(*) AS total_students FROM student GROUP BY city HAVING COUNT(*) > 5; -- WHERE first, then GROUP BY, then HAVING SELECT dept_id, AVG(marks) AS avg_marks FROM student WHERE marks >= 40 GROUP BY dept_id HAVING AVG(marks) > 60 ORDER BY avg_marks DESC;
INSERT, UPDATE, DELETE
INSERT adds new rows. UPDATE changes values in existing rows. DELETE removes rows. These are DML commands.
In short: INSERT = add. UPDATE = edit. DELETE = remove.
Think about it
Applications are not useful if they cannot save and change data. Adding a new student to the register, correcting a spelling mistake, and removing a student who left the college.
INSERT INTO table (columns) VALUES (values) adds one row.
We can add many rows in one command by writing several value lists.
UPDATE table SET column = value WHERE condition changes the matching rows.
DELETE FROM table WHERE condition removes the matching rows.
If WHERE is missing, UPDATE changes every row and DELETE removes every row.
Run a SELECT with the same WHERE first to see which rows will be affected.
In a transaction, these commands can be undone with ROLLBACK before COMMIT.
Key points
Read more
Example
CodeChanging data: -- Add one row INSERT INTO student (roll_no, name, city, marks) VALUES (1, 'Asha', 'Delhi', 88); -- Add many rows INSERT INTO student (roll_no, name, city, marks) VALUES (2, 'Ravi', 'Pune', 72), (3, 'Meena', 'Agra', 91); -- Change data UPDATE student SET marks = 95 WHERE roll_no = 3; -- Remove data DELETE FROM student WHERE roll_no = 2;
Aggregate Functions (COUNT, SUM, AVG, MIN, MAX)
Aggregate functions work on many rows and return one value. The main ones are COUNT, SUM, AVG, MIN and MAX.
In short: They turn a list of numbers into one answer, like total or average.
Think about it
Totals, averages and counts are the base of almost every business report. Class teacher finds the total students, highest marks, lowest marks and class average.
COUNT(*) counts all rows.
COUNT(column) counts only rows where that column is not NULL.
SUM adds values.
AVG finds the average.
MIN finds the smallest value and MAX the largest.
Aggregate functions ignore NULL values, except COUNT(*).
They are often used with GROUP BY.
Without GROUP BY they give one result for the whole table.
We cannot mix a normal column with an aggregate unless we group by that column.
Key points
Example
CodeAggregate functions: SELECT COUNT(*) AS total_students, SUM(marks) AS total_marks, ROUND(AVG(marks),2) AS average_marks, MIN(marks) AS lowest, MAX(marks) AS highest FROM student; -- Per department SELECT dept_id, COUNT(*) AS students, MAX(marks) AS topper_marks FROM student GROUP BY dept_id;
Solved examples
Show name and marks of students from Delhi who scored more than 75, highest marks first.
- Table: student(roll_no, name, city, marks)
One SELECT query
Formula Applied:—Approach note: Write the query in order: SELECT, FROM, WHERE, ORDER BY.
Find the number of employees and the average salary in each department. Show only departments with average salary above 40000.
- Table: employees(emp_id, name, salary, dept_id)
GROUP BY with HAVING
Formula Applied:—Approach note: If the condition has COUNT, SUM, AVG, MIN or MAX, use HAVING, not WHERE.
Give a 10 percent raise to employees of department 2 only.
- Table: employees(emp_id, name, salary, dept_id)
UPDATE with WHERE
Formula Applied:—Approach note: First run SELECT * FROM employees WHERE dept_id = 2; to preview the rows.
List each city once, along with the highest marks in that city, for students whose name starts with A or S.
- Table: student(roll_no, name, city, marks)
Query using LIKE, GROUP BY, MAX
Formula Applied:—Approach note: WHERE runs first on rows, then GROUP BY makes groups.
Real-world applications
Using SQL SELECT, WHERE and Clauses in real projects
Reports like "total sales this month", "top 5 students" and "employees by department" all use these commands.
Common mistakes
❌ Myth: WHERE and HAVING are the same.
Why this is wrong: Both filter data.
✅ Verified Truth: WHERE filters rows before grouping. HAVING filters groups after grouping and can use aggregate functions.
⚠️ Exam Tip: Rule: aggregate in condition means HAVING.
❌ Myth: WHERE column = NULL finds empty values.
Why this is wrong: It looks natural to compare with NULL.
✅ Verified Truth: NULL means unknown, so = NULL is never true. Use IS NULL or IS NOT NULL.
⚠️ Exam Tip: Always write IS NULL.
❌ Myth: COUNT(*) and COUNT(column) always give the same answer.
Why this is wrong: Both count rows.
✅ Verified Truth: COUNT(*) counts all rows. COUNT(column) skips rows where the column is NULL.
⚠️ Exam Tip: Check NULLs before choosing.
Revision notes
SELECT reads data from tables. WHERE, ORDER BY, GROUP BY and HAVING help us filter, sort and summarise it. INSERT, UPDATE and DELETE change the data. Aggregate functions like COUNT and SUM calculate totals.
High-Yield Quick Revision Points
- SELECT columns FROM table. Use WHERE to filter rows.
- AND needs both true. OR needs one true. Use brackets when mixing.
- Use IS NULL for empty values. Use LIKE with % and _ for patterns.
- ORDER BY sorts. Default is ASC. Use DESC for highest first.
- DISTINCT removes duplicates. AS gives an alias.
- GROUP BY makes groups. HAVING filters groups. WHERE filters rows.
- INSERT adds, UPDATE edits, DELETE removes. Always use WHERE with UPDATE and DELETE.
- Aggregates: COUNT, SUM, AVG, MIN, MAX. They skip NULL values.
Practice questions
Which clause sorts the result?
Which clause can filter using an aggregate like COUNT(*)?
Which query finds names starting with A?
What happens if we run DELETE FROM student; without WHERE?
Which function returns the largest value?
Which keyword removes duplicate rows from the result?