ποΈ SQL Β· Topic 5 of 20
Operators, NULL & Patterns β SQL Questions with Answers
30 practice questions on Operators, NULL & Patterns, each with the correct answer and a clear explanation of why it is right. Read through them as revision notes, or take this topic as an interactive quiz to test yourself.
0 easy Β· 16 medium Β· 14 hard Β· Part of SQL: Databases from basics to window functions - 20 topics.
Medium questions (16)
Q1. medium
What does NULL represent in SQL?
- A An UNKNOWN or missing value - not zero, not an empty string, not false
- B The number zero
- C An empty string
- D A deleted row
Answer: A β An UNKNOWN or missing value - not zero, not an empty string, not false
NULL means 'we do not know'. That is why arithmetic and comparisons involving NULL produce NULL rather than a definite answer.
NULLMissing data
Q3. medium
What does COALESCE(a, b, c) return?
- A The FIRST non-NULL value among its arguments
- B The sum of all values
- C Always the first argument
- D NULL if any argument is NULL
Answer: A β The FIRST non-NULL value among its arguments
COALESCE is the standard way to supply fallbacks: COALESCE(nickname, first_name, 'Guest'). It accepts any number of arguments.
COALESCEDefaults
Q4. medium
What does IFNULL(x, 0) / ISNULL(x, 0) / NVL(x, 0) do?
- A Returns 0 when x is NULL - the two-argument, dialect-specific version of COALESCE
- B Tests whether x is NULL
- C Deletes NULLs
- D Counts NULLs
Answer: A β Returns 0 when x is NULL - the two-argument, dialect-specific version of COALESCE
IFNULL is MySQL, ISNULL is SQL Server, NVL is Oracle. COALESCE works everywhere and is preferred for portable code.
COALESCEDialects
Q7. medium
What does COUNT(*) do with NULL rows?
- A Counts every row, including rows full of NULLs
- B Skips rows containing NULLs
- C Returns NULL
- D Errors
Answer: A β Counts every row, including rows full of NULLs
COUNT(*) counts rows; COUNT(column) counts non-NULL values in that column. The difference between them tells you how many values are missing.
COUNTNULL
Q9. medium
How does DISTINCT treat multiple NULLs?
- A They collapse into ONE NULL in the result
- B Each NULL is kept separately
- C NULLs are removed
- D It errors
Answer: A β They collapse into ONE NULL in the result
For grouping and DISTINCT, NULLs are treated as 'the same unknown', even though NULL = NULL is not TRUE in comparisons. GROUP BY behaves the same way.
DISTINCTGROUP BYNULL
Q10. medium
Which pattern finds emails at gmail.com?
- A WHERE email LIKE '%@gmail.com'
- B WHERE email = '%@gmail.com'
- C WHERE email LIKE '@gmail.com'
- D WHERE email CONTAINS 'gmail'
Answer: A β WHERE email LIKE '%@gmail.com'
LIKE enables wildcards; = matches literally. The % before @gmail.com allows any username.
LIKEWildcards
Q12. medium
What does ILIKE do (PostgreSQL)?
- A Case-INSENSITIVE pattern matching
- B Inverted LIKE
- C Integer LIKE
- D Index-based LIKE
Answer: A β Case-INSENSITIVE pattern matching
PostgreSQL is case-sensitive by default, so ILIKE 'a%' matches both 'Ana' and 'ana'. Portable alternative: LOWER(name) LIKE 'a%'.
ILIKECase sensitivity
Q13. medium
What does NOT LIKE do?
WHERE email NOT LIKE '%@test.com'
OR email IS NULL;
- A Matches rows that do NOT fit the pattern
- B Matches everything
- C Is invalid
- D Is the same as <>
Answer: A β Matches rows that do NOT fit the pattern
Remember rows where the column is NULL are excluded by NOT LIKE too - NULL never matches or 'not matches'.
NOT LIKENULL
Q15. medium
What does the modulo operator % (or MOD) return?
WHERE id % 2 = 0; -- even ids
- A The remainder after division - useful for finding even/odd values
- B A percentage
- C A wildcard
- D Multiplication
Answer: A β The remainder after division - useful for finding even/odd values
Note the same symbol is a wildcard inside LIKE but an arithmetic operator elsewhere. Oracle uses MOD(a, b).
ArithmeticMOD
Q17. medium
How do you convert a value's type?
SELECT CAST('42' AS INTEGER) + 8; -- 50
- A CAST(value AS INTEGER) - or the shorthand value::INTEGER in PostgreSQL
- B CONVERT_TYPE(value)
- C TYPE(value, INT)
- D Types cannot be converted
Answer: A β CAST(value AS INTEGER) - or the shorthand value::INTEGER in PostgreSQL
CAST is standard SQL. Casting matters when comparing or sorting values stored in the wrong type, e.g. numbers kept in a VARCHAR column.
CASTData types
Q20. medium
What does ANY / SOME do?
WHERE price > ANY (SELECT price FROM budget_items)
- A TRUE if the comparison holds for AT LEAST ONE value returned by the subquery
- B TRUE only if it holds for all values
- C Returns any random row
- D Is invalid
Answer: A β TRUE if the comparison holds for AT LEAST ONE value returned by the subquery
> ANY means 'greater than the minimum'. Its counterpart ALL means the comparison must hold for every value, so > ALL means 'greater than the maximum'.
ANYALLSubqueries
Q22. medium
How do you concatenate text in standard SQL?
- A first || ' ' || last (or CONCAT(first, ' ', last))
- B first + last everywhere
- C first & last
- D CONCATENATE(first, last)
Answer: A β first || ' ' || last (or CONCAT(first, ' ', last))
|| is standard (PostgreSQL, Oracle, SQLite); SQL Server uses +; CONCAT works in most modern databases and often handles NULLs more gracefully.
ConcatenationDialects
Q24. medium
What does the CASE expression evaluate to when several WHEN conditions are true?
- A The result of the FIRST matching condition - evaluation stops there
- B All matching results
- C The last match
- D An error
Answer: A β The result of the FIRST matching condition - evaluation stops there
Like an if/else-if chain, order matters. Put the most specific conditions first, exactly as in the grade-boundary example.
CASEOrder
Q27. medium
What does the IS NOT DISTINCT FROM operator do?
- A Compares two values treating NULL as equal to NULL
- B The same as <>
- C Tests data types
- D Removes duplicates
Answer: A β Compares two values treating NULL as equal to NULL
Supported in PostgreSQL and some others, it solves the awkward case of comparing nullable columns without writing (a = b OR (a IS NULL AND b IS NULL)).
NULLComparison
Q28. medium
Which is TRUE about the empty string '' versus NULL?
- A They are different: '' is a known blank value, NULL is unknown (except in Oracle, which treats '' as NULL)
- B They are always identical
- C '' is invalid SQL
- D NULL is shorter to store
Answer: A β They are different: '' is a known blank value, NULL is unknown (except in Oracle, which treats '' as NULL)
Real datasets frequently contain both, so data-cleaning queries usually check for both: WHERE col IS NULL OR TRIM(col) = ''.
NULLEmpty stringOracle
Q30. medium
Which condition safely finds rows where a numeric column is missing OR zero?
- A WHERE COALESCE(amount, 0) = 0
- B WHERE amount = 0
- C WHERE amount = NULL OR 0
- D WHERE amount IS 0
Answer: A β WHERE COALESCE(amount, 0) = 0
COALESCE converts NULL to 0 first, so one condition covers both cases. (Note this prevents index use on amount - acceptable for reporting queries.)
COALESCENULL
Hard questions (14)
Q2. hard
What is the result of 100 + NULL?
SELECT salary + COALESCE(bonus, 0) AS total FROM staff;
- A NULL - any arithmetic with NULL yields NULL
- B 100
- C 0
- D An error
Answer: A β NULL - any arithmetic with NULL yields NULL
Unknown plus anything is still unknown. This silently propagates: a single NULL bonus can turn a computed total salary into NULL. Use COALESCE to substitute a default.
NULLCOALESCE
Q5. hard
What does NULLIF(a, b) return?
SELECT passed * 100.0 / NULLIF(total, 0) AS pct FROM stats;
- A NULL if a equals b, otherwise a
- B a if b is NULL
- C The first non-NULL value
- D TRUE or FALSE
Answer: A β NULL if a equals b, otherwise a
Its classic use is avoiding division by zero: total / NULLIF(count, 0) yields NULL instead of raising an error.
NULLIFDivision by zero
Q6. hard
Do aggregate functions like SUM and AVG include NULLs?
- A No - they IGNORE NULLs (which changes what AVG divides by)
- B Yes, treating them as 0
- C They return NULL if any value is NULL
- D They throw an error
Answer: A β No - they IGNORE NULLs (which changes what AVG divides by)
AVG(score) over values 10, 20, NULL is 15 (sum 30 divided by 2), not 10. If NULL should count as zero, write AVG(COALESCE(score, 0)).
- A very common source of subtly wrong reports.
AggregatesNULLAVG
Q8. hard
What does this return when some emails are NULL?
SELECT COUNT(*) - COUNT(email) FROM users;
- A The number of users whose email IS NULL
- B Zero always
- C The total user count
- D NULL
Answer: A β The number of users whose email IS NULL
A neat idiom for counting missing values without a separate WHERE clause. Equivalent to COUNT(*) FILTER (WHERE email IS NULL) where supported.
COUNTData quality
Q11. hard
How do you match a LITERAL percent sign with LIKE?
- A Use an escape character: LIKE '%50\%%' ESCAPE '\'
- B Use double %%
- C Put it in quotes
- D It is impossible
Answer: A β Use an escape character: LIKE '%50\%%' ESCAPE '\'
Without escaping, % is a wildcard. The ESCAPE clause designates a character that makes the next symbol literal - needed when searching for discounts like '50%'.
LIKEESCAPE
Q14. hard
What is the difference between BETWEEN and >= / <= ?
- A None functionally - BETWEEN is shorthand and is INCLUSIVE at both ends
- B BETWEEN excludes the endpoints
- C BETWEEN is faster
- D BETWEEN only works on numbers
Answer: A β None functionally - BETWEEN is shorthand and is INCLUSIVE at both ends
x BETWEEN 10 AND 20 is exactly x >= 10 AND x <= 20. For dates and timestamps the explicit form is safer because you can use a half-open range.
BETWEENRanges
Q16. hard
What is integer division in SQL?
SELECT 3 / 2;
- A In many databases it returns 1 - integer inputs give an integer result
- B Always 1.5
- C An error
- D 0
Answer: A β In many databases it returns 1 - integer inputs give an integer result
PostgreSQL and SQL Server truncate; MySQL returns 1.5. To be safe, force decimals: 3 * 1.0 / 2 or CAST(3 AS DECIMAL) / 2.
DivisionType casting
Q18. hard
What does EXISTS test?
SELECT * FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
- A Whether a subquery returns AT LEAST ONE row - it returns TRUE/FALSE, not data
- B Whether a table exists
- C Whether a column is NULL
- D Whether a value is in a list
Answer: A β Whether a subquery returns AT LEAST ONE row - it returns TRUE/FALSE, not data
EXISTS stops at the first matching row, so it is efficient. Unlike NOT IN, NOT EXISTS handles NULLs correctly - the safer choice for anti-joins.
EXISTSSubqueries
Q19. hard
Why prefer NOT EXISTS over NOT IN?
- A NOT IN returns NO rows if the subquery contains any NULL; NOT EXISTS handles NULLs correctly
- B NOT IN is invalid syntax
- C NOT EXISTS is shorter
- D They are identical
Answer: A β NOT IN returns NO rows if the subquery contains any NULL; NOT EXISTS handles NULLs correctly
This silent-empty-result bug is a favourite interview topic. Either use NOT EXISTS, or add WHERE col IS NOT NULL inside the subquery.
NOT EXISTSNULLGotchas
Q21. hard
What does > ALL (SELECT ...) mean?
- A Greater than EVERY returned value - i.e. greater than the maximum
- B Greater than at least one
- C Greater than the average
- D Invalid syntax
Answer: A β Greater than EVERY returned value - i.e. greater than the maximum
Careful: if the subquery returns no rows, > ALL is TRUE by definition (vacuous truth), while > ANY would be FALSE.
ALLANY
Q23. hard
What happens with 'Hello' || NULL in most databases?
SELECT first || ' ' || COALESCE(middle || ' ', '') || last AS full_name;
- A The result is NULL - concatenating with NULL wipes the whole string
- B 'Hello'
- C 'HelloNULL'
- D An error
Answer: A β The result is NULL - concatenating with NULL wipes the whole string
This is why full-name columns sometimes come out blank when a middle name is missing. CONCAT() in MySQL/SQL Server treats NULL as an empty string, or wrap values in COALESCE.
NULLConcatenation
Q25. hard
How do you count rows matching a condition WITHOUT a WHERE clause?
SELECT
COUNT(*) AS total,
SUM(CASE WHEN status='paid' THEN 1 ELSE 0 END) AS paid,
SUM(CASE WHEN status='due' THEN 1 ELSE 0 END) AS due
FROM invoices;
- A SUM(CASE WHEN condition THEN 1 ELSE 0 END)
- B COUNT(condition)
- C COUNT(*) WHERE condition
- D It is impossible
Answer: A β SUM(CASE WHEN condition THEN 1 ELSE 0 END)
This 'conditional aggregation' lets you compute several different counts in a single pass - the standard way to build summary reports.
Conditional aggregationCASE
Q26. hard
Why does COUNT(CASE WHEN x THEN 1 END) work without ELSE?
- A Non-matching rows produce NULL, and COUNT ignores NULLs
- B It counts zeros
- C ELSE is required
- D It errors
Answer: A β Non-matching rows produce NULL, and COUNT ignores NULLs
A neat alternative to SUM(...ELSE 0). Both are widely used; the COUNT version relies on NULL being skipped.
COUNTNULLCASE
Q29. hard
Why is a column full of NULLs a design smell?
- A It often signals a missing related table or an attribute belonging to a subtype
- B NULLs are always forbidden
- C NULLs use lots of storage
- D It is never a problem
Answer: A β It often signals a missing related table or an attribute belonging to a subtype
If only 2% of rows use a set of columns, those attributes may belong in a separate related table. Normalisation (topic 18) addresses exactly this.
DesignNormalization