Text functions and NULL handling
SQL · 17 questions
Short notes
Key idea
Real data has messy text and missing values. Text functions tidy strings; COALESCE and NULLIF handle NULLs safely.
Syntax
UPPER(name), LOWER(name), TRIM(name), LENGTH(name)
SUBSTRING(phone FROM 1 FOR 3)
first_name || ' ' || last_name -- join text
REPLACE(city, 'Bombay', 'Mumbai')
COALESCE(discount, 0) -- first non-NULL value
NULLIF(qty, 0) -- NULL when qty is 0
Example
Clean city names and avoid dividing by zero:
SELECT UPPER(TRIM(city)) AS city,
revenue / NULLIF(orders, 0) AS avg_order
FROM city_stats;
Traps
- Anything combined with NULL is NULL:
'a' || NULLis NULL. Wrap parts inCOALESCE. ' Chennai'and'Chennai'are different groups. Trim before grouping.LIKEis case-sensitive; useILIKE(DuckDB, PostgreSQL) or compare withLOWER().COALESCEchanges what an average means: replacing NULL with 0 pulls the average down.
Want the full lesson with step-by-step examples, a project and a certificate? SQL course, ₹120 →
- Question 1easy
What does
COALESCE(NULL, NULL, 'Chennai', 'Madurai')return? - Question 2medium
first_name || ' from ' || city: what is the result for a customer whose city is NULL? - Question 3medium
6 customers have a first name starting with "A". What does this return?
SELECT COUNT(*) FROM customers WHERE first_name LIKE 'a%';
- Question 4medium
4 products are in the Books category. What does this return?
SELECT COUNT(*) FROM products WHERE product_name ILIKE '%book%';
- Question 5hard
Return
categoryandproducts: the product names in that category joined with', ', in alphabetical order. Skip products with no category.Tables
Text functions and NULL handling
Text functions and NULL handling
Text functions and NULL handling
Text functions and NULL handling
Text functions and NULL handling
12 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.