MySQL common functions

Source: Internet
Author: User
Tags month name natural logarithm

I. mathematical functions

ABS (x) returns the absolute value of X.
Bin (x) returns the binary value of X (Oct returns octal, Hex returns hexadecimal)
Ceiling (x) returns the smallest integer greater than X.
Exp (x) returns the X power of E (the base of the natural logarithm ).
Floor (x) returns the largest integer less than X.
Greatest (x1, x2,..., xn) returns the maximum value in the set.
Least (x1, x2,..., xn) returns the smallest value in the set.
Ln (x) returns the natural logarithm of X.
Log (x, y) returns the base y logarithm of X.
MoD (x, y) returns the modulus (remainder) of x/y)
Pi () returns the PI value (circumference rate)
Rand () returns a random value from 0 to 1. You can generate a specified value by providing a random number generator for the parameter (SEED. Round (x, y) returns the rounded y decimal value of parameter X.
Sign (x) returns the value of the symbol representing the number X.
SQRT (x) returns the square root of a number.
Truncate (x, y) returns the result of truncating X to Y decimal places.

Ii. Aggregate functions (usually used in select queries of group by clauses)
AVG (COL) returns the average value of the specified Column
Count (COL) returns the number of non-null values in the specified column.
Min (COL) returns the minimum value of the specified Column
Max (COL) returns the maximum value of the specified Column
Sum (COL) returns the sum of all values in the specified column.
Group_concat (COL) returns the result of a combination of column values.

Iii. String Functions
ASCII (char) returns the ASCII value of a character
Bit_length (STR) returns the bit length of the string.
Concat (S1, S2. .., SN) concatenates S1, S2. .., and Sn into a string.
Concat_ws (SEP, S1, S2. .., SN) concatenates S1, S2. .., Sn into a string, and uses the SEP character interval.

Insert (STR, X, Y, instr): Start from position X of string str. Replace substring with string instr with length Y. The result is returned.

Find_in_set (STR, list) analyzes the list separated by commas (,). If STR is found, the position of STR in the list is returned.

Lcase (STR) or lower (STR) returns the result of changing all characters in the STR string to lowercase.

Left (STR, x) returns the leftmost x characters in the STR string.

Length (s) returns the number of characters in the STR string.

Ltrim (STR) removes the leading space from the STR string.

Position (substr, STR) returns the position of the substring substr that appears for the first time in the STR string.

Quote (STR) escape single quotes in STR with a backslash

Repeat (STR, srchstr, rplcstr) returns the string 'str' repeated X times.

Reverse (STR) returns the result of reverse string Str

Right (STR, x) returns the rightmost x characters in the STR string.

Rtrim (STR) returns the space at the end of the STR string.

Strcmp (S1, S2) compares strings S1 and S2

Trim (STR) removes all spaces at the beginning and end of the string.

Ucase (STR) or upper (STR) returns the result of converting all characters in the STR string to uppercase.

Iv. Date and Time Functions

Curdate () or current_date () returns the current date

Curtime () or current_time () returns the current time

Date_add (date, interval int keyword) returns the result of date plus the interval int (INT must be formatted according to the keyword), such as: Select date_add (current_date, interval 6 month );

Date_format (date, FMT) format the date value according to the specified FMT Format

Date_sub (date, interval int keyword) returns the result of date plus the interval int (INT must be formatted according to the keyword), such as: Select date_sub (current_date, interval 6 month );

Dayofweek (date) returns the Day (1 ~ 7)

Dayofmonth (date) returns the Day (1 ~ 31)

Dayofyear (date) returns the Day (1 ~ 366)

Dayname (date) returns the week name of date, for example, select dayname (current_date );

From_unixtime (TS, FMT) format the Unix timestamp ts Based on the specified FMT Format

Hour (time) returns the hour value of time (0 ~ 23)

Minute (time) returns the minute value of time (0 ~ 59)

Month (date) returns the month value of date (1 ~ 12)

Monthname (date) returns the month name of date, for example, select monthname (current_date );

Now () returns the current date and time

Quarter (date) returns the quarter (1 ~ 4), such as select quarter (current_date );

Week (date) returns the week (0 ~ 53)

Year (date) returns the year (1000 ~ 9999)

Some examples:

Obtain the current system time: Select from_unixtime (unix_timestamp ());

Select extract (year_month from current_date );

Select extract (day_second from current_date );

Select extract (hour_minute from current_date );

Returns the difference between two date values (number of months): Select period_diff (200302,199802 );

Age calculation in MySQL:

Select date_format (from_days (to_days (now ()-to_days (birthday), '% y') + 0 as age from employee;

In this way, if brithday is the year, month, and day of the future, the calculation result is 0.

The following SQL statement calculates the absolute age of an employee, that is, when birthday is a future date, a negative value is obtained.

Select date_format (now (), '% y')-date_format (birthday,' % y')-(date_format (now (), '00-% m-% D ') <date_format (birthday, '00-% m-% D') as age from employee

V. encryption functions

Aes_encrypt (STR, key) returns the string STR with the key pair using the Advanced Encryption StandardAlgorithmAfter encryption, the result of calling aes_encrypt is a binary string stored as blob.

Aes_decrypt (STR, key) returns the decryption result of the string STR encrypted with the key using the Advanced Encryption Standard algorithm.

Decode (STR, key) uses the key as the key to decrypt the encrypted string Str

Encrypt (STR, salt) uses the Unix crypt () function and uses the keyword salt (a string that uniquely identifies a password, just like a key) to encrypt the string Str

Encode (STR, key) uses key as the key to encrypt the string Str. The result of calling encode () is a binary string, which is stored as blob.

Calculate the MD5 checksum of the STR string using MD5 ().

Password (STR) returns the encrypted version of the string STR, which is irreversible and uses different algorithms than the encryption process of UNIX passwords.

SHA () calculates the Sha checksum of the STR string

Example:

Select encrypt ('root', 'salt ');

Select encode ('xufeng', 'key ');

Select decode (encode ('xufeng', 'key'), 'key'); # Put encryption and decryption together

Select aes_encrypt ('root', 'key ');

Select aes_decrypt (aes_encrypt ('root', 'key'), 'key ');

Select MD5 ('200 ');

Select Sha ('123 ');

Vi. Control Flow Functions

MySQL has four functions used for conditional operations. These functions can implement the SQL conditional logic, allowing developersProgramThe business logic is converted to the database background.

MySQL control flow functions:

Case when [test1] Then [result1]... else [Default] end if testn is true, resultn is returned; otherwise, default is returned.

Case [test] When [val1] Then [Result]... else [Default] end if test and valn are equal, resultn is returned; otherwise, default is returned.

If (test, T, f) If test is true, t is returned; otherwise, F is returned.

Ifnull (arg1, arg2) If arg1 is not empty, arg1 is returned; otherwise, arg2 is returned.

Nullif (arg1, arg2) returns NULL if arg1 = arg2; otherwise, arg1 is returned.

The first of these functions is ifnull (), which has two parameters and judges the first parameter. If the first parameter is not null, the function returns the first parameter to the caller. If the parameter is null, the second parameter is returned.

For example, select ifnull (1, 2), ifnull (null, 10), ifnull (4 * null, 'false ');

The nullif () function checks whether the two provided parameters are equal. If they are equal, null is returned. If they are not equal, the first parameter is returned.

For example, select nullif (), nullif ('A', 'B'), nullif (2 + 3, 4 + 1 );

Like the IF () function provided by many scripting languages, MySQL's if () function can also establish a simple conditional test, which has three parameters, the first is the expression to be judged. If the expression is true, if () returns the second parameter. If the expression is false, if () returns the third parameter.

For example, select if (1 <100, 3), if (56>, 'true', 'false ');

The IF () function is applicable only when there are two possible results. However, in the real world, we may find that multiple branches are required in conditional testing. In this case, MySQL provides the case function, which is the same as the switch-case condition routine in PHP and Perl.

The format of the Case function is a bit complex, usually as follows:

Case [exprEssion to be evaluated]

When [Val 1] Then [result 1]

When [Val 2] Then [result 2]

When [Val 3] Then [result 3]

......

When [Val N] Then [result N]

Else [default result]

End

Here, the first parameter is the value or expression to be judged, followed by a series of when-then blocks. The first parameter of each block specifies the value to be compared. If it is true, returns the result. All when-then blocks end with the else block. When the end ends with all external case blocks, if each of the preceding blocks does not match, the default result specified by the else block is returned. If no else block is specified and all when-then comparisons are not true, MySQL returns NULL.

There is another syntax for the case function, which is sometimes very convenient to use as follows:

Case

When [conditional test 1] Then [result 1]

When [conditional test 2] Then [result 2]

Else [default result]

End

In this condition, the returned result depends on whether the test is true.

Example:

Mysql> select case 'green'

When 'red' then 'stop'

When 'green' then 'Go' end;

Select case 9 when 1 then 'a 'when 2 then 'B' else' N/A' end;

Select case when (2 + 2) = 4 then 'OK' when (2 + 2) <> 4 then 'not OK 'end as status;

Select name, if (isactive = 1), 'activated', 'inactivated') as result from userlogininfo;

Select fname, lname, (Math + Sci + benchmark) as total,

Case when (Math + Sci + timeout) <50 then 'D'

When (Math + Sci + benchmark) between 50 and 150 then 'C'

When (Math + Sci + benchmark) between 151 and 250 then 'B'

Else 'A' end

As grade from marks;

Select if (encrypt ('sue ', 'ts') = upass, 'allow', 'deny') as loginresult from users where uname = 'sue'; # One login verification

VII. Formatting Functions

Date_format (date, FMT) format the date value according to the string FMT

Format (x, y) format X as a sequence of numbers separated by commas (,). y indicates the decimal places of the result.

Inet_aton (IP) returns the number of IP addresses

Inet_ntoa (Num) returns the IP address represented by the number

Time_format (time, FMT) format the time value according to the string FMT

The simplest is the format () function, which can format a large value into a comma-separated readable sequence.

Example:

Select format (34234.34323432, 3 );

Select date_format (now (), '% W, % d % m % Y % R ');

Select date_format (now (), '% Y-% m-% D ');

Select date_format (19990330, '% Y-% m-% D ');

Select date_format (now (), '% H: % I % p ');

Select inet_aton ('10. 122.89.47 ');

Select inet_ntoa (175790383 );

VIII. type conversion functions

To convert data types, MySQL provides the cast () function, which can convert a value to a specified data type. Types: binary, Char, date, time, datetime, signed, unsigned

Example:

Select cast (now () as signed integer), curdate () + 0;

Select 'F' = binary 'F', 'F' = cast ('F' as binary );

9. system information functions

Database () returns the current database name

Benchmark (count, expr) repeatedly runs count times for the expression expr

Connection_id () returns the connection ID of the current customer.

Found_rows () returns the total number of rows retrieved by the last SELECT query.

User () or system_user () returns the current Login User Name

Version () returns the MySQL server version.

Example:

Select database (), version (), user ();

Select benchmark (9999999, log (RAND () * Pi (); # in this example, MySQL calculates the log (RAND () * Pi () expression 9999999 times.

Time Format

Date_forma T (date, format) format the date or Date and Time Value Based on the format string, and return the result string. Date _...

Date_forma T (date, format) format the date or Date and Time Value Based on the format string, and return the result string.

You can use date_format () to format the date or datetime value to obtain the expected format. Format the date value based on the format string:

% S, % s two-digit second (,..., 59)

% I two-digit score (,..., 59)

% H two-digit hour, 24 hours (,..., 23)

% H, % I two-digit hour, 12 hours (,..., 12)

% K, 24 hours (0, 1,..., 23)

% L hour in numeric format (1, 2,..., 12)

% T 24-hour time format (H: M: S)

% R 12-hour time format (HH: mm: SS am or hh: mm: SS pm)

% P am or p m

% W name of each day in a week (s u n d a Y, Monday,..., Saturday)

% A abbreviation of the name of each day in a week (Sun, Mon,..., SAT)

% D indicates the number of days in a month (00, 01,..., 31)

% E indicates the number of days in a month (1, 2,..., 31)

% D indicates the number of days in a month (1st, 2nd, 3rd ,...)

% W represents the number of days in a week (0 = s u n d a Y, 1 = Monday,..., 6 = Saturday)

% J represents the number of days in a year in three digits (001,002,..., 366)

% U Week (0, 1, 52), where Sunday is the first day of the week

% U Week (0, 1, 52), where Monday is the first day of the week

% M month name (j A n u a r y, February,..., December)

% B abbreviated month name (j A n u a r y, February,..., December)

% M double-digit month (01, 02,..., 12)

% C indicates the month (1, 2,..., 12)

The year in the format of % Y.

The year in double-digit % Y format.

% Direct value "%"

Eg: Select date_format (current_date, "% Y-% m ")

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.