String, numeric & control-flow functions
CONCAT, SUBSTRING, REPLACE, ROUND, MOD, IFNULL, COALESCE, IF and CASE expressions.
MySQL ships with hundreds of built-in functions. You call them with NAME(arguments) anywhere an expression is allowed: in the SELECT list, in WHERE, ORDER BY, UPDATE ... SET and more. This lesson covers the string, numeric and control-flow functions you'll use every week. Dates get their own lesson next.
Sample data#
Joining and splitting text#
Notice row 3: CONCAT returns NULL if any argument is NULL, while CONCAT_WS ("with separator") simply skips NULLs. CHAR_LENGTH counts characters. LENGTH counts bytes, which differs for non-ASCII text (LENGTH('é') is 2).
Cleaning up messy input#
A realistic combination is splitting an email into user and domain. SUBSTRING_INDEX(s, delim, n) returns everything before the n-th delimiter (or after it, counting from the right, if n is negative):
Regular-expression helpers are available in MySQL 8: REGEXP_REPLACE, REGEXP_SUBSTR and REGEXP_INSTR. For example, keep only the digits of a phone number:
Numeric functions#
ROUND(x)without a second argument rounds to a whole number. Negative precisions round to tens, hundreds and so on:ROUND(1234, -2)is 1200.FLOORrounds down (towards −∞), soFLOOR(-2.1)is −3.RAND()returns a random number in [0, 1).ORDER BY RAND() LIMIT 1picks a random row, but it's slow on big tables.FORMAT(n, d)adds thousands separators for display:FORMAT(1234567.891, 2)gives'1,234,567.89'.
Integer division has its own operator. 7 / 2 is 3.5000, 7 DIV 2 is 3 and 7 % 2 is 1. Division by zero returns NULL in a SELECT (with a warning), but in strict mode an INSERT or UPDATE that divides by zero fails.
Converting types: CAST and CONVERT#
MySQL often converts implicitly ('10' + 5 is 15), but relying on that hides bugs. Compare numbers with numbers and strings with strings. Note that CAST(3.99 AS SIGNED) rounds to 4.
Control-flow functions: IF, CASE, IFNULL, COALESCE, NULLIF#
These let you make decisions inside a query.
IF(cond, a, b)returnsawhen the condition is true andbotherwise.CASE WHEN ... THEN ... ELSE ... ENDchecks conditions in order and returns the first match. Without anELSE, the result isNULL. There's also the "simple" form:CASE status WHEN 'A' THEN 'Active' WHEN 'B' THEN 'Blocked' END.IFNULL(x, fallback)replaces a NULL.COALESCE(a, b, c, ...)is the standard-SQL version and takes any number of arguments.NULLIF(a, b)returns NULL whena = b. The classic use is avoiding division by zero:total / NULLIF(count, 0).
CASE also works in ORDER BY and inside aggregates. That's a powerful trick you'll use in the aggregates lesson:
Using functions in UPDATE#
Functions are great for one-off data clean-ups:
Common mistakes#
- Forgetting that positions start at 1.
SUBSTRING(s, 0, 3)returns an empty string. - Wrapping indexed columns in functions in
WHERE.WHERE LOWER(email) = 'x'can't use a normal index onemail. Clean data on the way in instead (or use a functional index, covered in Indexes). CONCATwith nullable columns. UseCONCAT_WSorCOALESCE.- Formatting numbers in SQL for the database's own use.
FORMAT()returns a string, so sorting on it sorts text. Format only for display, and ideally in the application.
What's next#
Dates and times deserve a lesson of their own: formatting, adding intervals, computing ages and differences, and dealing with time zones.
Check your understanding
Quick quiz
1.What does
CONCAT('Hello', NULL, 'World')return in MySQL?2.Which expression returns the first non-NULL value among its arguments?
3.What is
ROUND(2.567, 1)versusTRUNCATE(2.567, 1)?
Finished reading?
Mark this lesson complete to track your progress.