1. Database Basics & Querying
SQL Text, Date & Math Functions
Clean messy text with TRIM, LOWER, and COALESCE, format and filter dates cleanly, and perform rounded numeric calculations right inside SQL queries.
- Clean and standardize text fields using TRIM, LOWER, and SUBSTR
- Avoid NULL math pitfalls with COALESCE and integer-division fixes
- Filter time windows cleanly using ISO dates and date functions
Real-world data is rarely spotless: emails have trailing spaces or mixed uppercase letters, phone numbers are NULL, and reports ask for "orders from the last 30 days." SQL's built-in functions handle all of this cleanly inside your query.
Cleaning & Formatting Text
SELECT
id,
TRIM(LOWER(email)) AS normalized_email,
LENGTH(full_name) AS name_length,
SUBSTR(full_name, 1, 1) AS first_initial
FROM students;LOWER(...)/UPPER(...)— normalize casing for consistent comparisonsTRIM(...)— remove accidental spaces at the start and endSUBSTR(text, start, length)— extract part of a string (SQL positions start at 1)
Replacing NULL Safely with COALESCE
COALESCE(a, b) returns the first non-NULL value in its arguments:
SELECT
full_name,
COALESCE(phone, 'Not Provided') AS contact_phone
FROM students;You can also guard math calculations against NULL: COALESCE(discount, 0).
Conditional Logic in Queries (CASE WHEN)
Need to bucket rows into readable categories—such as pricing tiers or order health—without exporting to Python first? Use CASE WHEN ... THEN ... ELSE ... END:
SELECT
name,
price,
CASE
WHEN price >= 80 THEN 'Premium'
WHEN price >= 35 THEN 'Mid-Range'
ELSE 'Budget'
END AS price_tier
FROM products;Math Functions (ROUND, ABS)
SELECT
title,
ROUND(price * 0.85, 2) AS discounted_price
FROM products;In SQLite and PostgreSQL, 5 / 2 with two integers equals 2 (integer division), NOT 2.5! Multiply by 1.0 or use a decimal (5 * 1.0 / 2) whenever you want an exact decimal average or percentage.
Working with Dates
Dates stored in ISO format (YYYY-MM-DD, like '2026-11-29') sort alphabetically and chronologically in the exact same order!
-- PostgreSQL: orders in the last 30 days
SELECT id, ordered_at
FROM orders
WHERE ordered_at >= CURRENT_DATE - INTERVAL '30 days';
-- SQLite equivalent:
SELECT id, ordered_at
FROM orders
WHERE ordered_at >= DATE('now', '-30 days');Try It Yourself: Live SQL Functions & CASE WHEN
Click “Run Code” to execute this snippet right in your browser.
Quick Checkpoints
What does COALESCE(nickname, full_name, 'Guest') return if nickname is NULL and full_name is 'Riya'?
Why do databases prefer storing dates as ISO YYYY-MM-DD strings or DATE types instead of DD/MM/YYYY?