Informatics Practices I: SQL Functions, Grouping and Operations on Relations
2. Aggregate Functions, GROUP BY, HAVING and ORDER BY
An aggregate function works on a set of rows and returns one value: MAX, MIN, AVG, SUM and COUNT. Except for COUNT(*), they ignore NULL. On EMP, COUNT(*) is 6 (every row), COUNT(salary) is 5 (Imran's NULL is skipped), SUM(salary) is 215000, AVG(salary) is 215000 ÷ 5 = 43000 (not ÷ 6), MAX(salary) is 60000 and MIN(salary) is 30000.
GROUP BY divides the rows into groups with the same value and applies the aggregate to each group: SELECT dept, AVG(salary) FROM emp GROUP BY dept gives HR 35000, IT 55000 and Sales 35000. WHERE filters rows before grouping; HAVING filters groups after aggregation, so a condition on an aggregate belongs in HAVING: SELECT dept FROM emp GROUP BY dept HAVING AVG(salary) > 40000 returns only IT. ORDER BY sorts the result, ascending by default and descending with DESC: ORDER BY salary DESC LIMIT 2 gives Divya and Karan.
- FROM
- WHEREFilters rows before grouping
- GROUP BY
- HAVINGFilters groups after aggregation
- SELECT
- ORDER BYAscending by default; DESC for descending
- Takes the value of one row
- Returns one value per row
- POWER, MID, UPPER, MONTHNAME
- Works on a set of rows
- Returns one value for the set
- MAX, MIN, AVG, SUM, COUNT
An aggregate function works on a set of rows and returns one value: MAX, MIN, AVG, SUM and COUNT. Except for COUNT(), they ignore NULL. On EMP, COUNT() is 6 (every row), COUNT(salary) is 5…
3. Operations on Relations: Union, Intersection, Minus, Cartesian Product and JOIN
The set operations need two relations with the same number of columns and compatible types. Let A hold 1, 2, 3, 3 and B hold 2, 3, 4. UNION gives 1, 2, 3, 4 (duplicates removed; UNION ALL keeps all 7 rows), INTERSECT gives 2, 3 (rows in both) and MINUS (EXCEPT in some systems) gives 1 (rows of A not in B). Note that A MINUS B and B MINUS A are different.
The Cartesian product pairs every row of one table with every row of the other, so the result has m × n rows and the columns of both: EMP × DEPT has 6 × 3 = 18 rows, most of them meaningless. A JOIN keeps only the matching pairs: SELECT name, city FROM emp JOIN dept ON emp.dept = dept.dept gives six rows, one per employee, and for empno 4 it returns (Karan, Noida). Writing FROM emp, dept WHERE emp.dept = dept.dept does the same. A natural join matches on all columns with the same name and shows the common column once. The usual error is to forget the join condition and get the whole Cartesian product.
| Operation | Result | Rows for A (4 rows, with a repeated 3) and B (3 rows) |
|---|---|---|
| UNION | All distinct rows of both | 4 (1, 2, 3, 4) |
| UNION ALL | All rows including duplicates | 7 |
| INTERSECT | Rows common to both | 2 (2, 3) |
| MINUS | Rows in A but not in B | 1 (1) |
| Cartesian product | Every pairing | 4 × 3 = 12 |
The set operations need two relations with the same number of columns and compatible types. Let A hold 1, 2, 3, 3 and B hold 2, 3, 4. UNION gives 1, 2, 3, 4 (duplicates removed; UNION ALL…
4. Worked Queries on a Small Table
Take a table STAFF(Id, Name, Dept, Salary) with six rows: Asha (Sales, 30000), Ravi (Sales, 40000), Meena (HR, 35000), Karan (IT, 50000), Sita (IT, 60000) and Om (IT, 55000), and a table DEPT(Code, City) with Sales in Patna, HR in Gaya and IT in Delhi. The query SELECT Dept, COUNT(*), AVG(Salary) FROM Staff GROUP BY Dept returns HR 1 35000, IT 3 55000 and Sales 2 35000. Adding HAVING COUNT(*) >= 2 and selecting MAX(Salary) leaves IT with 60000 and Sales with 40000, because HR has only one row and HAVING filters the groups after they are formed. A condition on a single row, such as WHERE Dept = 'IT', filters before grouping: it gives a count of 3, a sum of 165000, a minimum of 50000 and a maximum of 60000.
A join matches rows of two tables on a condition. SELECT Name, City FROM Staff, Dept WHERE Staff.Dept = Dept.Code AND City = 'Delhi' returns Karan, Sita and Om, the three IT staff. Without the matching condition the same two tables give the Cartesian product, which has 6 × 3 = 18 rows and 4 + 2 = 6 columns, most of them meaningless pairings. This is why every join query needs the equality condition on the common column.
Take a table STAFF(Id, Name, Dept, Salary) with six rows: Asha (Sales, 30000), Ravi (Sales, 40000), Meena (HR, 35000), Karan (IT, 50000), Sita (IT, 60000) and Om (IT, 55000), and a table…
Key takeaways
- POWER, MOD and ROUND are math functions; MID, LEFT, RIGHT, INSTR, LENGTH and TRIM work on text; positions in SQL start at 1.
- YEAR, MONTH, DAY, MONTHNAME and DAYNAME give parts of a date; NOW() gives the current date and time and DATE() its date part.
- MAX, MIN, AVG, SUM and COUNT(column) ignore NULL, while COUNT(*) counts every row; AVG divides by the number of non-NULL values.
- WHERE filters rows before grouping and HAVING filters groups after aggregation; ORDER BY sorts, ascending by default.
- UNION removes duplicates, INTERSECT keeps common rows, MINUS keeps rows of the first not in the second; Cartesian product gives m × n rows and JOIN with ON keeps only matches.
Practice questions (26)
Attempt each one before opening the answer. Every explanation names the tempting wrong option as well as the right one, because that is where marks are lost.
In MySQL, what does MOD(17, 5) return?
Show answer
Answer: B — 2
MOD gives the remainder of 17 divided by 5: 17 = 3 × 5 + 2. The quotient is 3, and 3.4 is the true division.What is the result of SELECT MID('computer', 2, 3)?
Show answer
Answer: A — omp
Three characters are taken from position 2, counting from 1: o, m, p. The answer mpu would come from Python slicing, which starts at 0.What does INSTR('computer', 'put') return?
Show answer
Answer: D — 4
The substring 'put' begins at the 4th letter (c-o-m-p), so the position is 4. A result of 0 would mean the substring is absent.
Show the other 23 questions
Which function returns the number of characters in a string?
Show answer
Answer: C — LENGTH()
LENGTH('database') is 8. INSTR finds a position, MID extracts part of the string and ROUND is a math function.On EMP (six rows, one salary NULL), what do COUNT(*) and COUNT(salary) return?
Show answer
Answer: B — 6 and 5
COUNT(*) counts rows, including the one with NULL, but COUNT(salary) counts only the non-NULL values.On EMP, AVG(salary) is 43000 because
Show answer
Answer: A — the NULL is ignored and the sum 215000 is divided by 5
If the NULL were treated as 0 the average would be 215000 ÷ 6 = 35833.33. SQL aggregate functions skip NULLs.Which clause is used to filter groups after aggregation?
Show answer
Answer: D — HAVING
WHERE cannot use an aggregate such as AVG(salary); HAVING can. On EMP, HAVING AVG(salary) > 40000 returns only IT.The query SELECT dept, SUM(salary) FROM emp WHERE salary > 30000 GROUP BY dept gives for IT the sum
Show answer
Answer: C — 110000
Karan 50000 and Divya 60000 both satisfy the WHERE condition, so IT sums to 110000. The average, 55000, is a different aggregate.If A holds 1, 2, 3, 3 and B holds 2, 3, 4, then A UNION B has how many rows?
Show answer
Answer: B — 4
UNION removes duplicates and leaves 1, 2, 3, 4. UNION ALL would keep all 7 rows, and 12 is the Cartesian product 4 × 3.The Cartesian product of a table of 6 rows and a table of 3 rows has
Show answer
Answer: A — 18 rows
Each of the 6 rows pairs with each of the 3, giving 6 × 3 = 18 rows. A JOIN with a matching condition would reduce this to the matched rows only.What does SELECT LEFT('computer', 3); return in MySQL?
Show answer
Answer: A — com
LEFT returns the given number of characters from the left end, which is com. ter would be RIGHT('computer', 3) and mpu comes from the middle.What does SELECT ROUND(18.567, 2); return?
Show answer
Answer: B — 18.57
Rounding to two decimal places gives 18.57. 18.56 truncates instead of rounding and 19 rounds to a whole number.What does SELECT LENGTH('Python'); return?
Show answer
Answer: B — 6
The string Python has 6 characters. 5 and 7 are off by one.Which MySQL function returns the current date and time?
Show answer
Answer: A — NOW()
NOW() gives the current date and time together. MONTH() and DAYNAME() extract a part of a given date.What does SELECT MID('database', 5, 3); return in MySQL (MID is the same as SUBSTR)?
Show answer
Answer: B — bas
Starting at position 5 and taking 3 characters gives bas. "dat" starts at position 1 and "ata" at position 2.What does SELECT INSTR('informatics', 'mat'); return?
Show answer
Answer: B — 6
The substring mat begins at the 6th character of informatics, so the value is 6. 5 and 7 are off by one.Which SQL function ignores NULL values when computing a result?
Show answer
Answer: A — SUM() and AVG() on a column
Aggregates on a column skip NULLs, whereas COUNT(*) counts all rows including those with NULLs.Assertion (A): GROUP BY is used with aggregate functions.
Reason (R): It divides the rows into groups so that an aggregate such as SUM or COUNT can be computed for each group.
Choose the correct option:Show answer
Answer: A — Both A and R are true and R is the correct explanation of A
Each group gets its own aggregate value, which R states. Option 2 is wrong.Consider the following statements:
A. COUNT(*) counts all rows including those with NULL values.
B. COUNT(column) does not count NULL values.
C. SUM() ignores NULL values.
D. AVG() treats NULL as zero.
Choose the correct answer:Show answer
Answer: A — A, B and C only
A, B and C are correct. D is false because AVG skips NULLs rather than counting them as zero, so option 4 is the trap.Which type of join returns only the rows that have matching values in both tables?
Show answer
Answer: A — Inner join (equi-join)
An inner join keeps only matched rows. The Cartesian (cross) product pairs every row with every other row.Table A holds the values 1, 2, 3, 3 and table B holds 2, 3, 4. How many rows does A UNION ALL B contain?
Show answer
Answer: A — 7
UNION ALL keeps every row including duplicates, 4 + 3 = 7. UNION would remove the duplicates and give fewer rows.Table EMP(Name, Dept, Sal): (Asha, HR, 30000), (Ravi, IT, 50000), (Mona, IT, 40000), (Kabir, HR, 20000), (Zoya, IT, 60000).
A self-join counts pairs of employees working in the same department, each pair counted once. SELECT COUNT(*) FROM EMP E1, EMP E2 WHERE E1.Dept = E2.Dept AND E1.Name < E2.Name; returns:Show answer
Answer: B — 4
HR gives 1 pair and IT with three employees gives 3 pairs, so the count is 4. 10 is the number of pairs among all five employees regardless of department.Table EMP(Name, Dept, Sal): (Asha, HR, 30000), (Ravi, IT, 50000), (Mona, IT, 40000), (Kabir, HR, 20000), (Zoya, IT, 60000).
What does SELECT SUM(Sal) FROM EMP WHERE Name LIKE '%i'; return?Show answer
Answer: B — 50000
Only the name Ravi ends with the letter i, so the sum is 50000. 200000 would be the total of all rows.Table EMP(Name, Dept, Sal): (Asha, HR, 30000), (Ravi, IT, 50000), (Mona, IT, 40000), (Kabir, HR, 20000), (Zoya, IT, 60000).
How many departments does SELECT Dept FROM EMP GROUP BY Dept HAVING COUNT(*) > 2; list?Show answer
Answer: B — 1
Only IT has more than two employees, so one department is listed: 1. 2 counts HR as well, which has only two employees.Assertion (A): COUNT(*) and COUNT(salary) can return different values on the same table.
Reason (R): COUNT(salary) skips rows in which salary is NULL, whereas COUNT(*) counts every row.
Choose the correct option:Show answer
Answer: A — Both A and R are true and R is the correct explanation of A
Skipping NULLs explains the difference, as R states. Option 2 is wrong.The query SELECT Dept, SUM(Sal) FROM EMP GROUP BY Dept; on the EMP table (HR: 30000, 20000; IT: 50000, 40000, 60000) shows:
Show answer
Answer: A — HR 50000 and IT 150000
Each department's salaries are added: 30000 + 20000 = 50000 and 50000 + 40000 + 60000 = 150000. 200000 is the sum of everything.