Informatics Practices I: SQL Functions, Grouping and Operations on Relations

Section B2 of the NTA paper, Informatics Practices, is an alternative to Section B1, Computer Science, and its first unit is database querying with SQL beyond the basics: the math, text, date and aggregate functions, GROUP BY with HAVING, ORDER BY, and the operations on relations (union, intersection, minus, Cartesian product and JOIN). Every result in this chapter was produced by running the query on the small tables shown, so you can trace each answer.
Overview

1. The Tables Used and the Single-Row Functions

1 min read · 2 parts

All the examples use EMP(empno, name, dept, salary) with six rows: (1, Asha, Sales, 30000), (2, Ravi, Sales, 40000), (3, Meena, HR, 35000), (4, Karan, IT, 50000), (5, Divya, IT, 60000) and (6, Imran, HR, NULL), and DEPT(dept, city) with (Sales, Delhi), (HR, Pune) and (IT, Noida). A single-row function takes the value of one row and returns one value for it.

Math, text and date functions (MySQL)
FunctionWhat it doesExample and result
POWER(x, y)x raised to the power yPOWER(2, 5) = 32
MOD(x, y)Remainder of x ÷ yMOD(17, 5) = 2
ROUND(x, d)Rounds to d decimals; a negative d rounds to tens, hundredsROUND(3.14159, 2) = 3.14; ROUND(1257.6, -1) = 1260
UCASE / UPPER, LCASE / LOWERCase conversionUPPER('Delhi') = DELHI
MID / SUBSTRING / SUBSTR (s, start, n)n characters from position start (counting from 1)MID('computer', 2, 3) = omp
LEFT(s, n), RIGHT(s, n)First or last n charactersLEFT('computer', 3) = com; RIGHT('computer', 3) = ter
LENGTH(s)Number of characters (bytes)LENGTH('database') = 8
INSTR(s, t)Position of the first occurrence of t in s, 0 if absentINSTR('computer', 'put') = 4
LTRIM, RTRIM, TRIMRemoves spaces from the left, right or both endsTRIM(' sql ') = sql
NOW(), DATE()Current date and time; the date part onlyDATE(NOW()) gives today's date
YEAR, MONTH, DAY, MONTHNAME, DAYNAMEParts of a dateMONTHNAME('2024-03-15') = March; DAYNAME('2024-01-01') = Monday
⚠️ Positions start at 1
SQL counts string positions from 1, not 0 as Python does: MID('computer', 2, 3) starts at the second letter and gives omp, while Python's 'computer'[2:5] gives mpu.

All the examples use EMP(empno, name, dept, salary) with six rows: (1, Asha, Sales, 30000), (2, Ravi, Sales, 40000), (3, Meena, HR, 35000), (4, Karan, IT, 50000), (5, Divya, IT, 60000) and…

2. Aggregate Functions, GROUP BY, HAVING and ORDER BY

1 min read · 4 parts

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.

🧠 WHERE before, HAVING after
Remember the order of evaluation: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY. WHERE salary > 30000 removes Asha before the groups are formed, so SUM by dept becomes HR 35000, IT 110000, Sales 40000.
Order of evaluation of a query
  1. FROM
  2. WHEREFilters rows before grouping
  3. GROUP BY
  4. HAVINGFilters groups after aggregation
  5. SELECT
  6. ORDER BYAscending by default; DESC for descending
A condition on an aggregate belongs in HAVING.
Single-row versus aggregate functions
Single-row function
  • Takes the value of one row
  • Returns one value per row
  • POWER, MID, UPPER, MONTHNAME
Aggregate function
  • Works on a set of rows
  • Returns one value for the set
  • MAX, MIN, AVG, SUM, COUNT
Except COUNT(*), aggregates ignore NULL: AVG(salary) = 215000 ÷ 5.

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

1 min read · 1 part

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.

Relational operations compared
OperationResultRows for A (4 rows, with a repeated 3) and B (3 rows)
UNIONAll distinct rows of both4 (1, 2, 3, 4)
UNION ALLAll rows including duplicates7
INTERSECTRows common to both2 (2, 3)
MINUSRows in A but not in B1 (1)
Cartesian productEvery pairing4 × 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

1 min read · 1 part

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.

⚠️ WHERE filters rows, HAVING filters groups
A condition that uses an aggregate such as COUNT() or SUM can only go in HAVING, because WHERE runs before any groups exist. Writing WHERE COUNT() >= 2 is an error. The reverse also holds: a condition on a single column of a row belongs in WHERE for efficiency, since HAVING would filter only after the work of grouping was done.

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.

  1. In MySQL, what does MOD(17, 5) return?

    1. 3
    2. 2
    3. 3.4
    4. 85
    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.
  2. What is the result of SELECT MID('computer', 2, 3)?

    1. omp
    2. com
    3. mpu
    4. ute
    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.
  3. What does INSTR('computer', 'put') return?

    1. 3
    2. 5
    3. 0
    4. 4
    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
  1. Which function returns the number of characters in a string?

    1. INSTR()
    2. MID()
    3. LENGTH()
    4. ROUND()
    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.
  2. On EMP (six rows, one salary NULL), what do COUNT(*) and COUNT(salary) return?

    1. 5 and 5
    2. 6 and 5
    3. 6 and 6
    4. 5 and 6
    Show answer

    Answer: B — 6 and 5

    COUNT(*) counts rows, including the one with NULL, but COUNT(salary) counts only the non-NULL values.
  3. On EMP, AVG(salary) is 43000 because

    1. the NULL is ignored and the sum 215000 is divided by 5
    2. the sum is divided by 6
    3. NULL counts as zero
    4. the maximum is halved
    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.
  4. Which clause is used to filter groups after aggregation?

    1. WHERE
    2. ORDER BY
    3. DISTINCT
    4. HAVING
    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.
  5. The query SELECT dept, SUM(salary) FROM emp WHERE salary > 30000 GROUP BY dept gives for IT the sum

    1. 55000
    2. 215000
    3. 110000
    4. 60000
    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.
  6. If A holds 1, 2, 3, 3 and B holds 2, 3, 4, then A UNION B has how many rows?

    1. 7
    2. 4
    3. 2
    4. 12
    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.
  7. The Cartesian product of a table of 6 rows and a table of 3 rows has

    1. 18 rows
    2. 9 rows
    3. 6 rows
    4. 3 rows
    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.
  8. What does SELECT LEFT('computer', 3); return in MySQL?

    1. com
    2. ter
    3. mpu
    4. comp
    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.
  9. What does SELECT ROUND(18.567, 2); return?

    1. 18.56
    2. 18.57
    3. 18.6
    4. 19
    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.
  10. What does SELECT LENGTH('Python'); return?

    1. 5
    2. 6
    3. 7
    4. Python
    Show answer

    Answer: B — 6

    The string Python has 6 characters. 5 and 7 are off by one.
  11. Which MySQL function returns the current date and time?

    1. NOW()
    2. DATE()
    3. MONTH()
    4. DAYNAME()
    Show answer

    Answer: A — NOW()

    NOW() gives the current date and time together. MONTH() and DAYNAME() extract a part of a given date.
  12. What does SELECT MID('database', 5, 3); return in MySQL (MID is the same as SUBSTR)?

    1. dat
    2. bas
    3. ata
    4. ase
    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.
  13. What does SELECT INSTR('informatics', 'mat'); return?

    1. 5
    2. 6
    3. 7
    4. 4
    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.
  14. Which SQL function ignores NULL values when computing a result?

    1. SUM() and AVG() on a column
    2. COUNT(*)
    3. NOW()
    4. LENGTH()
    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.
  15. 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:

    1. Both A and R are true and R is the correct explanation of A
    2. Both A and R are true but R is not the correct explanation of A
    3. A is true but R is false
    4. A is false but R is true
    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.
  16. 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:

    1. A, B and C only
    2. A and D only
    3. B, C and D only
    4. A, B, C and D
    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.
  17. Which type of join returns only the rows that have matching values in both tables?

    1. Inner join (equi-join)
    2. Cartesian product
    3. Left outer join
    4. Cross join
    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.
  18. 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?

    1. 7
    2. 4
    3. 5
    4. 3
    Show answer

    Answer: A — 7

    UNION ALL keeps every row including duplicates, 4 + 3 = 7. UNION would remove the duplicates and give fewer rows.
  19. 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:

    1. 3
    2. 4
    3. 5
    4. 10
    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.
  20. 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?

    1. 200000
    2. 50000
    3. 30000
    4. 110000
    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.
  21. 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?

    1. 0
    2. 1
    3. 2
    4. 3
    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.
  22. 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:

    1. Both A and R are true and R is the correct explanation of A
    2. Both A and R are true but R is not the correct explanation of A
    3. A is true but R is false
    4. A is false but R is true
    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.
  23. The query SELECT Dept, SUM(Sal) FROM EMP GROUP BY Dept; on the EMP table (HR: 30000, 20000; IT: 50000, 40000, 60000) shows:

    1. HR 50000 and IT 150000
    2. HR 30000 and IT 60000
    3. HR 200000 and IT 200000
    4. HR 50000 and IT 50000
    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.