Appearance
Functions
String functions
CONCAT
Joins two or more strings together.
sql
SELECT CONCAT(firstname, ' ', lastname) AS fullname FROM users;Returns e.g. Teppo Testi.
LOWER / UPPER
Converts text to lowercase or uppercase.
sql
SELECT LOWER('Hello World'); -- hello world
SELECT UPPER('Hello World'); -- HELLO WORLDLENGTH
Returns the number of characters in a string.
sql
SELECT LENGTH('Teppo'); -- 5TRIM
Removes leading and trailing whitespace from a string.
sql
SELECT TRIM(' hello '); -- helloYou can also trim only one side:
sql
SELECT LTRIM(' hello'); -- hello
SELECT RTRIM('hello '); -- helloSUBSTRING
Extracts a part of a string. Takes the string, start position, and length.
sql
SELECT SUBSTRING('Hello World', 1, 5); -- HelloREPLACE
Replaces occurrences of a substring within a string.
sql
SELECT REPLACE('Hello World', 'World', 'SQL'); -- Hello SQLDate functions
NOW
Returns the current date and time.
sql
SELECT NOW(); -- 2024-06-15 14:30:00DATE / TIME
Extracts the date or time part from a datetime value.
sql
SELECT DATE(NOW()); -- 2024-06-15
SELECT TIME(NOW()); -- 14:30:00YEAR / MONTH / DAY
Extracts a specific part from a date.
sql
SELECT YEAR('2024-06-15'); -- 2024
SELECT MONTH('2024-06-15'); -- 6
SELECT DAY('2024-06-15'); -- 15DATEDIFF
Returns the number of days between two dates.
sql
SELECT DATEDIFF('2024-12-31', '2024-01-01'); -- 365The first argument is the later date, the second is the earlier date.
DATE_ADD / DATE_SUB
Adds or subtracts a time interval from a date.
sql
SELECT DATE_ADD('2024-01-01', INTERVAL 30 DAY); -- 2024-01-31
SELECT DATE_SUB('2024-06-15', INTERVAL 1 MONTH); -- 2024-05-15Numeric functions
ROUND
Rounds a number to a specified number of decimal places.
sql
SELECT ROUND(3.14159, 2); -- 3.14
SELECT ROUND(3.5); -- 4FLOOR / CEIL
FLOOR rounds down, CEIL rounds up to the nearest integer.
sql
SELECT FLOOR(3.7); -- 3
SELECT CEIL(3.2); -- 4MOD
Returns the remainder of a division.
sql
SELECT MOD(10, 3); -- 1RAND
Returns a random decimal number between 0 and 1.
sql
SELECT RAND(); -- e.g. 0.7324Useful for returning rows in random order:
sql
SELECT * FROM grades ORDER BY RAND() LIMIT 1;ABS
Returns the absolute (non-negative) value of a number.
sql
SELECT ABS(-5); -- 5Exercises
- Use
CONCATto combine first and last name into a full name. - Select all names in uppercase using
UPPER. - Find the length of each name using
LENGTH. - Use
TRIMto clean up a string with extra spaces. - Extract the year and month from a date column using
YEARandMONTH. - Calculate the number of days between two dates using
DATEDIFF. - Round a decimal column to 1 decimal place using
ROUND. - Use
FLOORandCEILon the same value and compare the results. - Return a random row from a table using
RAND. - Use
SUBSTRINGto extract the first 3 characters of a name.