By having functions built into MySQL, the speed of performing complex queries is substantially reduced, as is their complexity. If you wish to learn more about the available functions you can visit the following URLs:
String functions: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html
Date and time: http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html
But, for easy reference, here are some of the most commonly used MySQL functions.
This excerpt is from Learning PHP, MySQL, and JavaScript . Discover how the powerful combination of PHP and MySQL provides an easy way to build modern websites complete with dynamic data and user interaction. You'll also learn how to add JavaScript to create rich Internet applications and websites.
CONCAT_WS()
CONCAT_WS(separator,str1,str2, ...)
This works in the same way as CONCAT except it inserts a separator between
the items being concatenated. If the separator is NULL the result will be NULL, but NULL values can be used as other arguments,
which will then be skipped. This code returns the string
“Truman,Harry,S”:
SELECT CONCAT_WS(',' 'Truman', 'Harry', 'S');MID()
MID(str,pos,len)
Returns up to len characters from the string str starting at position pos. If len is omitted, then all characters up to the end of the string are returned. You may use a negative value for pos, in which case it represents the character pos places from the end of the string. The first position in the string is 1. This code returns the string “stop”:
SELECT MID('Christopher Columbus', '6', '4');LPAD()
LPAD(str,len,padstr)
Returns the string str padded to a length of len characters by prepending the string with padstr characters. If str is longer than len then the string returned will be truncated to len characters. The example code returns the following strings:
January
February
March
April
MayNotice how all the strings have been padded to be eight characters long.
SELECT LPAD('January', '8', ' ');
SELECT LPAD('February', '8', ' ');
SELECT LPAD('March', '8', ' ');
SELECT LPAD('April', '8', ' ');
SELECT LPAD('May', '8', ' ');LOCATE()
LOCATE(substr,str,pos)
Returns the position of the first occurrence of substr in the string str. If the parameter pos is passed, the search begins at position pos. If substr is not found in str, a value of zero is returned. This code returns the values 5 and 11, because the first function call returns the first encounter of the word “unit”, while the second one only starts to search at the seventh character, and so returns the second instance:
SELECT LOCATE('unit', 'Community unit');
SELECT LOCATE('unit', 'Community unit' 7);QUOTE()
QUOTE(str)Returns a quoted string that can be used as a properly escaped
value in a SQL statement. The returned string is enclosed in single
quotes with all instances of single quotes, backslashes, the ASCII
NUL character, and Control-Z
preceded by a backslash. If the argument str is
NULL, the return value is the word
NULL without enclosing quotes. The example code returns the following
string:
'I\'m hungry'
Note how the " symbol has been replaced with
\".
SELECT QUOTE("I'm hungry");TRIM()
TRIM([specifierremoveFROM]str)
Returns the string str with all remove
prefixes or suffixes removed. The specifier can
be one of BOTH, LEADING, or TRAILING. If no
specifier is supplied, then BOTH is assumed. The
remove string is optional and, if omitted, spaces
are removed. This code returns the strings “No Padding” and
“Hello__”:
SELECT TRIM(' No Padding ');
SELECT TRIM(LEADING '_' FROM '__Hello__');Dates are an important part of most databases. Whenever financial transactions take place, the date has to be recorded, expiry dates of credit cards need to be noted for repeat billing purposes, and so on. So, as you might expect, MySQL comes with a wide variety of functions to make handling dates a breeze.
DATE_ADD()
DATE_ADD(date, INTERVALexprunit)
Returns the result of adding the expression
expr using units unit to the
date. The date argument is
the starting date or DATETIME value
and expr may start with a - symbol for negative intervals. Table D.1, “Expected expr values” shows the interval types supported
and the expected expr values. Note the examples
in this table that show where it is necessary to surround the
expr value with quotes for MySQL to correctly
interpret them. Although if you are ever in doubt, adding the quotes
will always work.
Table D.1. Expected expr values
Type | Expected expr value | Example |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
You can also use the DATE_SUB
function to subtract date intervals. However it’s not actually
necessary for you to use the DATE_ADD or DATE_SUB functions, as you can use date
arithmetic directly in MySQL. This code:
SELECT DATE_ADD('1975-01-01', INTERVAL 77 DAY);
SELECT DATE_SUB('1982-07-04', INTERVAL '3-11' YEAR_MONTH);
SELECT '2010-12-31 23:59:59' + INTERVAL 1 SECOND;
SELECT '2000-01-01' - INTERVAL 1 SECOND;returns the following values:
1975-03-19 1978-08-04 2011-01-01 00:00:00 1999-12-31 23:59:59
Notice how the last two commands use direct date arithmetic without recourse to functions.
DATE_FORMAT()
DATE_FORMAT(date,format)
This returns the date value formatted
according to the format string. Table D.2, “DATE_FORMAT specifiers” shows the specifiers that can be
used in the format string. Note that the % character is required before each
specifier, as shown. This code returns the given date and time as
“Thursday May 4th 2006 03:02 AM”:
SELECT DATE_FORMAT('2006-05-04 03:02:01', '%W %M %D %Y %h:%i %p');Table D.2. DATE_FORMAT specifiers
Specifier | Description |
|---|---|
| Abbreviated weekday name (Sun–Sat) |
| Abbreviated month name (Jan–Dec) |
| Month, numeric (0–12) |
| Day of the month with English suffix (0th, 1st, 2nd, 3rd, ...) |
| Day of the month, numeric (00–31) |
| Day of the month, numeric (0–31) |
| Microseconds (000000–999999) |
| Hour (00–23) |
| Hour (01–12) |
| Hour (01–12) |
| Minutes, numeric (00–59) |
| Day of year (001–366) |
| Hour (0–23) |
| Hour (1–12) |
| Month name (January–December) |
| Month, numeric (00–12) |
| AM or PM |
| Time, 12-hour (hh:mm:ss followed by AM or PM) |
| Seconds (00–59) |
| Seconds (00–59) |
| Time, 24-hour (hh:mm:ss) |
| Week (00–53), where Sunday is the first day of the week |
| Week (00–53), where Monday is the first day of the week |
| Week (01–53), where
Sunday is the first day of the week; used with |
| Week (01–53), where
Monday is the first day of the week; used with |
| Weekday name (Sunday–Saturday) |
| Day of the week (0=Sunday–6=Saturday) |
| Year for the week where
Sunday is the first day of the week, numeric, four digits;
used with |
| Year for the week,
where Monday is the first day of the week, numeric, four
digits; used with |
| Year, numeric, four digits |
| Year, numeric, two digits |
| A literal |
LAST_DAY()
LAST_DAY(date)Returns the last day of the month for the given DATETIME value date. If
the argument is invalid it returns NULL. This code:
SELECT LAST_DAY('2011-02-03');
SELECT LAST_DAY('2011-03-11');
SELECT LAST_DAY('2011-04-26');returns the following values:
2011-02-28 2011-03-31 2011-04-30
As you’d expect, it correctly returns the 28th day of February, the 31st of March, and the 30th of April 2011.
SYSDATE()
SYSDATE()
Returns the current date and time as a value in either
YYYY-MM-DD HH:MM:SS or YYYYMMDDHHMMSS format, depending on whether the
function is used in a string or numeric context. The function NOW works in a similar manner, except that
it returns the time and date only at the start of the current
statement, whereas SYSDATE returns
the time and date at the exact moment the function itself is called.
On December 19, 2011, this code returns the values 2011-12-19 19:11:13
and 20111219191113:
SELECT SYSDATE(); SELECT SYSDATE() + 0;
WEEK()
WEEK(date[,mode])
Returns the week number for date. If passed
the optional mode parameter, the week number
returned will be modified according to Table D.3, “The modes supported by the WEEK function”. You can also
use the function WEEKOFYEAR, which is equivalent to
using the WEEK function with a
mode of 3. This code returns the week number
14:
SELECT WEEK('2006-04-04', 1);Table D.3. The modes supported by the WEEK function
Mode | First day of week | Range | Where week 1 is the first week ... |
|---|---|---|---|
0 | Sunday | 0–53 | with a Sunday in this year |
1 | Monday | 0–53 | with more than 3 days this year |
2 | Sunday | 1–53 | with a Sunday in this year |
3 | Monday | 1–53 | with more than 3 days this year |
4 | Sunday | 0–53 | with more than 3 days this year |
5 | Monday | 0–53 | with a Monday in this year |
6 | Sunday | 1–53 | with more than 3 days this year |
7 | Monday | 1–53 | with a Monday in this year |
Sometimes you need to work with the time, rather than the date, and MySQL provides plenty of functions for you to do so.
CURTIME()
CURTIME()
Returns the current time as a value in the format HH:MM::SS or HHMMSS.uuuuuu, depending on whether the function is used in a string or numeric context. The value is expressed using the current time zone. When the current time is 11:56:23, this code returns the values 11:56:23 and 11:56:23.000000:
SELECT CURTIME() + 0;
UNIX_TIMESTAMP()
UNIX_TIMESTAMP([date])If called without the optional date
argument, this function returns the number of seconds since 1970-01-01
00:00:00 UTC as an unsigned integer. If the date
parameter is passed, then the value returned is the number of seconds
since the 1970 start date until the given date. This code will return
the value 946684800 (the number of seconds up to the start of the new
millennium) followed by a TIMESTAMP
representing the current Unix time at the moment you run it:
SELECT UNIX_TIMESTAMP('2000-01-01');
SELECT UNIX_TIMESTAMP();FROM_UNIXTIME()
FROM_UNIXTIME(unix_timestamp[,format])
Returns the unix_timestamp parameter as either a string in YYYY-MM-DD HH:MM:SS or YYYYMMDDHHMMSS.uuuuuu format, depending on whether the function is used in a string or numeric context. If the optional format parameter is provided, the result is formatted according to the specifiers in Table 8-17. This code returns the strings “2000-01-01 00:00:00” and “Saturday January 1st 2000 12:00 AM”:
SELECT FROM_UNIXTIME(946684800); SELECT FROM_UNIXTIME(946684800, '%W %M %D %Y %h:%i %p');
If you enjoyed this excerpt, buy a copy of Learning PHP, MySQL, & JavaScript.
Copyright © 2009 O'Reilly Media, Inc.