Table of contents
In MySQL, a function is a database object that performs a specific operation or calculation and returns the result. Functions are commonly used for querying, data processing and transformation, and performing other operations within SQL statements. MySQL provides many built-in functions that can be used for various purposes.
1. String functions
function | Function |
---|---|
CONCAT(str1, str2, ...) | Concatenate two or more strings into one string |
LENGTH(str) | Returns the length of the string (number of characters) |
SUBSTRING(str, start, length) | Extract a substring from a string, you can specify the starting position and the number of characters to extract |
UPPER(str) | Convert string to uppercase |
LOWER(str) | Convert string to lowercase |
TRIM([leading | trailing | both] trimstr FROM str) | Remove specified characters from the beginning, end, or both ends of a string (trimstr) |
REPLACE(str, from_str, to_str) | Replace specific substring in string |
LEFT(str, length) | Returns the substring of the specified length on the left side of the string |
RIGHT(str, length) | Returns the substring of the specified length on the right side of the string |
LOCATE(substr, str[, start]) | Find the position of a substring (substr) in a string |
INSTR(str, substr) | Returns the position of the substring in the string |
CHAR_LENGTH(str) | Returns the number of characters in a string, not the number of bytes |
REVERSE(str) | Reverse the order of characters in a string |
CONCAT_WS(separator, str1, str2, ...) | Concatenate multiple strings into one string, using the specified separator to separate them |
LEFT() and RIGHT() | These two functions are used to extract characters of a specified length from the left or right side of a string. |
LPAD(str, length, padstr) | Left-pad a string to the specified length, using the specified padding character (padstr) |
RPAD(str, length, padstr) | Right-pad a string to the specified length, using the specified padding character (padstr) |
MID() or SUBSTRING() | Used to extract substrings from strings |
Commonly used string functions
String concatenation
# 字符串拼接
select concat('mysql',' hello');
Return results:
Convert case
# 转换为小写
select lower('DAN');
# 转换为大写
select upper('dog');
Pad left and right strings
# 左侧填充
select lpad('11',5,'_');
# 右侧填充
select rpad('11',9,'%');
Remove left and right spaces
# 去除左右空格
select trim(' dag d awd aw');
String interception
select substring('hello world',1,7);
2. Numerical functions
-
SUM(column) : Calculates the sum of all values in the specified column.
-
AVG(column) : Calculates the average of all values in the specified column.
-
COUNT(column) : Counts the number of non-NULL values in the specified column. Can be used to count the number of rows or the number of rows that meet certain conditions.
-
MAX(column) : Find the maximum value in the specified column.
-
MIN(column) : Find the minimum value in the specified column.
-
ROUND(number, decimals) : Rounds a number to the specified number of decimal places.
-
CEIL(number) : Round the number up to the nearest integer.
-
FLOOR(number) : Round the number down to the nearest integer.
-
ABS(number) : Returns the absolute value of a number.
-
POWER(base, exponent) : Calculate the specified power of a number.
-
SQRT(number) : Calculate the square root of a number.
-
MOD(dividend, divisor) : Calculate the remainder of the division of two numbers.
-
RAND() : Generates a random floating point number between 0 and 1 .
-
TRUNCATE(number, decimals) : intercept the decimal part of a number and retain the specified number of decimal places.
-
SIGN(number) : Returns the sign of a number, that is, 1 represents a positive number, -1 represents a negative number, and 0 represents zero.
-
LOG(number) : Calculates the natural logarithm of a number.
These numerical functions allow you to perform a variety of mathematical and statistical operations, including sums, averages, maximums, minimums, rounding, absolute values, exponentiation, remainder calculations, and more. These functions are useful in data analysis, report generation, calculations, and numerical processing.
Small case: Generate a six-digit random verification code through the above numerical function
Idea: Use the random generation function RAND() to multiply the corresponding number of digits. You need to consider the lack of decimal points and use left padding or right padding to complete the six digits.
select lpad(round((rand()*1000000), 0),6,'0')
3.Date function
-
NOW() : Returns the current date and time.
-
CURDATE() : Returns the current date.
-
CURTIME() : Returns the current time.
-
DATE_FORMAT(date, format) : Format the date into a string in the specified format. For example, "%Y-%m-%d" means year-month-day.
-
DAYNAME(date) : Returns the name of the day of the week corresponding to the date.
-
MONTHNAME(date) : Returns the name of the month corresponding to the date.
-
DAY(date) : Returns the day part of the date.
-
MONTH(date) : Returns the month part of the date.
-
YEAR(date) : Returns the year part of the date.
-
HOUR(time) : Returns the hour part of time.
-
MINUTE(time) : Returns the minute part of the time.
-
SECOND(time) : Returns the seconds part of the time.
-
TIMESTAMPDIFF(unit, start, end) : Calculate the difference between two dates or times. The unit can be seconds, minutes, hours, days, months, etc.
-
TIMESTAMPADD(unit, interval, date) : Adds the specified time interval to the date or time.
-
DATE_ADD(date, INTERVAL expr unit) : Add a period of time to the date.
-
DATE_SUB(date, INTERVAL expr unit) : Subtract a period of time from the date.
-
DATEDIFF(end, start) : Calculates the difference in days between two dates.
-
STR_TO_DATE(str, format) : Convert a string to a date, according to the specified format.
These date functions allow you to perform various date and time processing operations in queries and data operations, such as date formatting, date calculations, date comparisons, etc. You can choose the appropriate function to handle date and time data based on your specific needs.
Small case: Query the number of days of employment of all employees and sort them in reverse order according to the number of days of employment.
SELECT employee_id, DATEDIFF(NOW(), hire_date) AS days_since_hire
FROM employees
ORDER BY days_since_hire DESC;
Use
DATEDIFF
the function to calculateNOW()
the number of days difference between the current date ( ) and the joining date, and thendays_since_hire
sort the results in reverse order by the field to display the employees with the longest joining days first.
4. Process function
CASE expression : used to implement conditional branch logic in SQL queries. It comes in two main forms:
Simple CASE expression: similar to multiple IF-THEN-ELSE statements.
CASE expression
WHEN value1 THEN result1
WHEN value2 THEN result2
...
ELSE default_result
END
Search CASE expressions: More complex conditions can be used to implement branching logic.
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE default_result
END
IF function : used to implement conditional logic, similar to conditional statements in programming languages. It accepts a conditional expression and returns a value if the condition is true; otherwise it returns another value.
IF(condition, value_if_true, value_if_false)
COALESCE function : Returns the first non-NULL value from a set of expressions. Typically used to handle data that may be NULL.
COALESCE(expr1, expr2, ...)
NULLIF function : If two expressions are equal, it returns NULL, otherwise it returns the value of the first expression. Used to handle the equality of two expressions.
NULLIF(expr1, expr2)
5. Summary
Commonly used functions
1. String functions
CONCAT,LOWER,UPPER,LPAD,RPAD,TEIM,SUNSTRING
2. Numerical functions
CEIL,FLOOR,MOD,RAND,ROUND
3.Date function
CURDATE,CURTIME,NOW,YEAR,MONTH,DAY,DATE_ADD,DATEDIFF
4. Process function
IF,CASE[...] WHEN ... THEN ... ELSE ... END