SQL Tutorial chapters (5)
  1. 01Introduction to SQL
  2. 02SQL Database & Tables (DDL)
  3. 03SQL SELECT, WHERE & Clauses
  4. 04SQL Joins & Subqueries
  5. 05SQL Views, Indexes & Practice

Chapter 03

SQL SELECT, WHERE & Clauses

7 topics · 1 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

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.

1

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".

SELECT rows from a 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.
  • SELECT does not change the table.
  • Avoid SELECT * in big applications. Ask only for the columns you need.

Example

Code
SELECT 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;
2

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

  • BETWEEN: Value lies inside a range, ends included.
  • IN: Value matches any item in a list.
  • LIKE: Pattern match using % and _.
  • IS NULL: Checks for a missing value.
  • Text values use single quotes in standard SQL.
  • NULL is not equal to anything, not even NULL. Use IS NULL.
  • AND runs before OR. Use brackets.

Read more

Example

Code
Filtering 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;
3

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.

Filter · sort · group · modify rows

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

  • ASC: Ascending order. This is the default.
  • DESC: Descending order.
  • Use ORDER BY with LIMIT to get the top N rows.
  • Without ORDER BY the row order may change.

Read more

Example

Code
Sorting 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;
4

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

  • DISTINCT: Keeps only unique rows.
  • Alias: Temporary nickname for a column or table.
  • AS: Keyword used to give an alias. It is optional in most databases.
  • An alias does not change the real name in the table.
  • DISTINCT applies to the whole row of selected columns.

Example

Code
DISTINCT 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;
5

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

  • GROUP BY: Makes groups of rows with equal values.
  • HAVING: Filters groups using aggregate conditions.
  • WHERE = filter rows. HAVING = filter groups.
  • Do not use aggregate functions inside WHERE.
  • Selected columns must be in GROUP BY or aggregated.

Example

Code
Grouping 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;
6

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

  • INSERT INTO: Adds one or more rows.
  • SET: Lists the new values in UPDATE.
  • Rows affected: How many rows the command changed.
  • Always use WHERE with UPDATE and DELETE.
  • List the column names in INSERT to avoid mistakes when the table changes.

Example

Code
Changing 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;
7

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

  • COUNT: Number of rows.
  • SUM: Total of values.
  • AVG: Average of values.
  • MIN / MAX: Smallest and largest values.
  • COUNT(*) counts NULL rows. COUNT(column) does not.
  • Aggregates skip NULL values.
  • Use ROUND(AVG(x), 2) to limit decimal places.

Example

Code
Aggregate 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

Example 01 · Basic

Show name and marks of students from Delhi who scored more than 75, highest marks first.

Given Data:
  • Table: student(roll_no, name, city, marks)
Required To Find:

One SELECT query

Formula Applied:—
Step-by-Step Solution:
Step 1: Select name and marks.
Step 2: Filter with WHERE city = 'Delhi' AND marks > 75.
Step 3: Sort with ORDER BY marks DESC.
Final Answer: SELECT name, marks FROM student WHERE city = 'Delhi' AND marks > 75 ORDER BY marks DESC;

Approach note: Write the query in order: SELECT, FROM, WHERE, ORDER BY.

Example 02 · Intermediate

Find the number of employees and the average salary in each department. Show only departments with average salary above 40000.

Given Data:
  • Table: employees(emp_id, name, salary, dept_id)
Required To Find:

GROUP BY with HAVING

Formula Applied:—
Step-by-Step Solution:
Step 1: Group rows by dept_id.
Step 2: Use COUNT(*) and AVG(salary).
Step 3: Use HAVING because the filter uses an aggregate.
Final Answer: SELECT dept_id, COUNT(*) AS total_employees, AVG(salary) AS avg_salary FROM employees GROUP BY dept_id HAVING AVG(salary) > 40000;

Approach note: If the condition has COUNT, SUM, AVG, MIN or MAX, use HAVING, not WHERE.

Example 03 · Basic

Give a 10 percent raise to employees of department 2 only.

Given Data:
  • Table: employees(emp_id, name, salary, dept_id)
Required To Find:

UPDATE with WHERE

Formula Applied:—
Step-by-Step Solution:
Step 1: Use UPDATE employees SET salary = salary * 1.10.
Step 2: Add WHERE dept_id = 2 so only that department changes.
Final Answer: UPDATE employees SET salary = salary * 1.10 WHERE dept_id = 2;

Approach note: First run SELECT * FROM employees WHERE dept_id = 2; to preview the rows.

Example 04 · Intermediate

List each city once, along with the highest marks in that city, for students whose name starts with A or S.

Given Data:
  • Table: student(roll_no, name, city, marks)
Required To Find:

Query using LIKE, GROUP BY, MAX

Formula Applied:—
Step-by-Step Solution:
Step 1: Filter rows using name LIKE 'A%' OR name LIKE 'S%'.
Step 2: Group by city.
Step 3: Use MAX(marks) for each city.
Final Answer: SELECT city, MAX(marks) AS highest_marks FROM student WHERE name LIKE 'A%' OR name LIKE 'S%' GROUP BY city;

Approach note: WHERE runs first on rows, then GROUP BY makes groups.

Real-world applications

SQL

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.

Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

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

  1. SELECT columns FROM table. Use WHERE to filter rows.
  2. AND needs both true. OR needs one true. Use brackets when mixing.
  3. Use IS NULL for empty values. Use LIKE with % and _ for patterns.
  4. ORDER BY sorts. Default is ASC. Use DESC for highest first.
  5. DISTINCT removes duplicates. AS gives an alias.
  6. GROUP BY makes groups. HAVING filters groups. WHERE filters rows.
  7. INSERT adds, UPDATE edits, DELETE removes. Always use WHERE with UPDATE and DELETE.
  8. Aggregates: COUNT, SUM, AVG, MIN, MAX. They skip NULL values.

Practice questions

Question 1 · MCQ (Interview / semester)

Which clause sorts the result?

Question 2 · MCQ (Interview / semester)

Which clause can filter using an aggregate like COUNT(*)?

Question 3 · MCQ (Interview / semester)

Which query finds names starting with A?

Question 4 · MCQ (Interview / semester)

What happens if we run DELETE FROM student; without WHERE?

Question 5 · MCQ (Interview / semester)

Which function returns the largest value?

Question 6 · MCQ (Interview / semester)

Which keyword removes duplicate rows from the result?