4. MySQL commonly used functions

tags: MySQL  

String function

function Features
CONCAT(S1,S2,…Sn) Level S1, S2,...Sn into a string
INSERT(str,x,y,instr) Replace the string str, starting at position x, a substring of y characters long with instr
LOWER(str) Convert all characters of string str to lowercase
UPPER(str) Convert all characters in the string str to uppercase
LEFT(str,x) Returns the x characters from the left of the string str
RIGHT(str,x) Returns the x characters on the right side of the string str
LPAD(str,n,pad) Fill the left side of the string with the string pad until the length is n characters long
RPAD(str,n,pad) Fill the right side of the string with the string pad until the length is n characters long
LTRIM(str) Remove the left space of the string
RTRIM(str) Remove the space on the right side of the string
REPEAT(str,x) Repeat the string str x times
REPLACE(str,a,b) Replace all occurrences of a string in string str with string b
STRCMP(s1,s2) Compare strings s1 and s2
TRIM(str) Remove all strings at the end and beginning of the string str
SUBSTRING(str,x,y) Returns a string of length y from position str x
  • CONCAT(s1,s2,...sn)Concatenate multiple strings into one string, any string andNULLThe result of the connection isNULL
select CONCAT('ads','133'),CONCAT('abc',NULL);	

  • INSERT(str,x,y,instr)Replace the y characters of the string str starting from x with instr
select INSERT('Hello World',7,5,'MySQL');

  • LOWER(str)Convert all string str to lowercase
select LOWER('bHUFRhjH');

  • UPPER(str)Convert the string str to uppercase
select UPPER('jhssdgvTF');

  • LEFT(str,x)withRIGHT(str,x)Returns x characters to the left/right of string str
select LEFT('BEIJIN',3),RIGHT('LOVE',2);

  • LPAD(str,n,pad)withRPAD(str,n,pad)Fill the characters on the left/right side of the string str with pad until the length is n characters long
select lpad('2008',20,'beijing'),rpad('beijing',20,'2008');

  • LTRIM(str)And ``RTRIM(str)` to remove the spaces on the left/right side of the string str
select  LTRIM('   |b'),RTRIM('h|   ');

  • REPEAT(str,n)Repeat the string str n times
select REPEAT('Hello ',4);

  • REPLACE(str,a,b)Replace a in str with b
select REPLACE('Hello World','World','MySQL');

  • STRCMP(s1,s2)Compare the uppercase of the ASCII code value of the string s1, s2, if s1 is smaller than s2, return -1, if s1 and s2 are equal, return 0, if s1 is greater than s2, return 1
select STRCMP('java','python');

  • TRIM(str)Remove str leading and trailing spaces
select TRIM('   |k|   ');

  • SUBSTRING(str,x,y)Returns the y characters of the string str starting from x
select  SUBSTRING('Hello',1,2);

Numerical function

function effect
ABS(x) Returns the absolute value of x
CEIL(x) Returns the largest integer value greater than x
FLOOR(x) Returns the largest integer value less than x
MOD(x,y) Returns the value of x%y
RAND() Return a random value from 0 to 1
ROUND(x,y) Returns the value of x with y decimals after rounding
TRUNCATE(x,y) Returns the result of the number x truncated to y decimals
  • ABS(x)Returns the absolute value of x
select ABS(-8),ABS(8);

  • CEIL(x)Returns the largest integer value greater than x
select CEIL(2.6),CEIL(2.1);

  • FLOOR(x)Returns the largest integer value less than x
select FLOOR(3.9),FLOOR(3.1);

  • MOD(x,y)Returns the value of x%y
select MOD(5,2),5%2;

  • RAND()Return a random value from 0 to 1
select RAND(),RAND();

  • ROUND(x,y), Returns the value that contains y decimal places after rounding x
select ROUND(2.5674,3); 

Date and time type functions

function effect
CURDATE() Return current date
CURTIME() Return current time
NOW() Return the current date and time
UNIX_TIMESTAMP(date) Returns the UNIX timestamp of the date date
FROM_UNIXTIME() Returns the date value of the UNIX timestamp
WEEK(date) Return date date is the first few weeks of the year
YEAR(date) Returns the year of the date date
HOUR(time) Returns the hour value of time
MIUNTE(time) Returns the minute value of time
MONTHNAME(date) Returns the month name of date
DATE_FORMAT(date,fmt) Returns the date value formatted by the string fmt
DATE_ADD(date,INTERVAL expr type) Returns a date or time value plus a time interval time value
DATEDIFF(expr,expr2) Returns the number of days between the start time expr and the end time expr2
  • CURDATE()Return the current date value, including only the year, month, and day
select CURDATE();

  • CURTIME()Returns the current time including only hours, minutes and seconds
select CURTIME();

  • NOW()Return the current date and time
select NOW();

  • UNIX_TIMESTAMP(date)Returns the UNIX timestamp of date
select UNIX_TIMESTAMP(NOW());

  • FROM_UNIUXTIME(unixtime)Return the date value of the UNIX timestamp, andUNIX_TIMESTAMP(date)in contrast
select FROM_UNIXTIME(1597733300);

  • WEEK(date) and YEAR(date)The former returns the given date in the first few weeks of the year, the latter returns the given date in which year
select WEEK(NOW()),YEAR(NOW());

  • HOUR(time)withMINUTE(time)The former returns the hour of the given time, the latter returns the minute of the given time
select HOUR(CURTIME()),MINUTE(CURTIME());

  • MONTHNAME(date)Returns the name of the month corresponding to date
select MONTHNAME(NOW());

  • DATE_FORMAT(date,fmt), Format the date date according to the string fmt, the format characters that can be used are as follows
Format Format description
%S,%s Second in two-digit format (00,01,...,59)
%i Minutes in two-digit format (00,01,...,59)
%H Two-digit hour, 24 hours (0,1,...,24)
%h,%l Two-digit hour, 12 hours (0,1,...,12)
%k Numerical hour, 24 hours (0,1,...,24)
%l Number of hours, 12 hours (0,1,...,12)
%T 24-hour format (hh:mm:ss)
%r 12-hour format (hh:mm:ssAM or hh:mm:ssPM)
%p AM or PM
%W The name of each day of the week (Sunday,Monday,…,Saturday)
%a Abbreviation of the name of each day of the week (Sun,Mon,…,Sat)
%d Two digits indicate the number of days in the month (00, 01, ..., 31)
%e The number indicates the number of days in the month (1,2,...,31)
%D The English suffix indicates the number of days in the month (1st, 2nd, 3rd...)
%w Art form represents the number of days of the week (0=Sunday,1=Monday,…,6=Saturday)
%j Use three digits to indicate the number of days in the year (001, 002,...336)
%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, (January,February,…,December)
%b Abbreviated month (Jan,Feb,...Dec)
%m Two-digit month (01,02,...,12)
%c Number of months (1,2,…12)
%Y 4-digit year
%y Two-digit year
%% Direct value
select DATE_FORMAT(NOW(),'%Y year%m month%d day%H hour%i minute%S second');

  • DATE_ADD(date,INTERVAL expr type)Returns the INTERVAL time period from the given date, where INTERVAL is the time interval type, expr is an expression, type is the interval type, and MySQL provides 13 interval types.
Expression type description format
HOUR hour hh
MINUTE minute mm
SECOND second ss
YEAR year YY
MONTH month MM
DAY day DD
YEAR_MONTH years YY-MM
DAY_HOUR Day and time DD hh
DAY_MINUTE Day and minute DD hh:mm
DAY_SECOND Day and second DD hh:mm:ss
HOUR_MIUNTE Hours and minutes hh:mm
HOUR_SECOND Hour and second hh:ss
MINUTE_SECOND Minutes and seconds mm:ss
select NOW() CURRENT,DATE_ADD(NOW(),INTERVAL 31 DAY) AFTER_31_DAYS,DATE_ADD(NOW(),INTERVAL '1_2' YEAR_MONTH) AFTER_1YEAR_2MONTH;

  • DATEDIFF(date1,date2) calculates the number of days between two dates
select DATEDIFF('20210101',now());

Process function

Process functions are also a very commonly used function. Users can use this type of function to implement conditional selection in a SQL statement, which can improve the efficiency of the statement

function effect
IF(value,t ,f) If value is true, return t, otherwise return f
IFNULL(value1,value2) If value1 is not empty, return value1, otherwise return value2
CASE WHEN [value1] THEN[result1]…ELSE[default] END If value1 is true, return result1, otherwise return default
CASE[expr] WHEN[value1] THEN[result1] …ELSE[default]END If expr is equal to value1, return result1, otherwise return default

Create employee salary table

 create table salary (userid int,salary decimal(9,2));

Insert test data

 insert into salary values(1,1000),(2,2000), (3,3000),(4,4000),(5,5000), (1,null);
  • IF(value,t,f) If the employee's salary is greater than 3000, it is displayed as "high", otherwise it is displayed as "low"
select IF(salary>3000,'high','low') from salary;	

  • IFNULL(value1,value2)Often used to replace NULL
select IFNULL(salary,0) from salary;

  • CASE WHEN to achieve a high base salary
select CASE WHEN salary >=2000 then 'higt' ELSE 'low' END  from salary;

Other commonly used functions

Function name effect
DATABASE() Returns the current database name
VERSION() Returns the current database version
USER() Returns the currently logged in user name
INET_ATON(IP) Return the numeric representation of the IP address
INET_NTOA(num) Return the IP address represented by the number
PASSWORD(str) Returns the encrypted version of the string str
MD5(str) Returns the MD5 value of the string str
  • DATABASE
select DATABASE();

  • VERSION()
select VERSION();

  • USER()
select USER();

  • INET_ATON(ip)
select INET_ATON('192.168.31.51');

  • INET_NTOA(num)
select INET_NTOA(3232243507);

  • PASSWORD(str)
select PASSWORD('ihgyugjui4564');

  • MD5(str)
select MD5('sfcsf4778x');

  • INET_ATON(ip)
select INET_ATON('192.168.31.51');

  • INET_NTOA(num)
select INET_NTOA(3232243507);

Intelligent Recommendation

Compile and install openstack mitaka horizon

Since the openstack rpm package version is too low, there are bugs that can only manually compile and install a new version of horizon. For details of the bugs, please see [url=http://powertech.iteye....

In-depth understanding of Java enumeration Enum type usage

Enum refers to a sorted list of items that are packaged into a single entity. An instance of an enumeration can use the value of any single item in the list of enumerated items. Enumeration has a wide...

TensorFlow basics: Hello TensorFlow

Foreword Take some time every day to sort out some TF knowledge points includes tensorflow1.0 and tensorflow2.0 hello TensorFlow First meeting The value of TensorFlow needs to be displayed using sessi...

Detailed UIAutomator2.0 (UIDevice articles-waitForIdle)

UIDevice provides 5 methods for waiting. In this article, we will explain them one by one. Let's take a look first, if there is no wait operation, our execution effect will be. We use the previous cha...

WeChat applet introduces iconfont icon

Method 1, Font class mode There are three modes in the upper left corner of the picture below, Unicode, Font class and Symbol. Select Font class mode, then click the link below [Click to copy code] an...

More Recommendation

Optimize performance with Kotlin a custom letter index control

After the App refactored with Kotlin, the biggest feeling was that kotlin's simple syntax and extension functions greatly improved the speed at which we wrote the code. If Java is a normal train start...

Swift learning - extensions, generics, constraints -1/5

Yesterday was too busy to make a full day. It took a lot of time to move the blog to the brief book at noon and at night, and it felt great. I saw my favorite generics at noon today. The various thing...

The first program of openwrt--helloword

The first program of openwrt-helloword The first program The first program of openwrt--helloword 1. Create a new folder helloword under package 2. Create helloword.c and Makefile under the src folder ...

C ++ token allocation space

C ++ token allocation space First, C ++ memory partition model 1.1 code fast (before running) 1.2 global zone (before running) 1.3 Stack Area (running) 1.4 pile (running)...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top