SQL Practice Logo

SQLPractice Online

MySQL String & Math Functions: Performance

Module: Database-Specific Features

Functions impact performance differently: (1) Functions in WHERE: Prevent index usage (sequential scan, slow), use range comparisons instead. Example: YEAR(date) comparison (slow) vs date range (fast with index). (2) Functions in SELECT: Applied after filtering (fine), no index impact. (3) Generated columns: Use for frequently queried functions (UPPER(email)), create index on generated column. (4) Aggregate functions: Use with indexes on GROUP BY columns. Real-world: Amazon avoids functions in WHERE (uses range comparisons). Stripe uses generated columns for UPPER(email). Google Analytics uses DATE_FORMAT() in SELECT only.

Functions in WHERE: Prevent index usage (sequential scan), use range comparisons

Generated columns: Enable indexing for functions (UPPER, LOWER), 100x faster

Functions in SELECT: Fine (applied after filtering), no performance impact

DATE_FORMAT() in WHERE: Prevents index, use date >= '2024-01-01' instead

Aggregate functions: Use indexes on GROUP BY columns for faster grouping

SUBSTRING() in WHERE: Prevents index, use LIKE 'prefix%' instead

Avoid nested functions: UPPER(TRIM(col)) slow, use generated column

Functions in WHERE on indexed columns: Prevents index usage, sequential scan (slow)

YEAR(date) = 2024: Prevents index, use date >= '2024-01-01' AND date < '2025-01-01'

UPPER(col) = 'VALUE': Prevents index, use generated column with index

Not rounding currency: Use ROUND(amount, 2) for 2 decimal places

Using IFNULL() for multiple values: Use COALESCE() instead (supports multiple values)