SQL Queries: SELECT, WHERE, JOIN and GROUP BY with Solved Examples
Computer papers for lecturer, programmer, data-entry and bank IT posts no longer stop at asking what SQL stands for. They print a small table, give a query and ask how many rows come back, which name appears first or what an aggregate returns. This lesson shows how to read a query clause by clause and work out its result by hand, using the same small tables throughout. Every result here was checked by running the query.
Asked in: PPSC, FPSC, NTS, ETEA, KPPSC, SSC, IBPS and ICS/ECAT computer
How a SELECT query is read
A query is written in the order SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, but the database works on it in a different order. It first takes the table named in FROM (joining tables if asked), then keeps only the rows that pass WHERE, then forms groups with GROUP BY, then keeps only the groups that pass HAVING, then picks the columns listed in SELECT and finally sorts the result with ORDER BY.
Follow the same order when solving a question by hand: list the rows, cross out those that fail WHERE, group what remains, and only then work out the columns and the order. SELECT followed by column names returns only those columns; an asterisk in place of the column names returns every column. SQL keywords are not case-sensitive, but text values inside single quotes, such as Lahore, are written exactly as stored.
- Written order: SELECT β FROM β WHERE β GROUP BY β HAVING β ORDER BY
- Working order: FROM/JOIN β WHERE β GROUP BY β HAVING β SELECT β ORDER BY
Filtering rows with WHERE
WHERE keeps only the rows for which its condition is true. Conditions use the equals sign and the other comparison operators (less than, greater than, not equal), and they can be combined with AND, OR and NOT. AND is applied before OR, just as multiplication comes before addition, so A OR B AND C means A OR (B AND C). Use brackets whenever the meaning must be different.
BETWEEN 60 AND 80 is inclusive: it keeps 60, 80 and everything in between. IN (10, 20) keeps rows whose value matches any item in the list, and NOT IN keeps the rest. LIKE matches text patterns: the percent sign stands for any number of characters (including none) and the underscore stands for exactly one character. So LIKE 'A%' means starts with A, LIKE '%a' means ends with a, and LIKE '_a%' means the second letter is a. To test for a missing value write IS NULL; the condition = NULL is never true.
- BETWEEN x AND y includes both x and y
- % = any number of characters; _ = exactly one character
- AND is evaluated before OR
Sorting with ORDER BY and removing repeats with DISTINCT
ORDER BY sorts the final result. Ascending order (ASC) is the default, so ORDER BY Marks lists the smallest marks first; add DESC for largest first. With two columns, as in ORDER BY City, Marks DESC, rows are sorted by City first and the second column only breaks ties within the same city. Text is sorted alphabetically.
SELECT DISTINCT City returns each different city only once. Without ORDER BY, the order of rows in a result is not guaranteed by the SQL standard, so exam questions that ask which row comes first always include an ORDER BY.
- ORDER BY column (ASC by default) or ORDER BY column DESC
Aggregate functions
An aggregate function turns many rows into a single value: COUNT counts, SUM adds, AVG gives the mean, MIN gives the smallest and MAX the largest value. Without GROUP BY, an aggregate works on all the rows that passed WHERE and returns exactly one row.
Aggregates applied to a column ignore NULL values. If four fees are 400, NULL, 600 and 500, then SUM gives 1500, COUNT(Amount) gives 3 and AVG gives 1500 Γ· 3 = 500, not 1500 Γ· 4. COUNT with an asterisk counts every row, NULL or not, so it would give 4. COUNT(DISTINCT column) counts the different non-null values.
- AVG(column) = SUM(column) Γ· COUNT(column), NULLs left out
- COUNT(column) skips NULLs; COUNT with an asterisk counts all rows
GROUP BY and HAVING
GROUP BY City collects the rows into one group for each different city and returns one row per group. Every column in the SELECT list must either be named in GROUP BY or be inside an aggregate; the aggregate is then worked out separately for each group. The number of rows returned equals the number of different values (or combinations of values) in the GROUP BY columns.
WHERE filters rows before the groups are made and cannot contain an aggregate. HAVING filters whole groups after they are made, so it is where conditions like HAVING COUNT(RollNo) BETWEEN 2 AND 10 or HAVING SUM(Qty) BETWEEN 5 AND 50 belong. A query can use both: WHERE first removes rows, then HAVING removes groups.
- Rows returned by GROUP BY = number of distinct group values
- WHERE β rows (before grouping); HAVING β groups (after grouping)
Joins
A join combines rows of two tables using a matching column, usually a foreign key and the primary key it refers to. An INNER JOIN returns only the pairs of rows that match; a row with no partner in the other table disappears. A LEFT (OUTER) JOIN returns every row of the left table; where there is no match, the columns of the right table are filled with NULL. A RIGHT JOIN does the same for the right table, and a FULL OUTER JOIN keeps unmatched rows from both sides.
A CROSS JOIN pairs every row of one table with every row of the other, so tables of m and n rows give m Γ n rows (the Cartesian product). A self join joins a table to itself, for example to pair each employee with his or her manager from the same Employees table. When both tables have a column with the same name, prefix it with the table name or an alias, as in s.DeptID and d.DeptID.
- CROSS JOIN rows = m Γ n
- LEFT JOIN rows = matched pairs + unmatched rows of the left table
Solved examples
- Table Students (RollNo, Name, City, Marks, DeptID) has these rows: 1 Ali Lahore 72 10; 2 Priya Delhi 85 20; 3 Hamza Karachi 64 10; 4 Neha Mumbai 91 30; 5 Ayesha Lahore 58 20; 6 Ravi Delhi 77 10; 7 Sana Islamabad 69 50. What does SELECT Name FROM Students WHERE City = 'Lahore' return?
- Check the City of each row; only rows with exactly Lahore pass.
- Roll numbers 1 (Ali) and 5 (Ayesha) are from Lahore.
Answer: Two rows: Ali and Ayesha - Using the same Students table, find the result of SELECT Name, Marks FROM Students WHERE Marks BETWEEN 64 AND 77 ORDER BY Marks DESC.
- BETWEEN is inclusive, so marks of 64 and 77 both pass.
- Passing rows: Ali 72, Hamza 64, Ravi 77, Sana 69. Priya 85, Neha 91 and Ayesha 58 fail.
- Sort by Marks, largest first: Ravi 77, Ali 72, Sana 69, Hamza 64.
Answer: Ravi 77, Ali 72, Sana 69, Hamza 64 - Using the Students table, which names are returned by WHERE Name LIKE 'A%' and which by WHERE Name LIKE '_a%'?
- A% means the name starts with A: Ali and Ayesha.
- _a% means exactly one character, then a, then anything: the second letter must be a.
- Hamza (H-a), Ravi (R-a) and Sana (S-a) have a as the second letter; Ayesha has y and Priya has r, so they fail.
Answer: A%: Ali, Ayesha; _a%: Hamza, Ravi, Sana - Using the Students table, find the output of SELECT City, COUNT(RollNo), AVG(Marks) FROM Students GROUP BY City ORDER BY City.
- Different cities: Delhi, Islamabad, Karachi, Lahore, Mumbai, so the result has 5 rows.
- Delhi: Priya 85 and Ravi 77, count 2, average 162 Γ· 2 = 81.
- Lahore: Ali 72 and Ayesha 58, count 2, average 130 Γ· 2 = 65.
- Islamabad (Sana 69), Karachi (Hamza 64) and Mumbai (Neha 91) each have count 1 and that single mark as the average.
- ORDER BY City lists them alphabetically.
Answer: Delhi 2 81; Islamabad 1 69; Karachi 1 64; Lahore 2 65; Mumbai 1 91 - Table Students (RollNo, Name, City, Marks, DeptID) has these rows: 1 Ali Lahore 72 10; 2 Priya Delhi 85 20; 3 Hamza Karachi 64 10; 4 Neha Mumbai 91 30; 5 Ayesha Lahore 58 20; 6 Ravi Delhi 77 10; 7 Sana Islamabad 69 50. Table Departments (DeptID, DeptName) has these rows: 10 Computer; 20 Physics; 30 Maths; 40 English. What does SELECT s.Name FROM Students s INNER JOIN Departments d ON s.DeptID = d.DeptID WHERE d.DeptName = 'Computer' return?
- The join attaches a DeptName to each student whose DeptID exists in Departments.
- DeptName Computer belongs to DeptID 10.
- Students with DeptID 10: Ali, Hamza and Ravi.
Answer: Ali, Hamza and Ravi - Using the Students table, find the output of SELECT DeptID, COUNT(RollNo), SUM(Marks) FROM Students GROUP BY DeptID HAVING COUNT(RollNo) BETWEEN 2 AND 10.
- Groups by DeptID: 10 (Ali, Hamza, Ravi), 20 (Priya, Ayesha), 30 (Neha), 50 (Sana).
- Counts: 3, 2, 1 and 1. HAVING keeps only groups with 2 to 10 students, so DeptIDs 10 and 20 survive.
- Sum for 10: 72 + 64 + 77 = 213. Sum for 20: 85 + 58 = 143.
Answer: Two rows: 10, 3, 213 and 20, 2, 143
Exam shortcuts
- Solve in the working order: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY. Cross out failing rows before doing anything else.
- BETWEEN always includes both end values; check the boundary rows first, because that is where examiners set the trap.
- For GROUP BY questions, the number of output rows is simply the number of different values in the grouping column after WHERE.
- For an INNER JOIN, count only matching pairs; for a LEFT JOIN, add one row for every unmatched row of the left table.
- When AND and OR are mixed without brackets, put brackets around the AND part yourself before evaluating.
Common mistakes
- Treating BETWEEN as exclusive and dropping the rows equal to the end values.
- Dividing by the total number of rows in AVG when some values are NULL; NULLs are left out of both the sum and the count.
- Putting an aggregate condition in WHERE instead of HAVING.
- Assuming a student whose DeptID has no match still appears in an INNER JOIN; only a LEFT JOIN keeps such a row.
- Reading LIKE '_a%' as contains a; the underscore fixes exactly one character before the a.
Practice MCQs
- Which SQL operator is used in a WHERE clause to search for a text pattern, such as names beginning with S?
A) BETWEEN
B) IN
C) LIKE
D) MATCH
Answer: C) LIKE β LIKE compares a value against a pattern built with the wildcards % and _. BETWEEN tests a range of values, IN tests membership of a fixed list, and MATCH is not a standard SQL comparison operator. - If ORDER BY Marks is written without ASC or DESC, how are the rows sorted?
A) In ascending order of Marks
B) In descending order of Marks
C) In the order the rows were inserted
D) In random order each time
Answer: A) In ascending order of Marks β ASC is the default for ORDER BY, so the smallest marks come first. Descending order needs DESC written explicitly, and the insertion order or a random order is what you might get with no ORDER BY at all, not with it. - Table Orders (OrderID, Customer, Item, Qty, Price) has these rows: 1 Zain Pen 4 20; 2 Anjali Book 2 150; 3 Zain Book 1 150; 4 Fatima Pen 10 20; 5 Anjali Bag 1 900. Which customers are returned by SELECT Customer FROM Orders WHERE Item = 'Book'?
A) Anjali only
B) Anjali and Zain
C) Zain and Fatima
D) Anjali, Zain and Fatima
Answer: B) Anjali and Zain β Orders 2 (Anjali) and 3 (Zain) are for a Book. Fatima only bought pens, so any answer with her is wrong, and leaving out Zain ignores order 3. - Table Students (RollNo, Name, City, Marks, DeptID) has these rows: 1 Ali Lahore 72 10; 2 Priya Delhi 85 20; 3 Hamza Karachi 64 10; 4 Neha Mumbai 91 30; 5 Ayesha Lahore 58 20; 6 Ravi Delhi 77 10; 7 Sana Islamabad 69 50. What does SELECT COUNT(RollNo) FROM Students WHERE City IN ('Delhi', 'Mumbai') return?
A) 2
B) 1
C) 5
D) 3
Answer: D) 3 β IN keeps rows whose City is Delhi or Mumbai: Priya and Ravi from Delhi and Neha from Mumbai, so the count is 3. 2 counts Delhi alone, 1 counts Mumbai alone, and 5 counts the rows that are not from these cities. - Table Students (RollNo, Name, City, Marks, DeptID) has these rows: 1 Ali Lahore 72 10; 2 Priya Delhi 85 20; 3 Hamza Karachi 64 10; 4 Neha Mumbai 91 30; 5 Ayesha Lahore 58 20; 6 Ravi Delhi 77 10; 7 Sana Islamabad 69 50. What does SELECT MAX(Marks) FROM Students WHERE DeptID = 10 return?
A) 91
B) 77
C) 72
D) 213
Answer: B) 77 β DeptID 10 has Ali 72, Hamza 64 and Ravi 77, and the largest of these is 77. 91 is the highest mark in the whole table (Neha, DeptID 30), which WHERE has removed; 72 is not the maximum, and 213 is the sum for the department. - Table Students (RollNo, Name, City, Marks, DeptID) has these rows: 1 Ali Lahore 72 10; 2 Priya Delhi 85 20; 3 Hamza Karachi 64 10; 4 Neha Mumbai 91 30; 5 Ayesha Lahore 58 20; 6 Ravi Delhi 77 10; 7 Sana Islamabad 69 50. How many rows does SELECT Name FROM Students WHERE Name LIKE '%a' return?
A) 5
B) 3
C) 4
D) 7
Answer: A) 5 β The pattern %a means the name ends with a: Priya, Hamza, Neha, Ayesha and Sana, which is 5 rows. Ali and Ravi end in other letters, so 7 is too many, and 3 or 4 miss some of the matching names. - Table Students (RollNo, Name, City, Marks, DeptID) has these rows: 1 Ali Lahore 72 10; 2 Priya Delhi 85 20; 3 Hamza Karachi 64 10; 4 Neha Mumbai 91 30; 5 Ayesha Lahore 58 20; 6 Ravi Delhi 77 10; 7 Sana Islamabad 69 50. How many rows does SELECT Name FROM Students WHERE Marks BETWEEN 58 AND 72 return?
A) 2
B) 3
C) 4
D) 5
Answer: C) 4 β BETWEEN includes both ends, so Ayesha 58 and Ali 72 count along with Hamza 64 and Sana 69, giving 4. Leaving out both end values gives 2 and leaving out one gives 3; no fifth student has marks in this range. - Table Students (RollNo, Name, City, Marks, DeptID) has these rows: 1 Ali Lahore 72 10; 2 Priya Delhi 85 20; 3 Hamza Karachi 64 10; 4 Neha Mumbai 91 30; 5 Ayesha Lahore 58 20; 6 Ravi Delhi 77 10; 7 Sana Islamabad 69 50. The query SELECT Name FROM Students ORDER BY Marks DESC is run. Which name is in the third row of the result?
A) Ali
B) Priya
C) Sana
D) Ravi
Answer: D) Ravi β Sorted from the highest marks: Neha 91, Priya 85, Ravi 77, Ali 72 and so on, so Ravi is third. Priya is second, Ali is fourth, and Sana with 69 is fifth. - Table Orders (OrderID, Customer, Item, Qty, Price) has these rows: 1 Zain Pen 4 20; 2 Anjali Book 2 150; 3 Zain Book 1 150; 4 Fatima Pen 10 20; 5 Anjali Bag 1 900. What does SELECT Item, SUM(Qty) FROM Orders GROUP BY Item HAVING SUM(Qty) BETWEEN 2 AND 100 return?
A) Book 3 and Pen 14
B) Pen 14 only
C) Book 2 and Pen 10
D) Book 3, Pen 14 and Bag 1
Answer: A) Book 3 and Pen 14 β Grouping by Item gives Pen 4 + 10 = 14, Book 2 + 1 = 3 and Bag 1. HAVING keeps groups whose total is from 2 to 100, so Book and Pen stay and Bag (1) is removed. Pen alone forgets Book, the figures 2 and 10 are single orders rather than group totals, and Bag fails the HAVING condition. - Table Students (RollNo, Name, City, Marks, DeptID) has these rows: 1 Ali Lahore 72 10; 2 Priya Delhi 85 20; 3 Hamza Karachi 64 10; 4 Neha Mumbai 91 30; 5 Ayesha Lahore 58 20; 6 Ravi Delhi 77 10; 7 Sana Islamabad 69 50. Which names does SELECT Name FROM Students WHERE DeptID NOT IN (10, 20) return?
A) Neha only
B) Neha and Sana
C) Priya and Ayesha
D) Ali, Hamza and Ravi
Answer: B) Neha and Sana β NOT IN keeps rows whose DeptID is neither 10 nor 20: Neha (30) and Sana (50). Sana must be included because the list does not mention 50. Priya and Ayesha are in DeptID 20, and Ali, Hamza and Ravi are in DeptID 10, so those are exactly the rows removed. - Table Students (RollNo, Name, City, Marks, DeptID) has these rows: 1 Ali Lahore 72 10; 2 Priya Delhi 85 20; 3 Hamza Karachi 64 10; 4 Neha Mumbai 91 30; 5 Ayesha Lahore 58 20; 6 Ravi Delhi 77 10; 7 Sana Islamabad 69 50. Table Departments (DeptID, DeptName) has these rows: 10 Computer; 20 Physics; 30 Maths; 40 English. How many rows does SELECT s.Name, d.DeptName FROM Students s INNER JOIN Departments d ON s.DeptID = d.DeptID return?
A) 7
B) 4
C) 28
D) 6
Answer: D) 6 β An INNER JOIN keeps only matching pairs. Six students have a DeptID found in Departments; Sana (DeptID 50) has no match and is dropped, and English has no students. 7 would be a LEFT JOIN from Students, 4 is the number of departments, and 28 = 7 Γ 4 is a CROSS JOIN. - Table Students (RollNo, Name, City, Marks, DeptID) has these rows: 1 Ali Lahore 72 10; 2 Priya Delhi 85 20; 3 Hamza Karachi 64 10; 4 Neha Mumbai 91 30; 5 Ayesha Lahore 58 20; 6 Ravi Delhi 77 10; 7 Sana Islamabad 69 50. Table Departments (DeptID, DeptName) has these rows: 10 Computer; 20 Physics; 30 Maths; 40 English. How many rows does SELECT d.DeptName, s.Name FROM Departments d LEFT JOIN Students s ON d.DeptID = s.DeptID return?
A) 6
B) 4
C) 7
D) 8
Answer: C) 7 β All 4 departments are kept. Computer matches 3 students, Physics 2 and Maths 1, giving 6 rows, and English has no student so it appears once with a NULL name: 7 rows. 6 forgets the unmatched department, 4 counts departments only, and 8 wrongly adds a row for Sana, but a student without a matching department is not kept when Departments is the left table. - Table Fees (Name, Amount) has the rows: Bilal 400; Kavya NULL; Usman 600; Meera 500. What does SELECT AVG(Amount) FROM Fees return?
A) 500
B) 375
C) 1500
D) NULL
Answer: A) 500 β AVG ignores NULL, so it divides the sum 400 + 600 + 500 = 1500 by the 3 non-null values, giving 500. 375 wrongly divides by 4, 1500 is the SUM, and the result is NULL only when every value is NULL. - Table Students (RollNo, Name, City, Marks, DeptID) has these rows: 1 Ali Lahore 72 10; 2 Priya Delhi 85 20; 3 Hamza Karachi 64 10; 4 Neha Mumbai 91 30; 5 Ayesha Lahore 58 20; 6 Ravi Delhi 77 10; 7 Sana Islamabad 69 50. What does SELECT Name FROM Students WHERE City = 'Delhi' OR City = 'Lahore' AND Marks BETWEEN 70 AND 100 return?
A) Priya and Ravi only
B) Ali, Priya and Ravi
C) Ali, Ayesha, Priya and Ravi
D) Ali only
Answer: B) Ali, Priya and Ravi β AND is evaluated before OR, so the condition means City is Delhi, OR (City is Lahore AND Marks from 70 to 100). Both Delhi students (Priya, Ravi) pass, and from Lahore only Ali (72) passes, while Ayesha (58) fails. Leaving out Ali ignores the Lahore part, and including Ayesha ignores the marks condition. - Table Students (RollNo, Name, City, Marks, DeptID) has these rows: 1 Ali Lahore 72 10; 2 Priya Delhi 85 20; 3 Hamza Karachi 64 10; 4 Neha Mumbai 91 30; 5 Ayesha Lahore 58 20; 6 Ravi Delhi 77 10; 7 Sana Islamabad 69 50. Table Departments (DeptID, DeptName) has these rows: 10 Computer; 20 Physics; 30 Maths; 40 English. Query: SELECT d.DeptName, AVG(s.Marks) FROM Students s INNER JOIN Departments d ON s.DeptID = d.DeptID GROUP BY d.DeptName ORDER BY AVG(s.Marks) DESC. What is the second row of the result?
A) Computer, 71
B) Maths, 91
C) Physics, 71.5
D) Physics, 143
Answer: C) Physics, 71.5 β Averages: Maths 91 (Neha), Physics (85 + 58) Γ· 2 = 71.5 and Computer (72 + 64 + 77) Γ· 3 = 71. In descending order Maths is first and Physics second. Computer is third, and 143 is the Physics sum, not its average.
Questions
What is the difference between WHERE and HAVING?
WHERE filters individual rows before any grouping and cannot use aggregate functions. HAVING filters the groups produced by GROUP BY and is where conditions on COUNT, SUM or AVG belong.
Does SQL count NULL values?
Aggregates on a column, such as COUNT(Amount), SUM and AVG, skip NULLs. Only COUNT written with an asterisk counts every row regardless of NULLs.
How do I count rows in a join question quickly?
For an INNER JOIN, add up the matches for each row. For a LEFT JOIN, take that total and add one for each left-table row with no match. For a CROSS JOIN, multiply the row counts of the two tables.
Is SQL case-sensitive?
Keywords such as SELECT and WHERE are not case-sensitive. Whether text comparisons inside quotes are case-sensitive depends on the database settings, so exam questions use values exactly as stored.