Source code editor What Is Ajax
↑
Name | Description |
---|---|
AES_DECRYPT() | Decrypt using AES |
AES_ENCRYPT() | Encrypt using AES |
BENCHMARK() | Repeatedly execute an expression |
BIT_COUNT() | Return the number of bits that are set |
& | Bitwise AND |
| | Bitwise OR |
^ | Bitwise XOR |
CHARSET() (v4.1.0) | Return the character set of the argument |
COERCIBILITY() (v4.1.1) | Return the collation coercibility value of the string argument |
COLLATION() (v4.1.0) | Return the collation of the string argument |
COMPRESS() (v4.1.1) | Return result as a binary string |
CONNECTION_ID() | Return the connection ID (thread ID) for the connection |
CURRENT_USER() , CURRENT_USER | Return the username and hostname combination |
DATABASE() | Return the default (current) database name |
DECODE() | Decodes a string encrypted using ENCODE() |
DEFAULT() | Return the default value for a table column |
DES_DECRYPT() | Decrypt a string |
DES_ENCRYPT() | Decrypt a string |
ENCODE() | Encode a string |
ENCRYPT() | Encrypt a string |
FOUND_ROWS() | For a SELECT with a LIMIT clause, the number of rows that would be returned were there no LIMIT clause |
GET_LOCK() | Get a named lock |
INET_ATON() | Return the numeric value of an IP address |
INET_NTOA() | Return the IP address from a numeric value |
IS_FREE_LOCK() | Checks whether the named lock is free |
IS_USED_LOCK() (v4.1.0) | Checks whether the named lock is in use. Return connection identifier if true. |
LAST_INSERT_ID() | Value of the AUTOINCREMENT column for the last INSERT |
<< | Left shift |
MASTER_POS_WAIT() | Block until the slave has read and applied all updates up to the specified position |
MD5() | Calculate MD5 checksum |
NAME_CONST() (v5.0.12) | Causes the column to have the given name |
OLD_PASSWORD() (v4.1) | Return the value of the old (pre-4.1) implementation of PASSWORD |
PASSWORD() | Calculate and return a password string |
RELEASE_LOCK() | Releases the named lock |
>> | Right shift |
ROW_COUNT() (v5.0.1) | The number of rows updated |
SCHEMA() (v5.0.2) | A synonym for DATABASE() |
SESSION_USER() | Synonym for USER() |
SHA1() , SHA() | Calculate an SHA-1 160-bit checksum |
SLEEP() (v5.0.12) | Sleep for a number of seconds |
SYSTEM_USER() | Synonym for USER() |
~ | Invert bits |
UNCOMPRESS() (v4.1.1) | Uncompress a string compressed |
UNCOMPRESSED_LENGTH() (v4.1.1) | Return the length of a string before compression |
USER() | Return the current username and hostname |
UUID() (v4.1.2) | Return a Universal Unique Identifier (UUID) |
VALUES() (v4.1.1) | Defines the values to be used during an INSERT |
Name | Description |
---|---|
BIT_COUNT() | Return the number of bits that are set |
& | Bitwise AND |
| | Bitwise OR |
^ | Bitwise XOR |
<< | Left shift |
>> | Right shift |
~ | Invert bits |
MySQL uses BIGINT
(64-bit) arithmetic for bit operations, so these operators have a maximum range of 64 bits.
Bitwise OR:
mysql> SELECT 29 | 15;
-> 31
The result is an unsigned 64-bit integer.
Bitwise AND:
mysql> SELECT 29 & 15;
-> 13
The result is an unsigned 64-bit integer.
Bitwise XOR:
mysql>SELECT 1 ^ 1;
-> 0 mysql>SELECT 1 ^ 0;
-> 1 mysql>SELECT 11 ^ 3;
-> 8
The result is an unsigned 64-bit integer.
Shifts a longlong (BIGINT
) number to the left.
mysql> SELECT 1 << 2;
-> 4
The result is an unsigned 64-bit integer.
Shifts a longlong (BIGINT
) number to the right.
mysql> SELECT 4 >> 2;
-> 1
The result is an unsigned 64-bit integer.
Invert all bits.
mysql> SELECT 5 & ~1;
-> 4
The result is an unsigned 64-bit integer.
Returns the number of bits that are set in the argument N
.
mysql> SELECT BIT_COUNT(29), BIT_COUNT(b'101010');
-> 4, 3
Name | Description |
---|---|
AES_DECRYPT() | Decrypt using AES |
AES_ENCRYPT() | Encrypt using AES |
COMPRESS() (v4.1.1) | Return result as a binary string |
DECODE() | Decodes a string encrypted using ENCODE() |
DES_DECRYPT() | Decrypt a string |
DES_ENCRYPT() | Decrypt a string |
ENCODE() | Encode a string |
ENCRYPT() | Encrypt a string |
MD5() | Calculate MD5 checksum |
OLD_PASSWORD() (v4.1) | Return the value of the old (pre-4.1) implementation of PASSWORD |
PASSWORD() | Calculate and return a password string |
SHA1() , SHA() | Calculate an SHA-1 160-bit checksum |
UNCOMPRESS() (v4.1.1) | Uncompress a string compressed |
UNCOMPRESSED_LENGTH() (v4.1.1) | Return the length of a string before compression |
The functions in this section perform encryption and decryption, and compression and uncompression:
Compression or encryption | Uncompression or decryption |
AES_ENCRYT() | AES_DECRYPT() |
COMPRESS() | UNCOMPRESS() |
ENCODE() | DECODE() |
DES_ENCRYPT() | DES_DECRYPT() |
ENCRYPT() | Not available |
MD5() | Not available |
OLD_PASSWORD() | Not available |
PASSWORD() | Not available |
SHA() or SHA1() | Not available |
Not available | UNCOMPRESSED_LENGTH() |
Note: The encryption and compression functions return binary strings. For many of these functions, the result might contain arbitrary byte values. If you want to store these results, use a BLOB
column rather than a CHAR
or (before MySQL 5.0.3) VARCHAR
column to avoid potential problems with trailing space removal that would change data values.
Note: Exploits for the MD5 and SHA-1 algorithms have become known. You may wish to consider using one of the other encryption functions described in this section instead.
AES_ENCRYPT(
, str
,key_str
)AES_DECRYPT(
crypt_str
,key_str
)
These functions allow encryption and decryption of data using the official AES (Advanced Encryption Standard) algorithm, previously known as “Rijndael.” Encoding with a 128-bit key length is used, but you can extend it up to 256 bits by modifying the source. We chose 128 bits because it is much faster and it is secure enough for most purposes.
AES_ENCRYPT()
encrypts a string and returns a binary string. AES_DECRYPT()
decrypts the encrypted string and returns the original string. The input arguments may be any length. If either argument is NULL
, the result of this function is also NULL
.
Because AES is a block-level algorithm, padding is used to encode uneven length strings and so the result string length may be calculated using this formula:
16 Ч (trunc(string_length
/ 16) + 1)
If AES_DECRYPT()
detects invalid data or incorrect padding, it returns NULL
. However, it is possible for AES_DECRYPT()
to return a non-NULL
value (possibly garbage) if the input data or the key is invalid.
You can use the AES functions to store data in an encrypted form by modifying your queries:
INSERT INTO t VALUES (1,AES_ENCRYPT('text','password'));
AES_ENCRYPT()
and AES_DECRYPT()
can be considered the most cryptographically secure encryption functions currently available in MySQL.
Compresses a string and returns the result as a binary string. This function requires MySQL to have been compiled with a compression library such as zlib
. Otherwise, the return value is always NULL
. The compressed string can be uncompressed with UNCOMPRESS()
.
mysql>SELECT LENGTH(COMPRESS(REPEAT('a',1000)));
-> 21 mysql>SELECT LENGTH(COMPRESS(''));
-> 0 mysql>SELECT LENGTH(COMPRESS('a'));
-> 13 mysql>SELECT LENGTH(COMPRESS(REPEAT('a',16)));
-> 15
The compressed string contents are stored the following way:
Empty strings are stored as empty strings.
Non-empty strings are stored as a four-byte length of the uncompressed string (low byte first), followed by the compressed string. If the string ends with space, an extra ‘.
’ character is added to avoid problems with endspace trimming should the result be stored in a CHAR
or VARCHAR
column. (Use of CHAR
or VARCHAR
to store compressed strings is not recommended. It is better to use a BLOB
column instead.)
Decrypts the encrypted string crypt_str
using pass_str
as the password. crypt_str
should be a string returned from ENCODE()
.
Encrypt str
using pass_str
as the password. To decrypt the result, use DECODE()
.
The result is a binary string of the same length as str
.
The strength of the encryption is based on how good the random generator is. It should suffice for short strings.
DES_DECRYPT(
crypt_str
[,key_str
])
Decrypts a string encrypted with DES_ENCRYPT()
. If an error occurs, this function returns NULL
.
Note that this function works only if MySQL has been configured with SSL support. See Section 5.8.7, “Using Secure Connections”.
If no key_str
argument is given, DES_DECRYPT()
examines the first byte of the encrypted string to determine the DES key number that was used to encrypt the original string, and then reads the key from the DES key file to decrypt the message. For this to work, the user must have the SUPER
privilege. The key file can be specified with the --des-key-file
server option.
If you pass this function a key_str
argument, that string is used as the key for decrypting the message.
If the crypt_str
argument does not appear to be an encrypted string, MySQL returns the given crypt_str
.
DES_ENCRYPT(
str
[,{key_num
|key_str
}])
Encrypts the string with the given key using the Triple-DES algorithm.
Note that this function works only if MySQL has been configured with SSL support. See Section 5.8.7, “Using Secure Connections”.
The encryption key to use is chosen based on the second argument to DES_ENCRYPT()
, if one was given:
Argument | Description |
No argument | The first key from the DES key file is used. |
key_num | The given key number (0-9) from the DES key file is used. |
key_str | The given key string is used to encrypt str . |
The key file can be specified with the --des-key-file
server option.
The return string is a binary string where the first character is CHAR(128 |
. If an error occurs, key_num
)DES_ENCRYPT()
returns NULL
.
The 128 is added to make it easier to recognize an encrypted key. If you use a string key, key_num
is 127.
The string length for the result is given by this formula:
new_len
=orig_len
+ (8 - (orig_len
% 8)) + 1
Each line in the DES key file has the following format:
key_num
des_key_str
Each key_num
value must be a number in the range from 0
to 9
. Lines in the file may be in any order. des_key_str
is the string that is used to encrypt the message. There should be at least one space between the number and the key. The first key is the default key that is used if you do not specify any key argument to DES_ENCRYPT()
.
You can tell MySQL to read new key values from the key file with the FLUSH DES_KEY_FILE
statement. This requires the RELOAD
privilege.
One benefit of having a set of default keys is that it gives applications a way to check for the existence of encrypted column values, without giving the end user the right to decrypt those values.
mysql>SELECT customer_address FROM customer_table
>WHERE crypted_credit_card = DES_ENCRYPT('credit_card_number');
Encrypts str
using the Unix crypt()
system call and returns a binary string. The salt
argument should be a string with at least two characters. If no salt
argument is given, a random value is used.
mysql> SELECT ENCRYPT('hello');
-> 'VxuFAJXVARROc'
ENCRYPT()
ignores all but the first eight characters of str
, at least on some systems. This behavior is determined by the implementation of the underlying crypt()
system call.
The use of ENCYPT()
with multi-byte character sets other than utf8
is not recommended because the system call expects a string terminated by a zero byte.
If crypt()
is not available on your system (as is the case with Windows), ENCRYPT()
always returns NULL
.
Calculates an MD5 128-bit checksum for the string. The value is returned as a binary string of 32 hex digits, or NULL
if the argument was NULL
. The return value can, for example, be used as a hash key.
mysql> SELECT MD5('testing');
-> 'ae2b1fca515949e5d54fb22b8ed95575'
This is the “RSA Data Security, Inc. MD5 Message-Digest Algorithm.”
If you want to convert the value to uppercase, see the description of binary string conversion given in the entry for the BINARY
operator in Section 12.9, “Cast Functions and Operators”.
See the note regarding the MD5 algorithm at the beginning this section.
OLD_PASSWORD()
was added to MySQL when the implementation of PASSWORD()
was changed to improve security. OLD_PASSWORD()
returns the value of the old (pre-4.1) implementation of PASSWORD()
as a binary string, and is intended to permit you to reset passwords for any pre-4.1 clients that need to connect to your version 5.0 MySQL server without locking them out. See Section 5.7.9, “Password Hashing as of MySQL 4.1”.
Calculates and returns a password string from the plaintext password str
and returns a binary string, or NULL
if the argument was NULL
. This is the function that is used for encrypting MySQL passwords for storage in the Password
column of the user
grant table.
mysql> SELECT PASSWORD('badpwd');
-> '*AAB3E285149C0135D51A520E1940DD3263DC008C'
PASSWORD()
encryption is one-way (not reversible).
PASSWORD()
does not perform password encryption in the same way that Unix passwords are encrypted. See ENCRYPT()
.
Note: The PASSWORD()
function is used by the authentication system in MySQL Server; you should not use it in your own applications. For that purpose, consider MD5()
or SHA1()
instead. Also see RFC 2195, section 2 (Challenge-Response Authentication Mechanism (CRAM)), for more information about handling passwords and authentication securely in your applications.
Calculates an SHA-1 160-bit checksum for the string, as described in RFC 3174 (Secure Hash Algorithm). The value is returned as a binary string of 40 hex digits, or NULL
if the argument was NULL
. One of the possible uses for this function is as a hash key. You can also use it as a cryptographic function for storing passwords. SHA()
is synonymous with SHA1()
.
mysql> SELECT SHA1('abc');
-> 'a9993e364706816aba3e25717850c26c9cd0d89d'
SHA1()
can be considered a cryptographically more secure equivalent of MD5()
. However, see the note regarding the MD5 and SHA-1 algorithms at the beginning this section.
UNCOMPRESS(
string_to_uncompress
)
Uncompresses a string compressed by the COMPRESS()
function. If the argument is not a compressed value, the result is NULL
. This function requires MySQL to have been compiled with a compression library such as zlib
. Otherwise, the return value is always NULL
.
mysql>SELECT UNCOMPRESS(COMPRESS('any string'));
-> 'any string' mysql>SELECT UNCOMPRESS('any string');
-> NULL
UNCOMPRESSED_LENGTH(
compressed_string
)
Returns the length that the compressed string had before being compressed.
mysql> SELECT UNCOMPRESSED_LENGTH(COMPRESS(REPEAT('a',30)));
-> 30
Name | Description |
---|---|
BENCHMARK() | Repeatedly execute an expression |
CHARSET() (v4.1.0) | Return the character set of the argument |
COERCIBILITY() (v4.1.1) | Return the collation coercibility value of the string argument |
COLLATION() (v4.1.0) | Return the collation of the string argument |
CONNECTION_ID() | Return the connection ID (thread ID) for the connection |
CURRENT_USER() , CURRENT_USER | Return the username and hostname combination |
DATABASE() | Return the default (current) database name |
FOUND_ROWS() | For a SELECT with a LIMIT clause, the number of rows that would be returned were there no LIMIT clause |
LAST_INSERT_ID() | Value of the AUTOINCREMENT column for the last INSERT |
ROW_COUNT() (v5.0.1) | The number of rows updated |
SCHEMA() (v5.0.2) | A synonym for DATABASE() |
SESSION_USER() | Synonym for USER() |
SYSTEM_USER() | Synonym for USER() |
USER() | Return the current username and hostname |
The BENCHMARK()
function executes the expression expr
repeatedly count
times. It may be used to time how quickly MySQL processes the expression. The result value is always 0
. The intended use is from within the mysql client, which reports query execution times:
mysql> SELECT BENCHMARK(1000000,ENCODE('hello','goodbye'));
+----------------------------------------------+
| BENCHMARK(1000000,ENCODE('hello','goodbye')) |
+----------------------------------------------+
| 0 |
+----------------------------------------------+
1 row in set (4.74 sec)
The time reported is elapsed time on the client end, not CPU time on the server end. It is advisable to execute BENCHMARK()
several times, and to interpret the result with regard to how heavily loaded the server machine is.
BENCHMARK()
is intended for measuring the runtime performance of scalar expressions, which has some significant implications for the way that you use it and interpret the results:
Only scalar expressions can be used. Although the expression can be a subquery, it must return a single column and at most a single row. For example, BENCHMARK(10, (SELECT * FROM t))
will fail if the table t
has more than one column or more than one row.
Executing a SELECT
statement expr
N
times differs from executing SELECT BENCHMARK(
in terms of the amount of overhead involved. The two have very different execution profiles and you should not expect them to take the same amount of time. The former involves the parser, optimizer, table locking, and runtime evaluation N
, expr
)N
times each. The latter involves only runtime evaluation N
times, and all the other components just once. Memory structures already allocated are reused, and runtime optimizations such as local caching of results already evaluated for aggregate functions can alter the results. Use of BENCHMARK()
thus measures performance of the runtime component by giving more weight to that component and removing the “noise” introduced by the network, parser, optimizer, and so forth.
Returns the character set of the string argument.
mysql>SELECT CHARSET('abc');
-> 'latin1' mysql>SELECT CHARSET(CONVERT('abc' USING utf8));
-> 'utf8' mysql>SELECT CHARSET(USER());
-> 'utf8'
Returns the collation coercibility value of the string argument.
mysql>SELECT COERCIBILITY('abc' COLLATE latin1_swedish_ci);
-> 0 mysql>SELECT COERCIBILITY(USER());
-> 3 mysql>SELECT COERCIBILITY('abc');
-> 4
The return values have the meanings shown in the following table. Lower values have higher precedence.
Coercibility | Meaning | Example |
0 | Explicit collation | Value with COLLATE clause |
1 | No collation | Concatenation of strings with different collations |
2 | Implicit collation | Column value |
3 | System constant | USER() return value |
4 | Coercible | Literal string |
5 | Ignorable | NULL or an expression derived from NULL |
Before MySQL 5.0.3, the return values are shown as follows, and functions such as USER()
have a coercibility of 2:
Coercibility | Meaning | Example |
0 | Explicit collation | Value with COLLATE clause |
1 | No collation | Concatenation of strings with different collations |
2 | Implicit collation | Column value, stored routine parameter or local variable |
3 | Coercible | Literal string |
Returns the collation of the string argument.
mysql>SELECT COLLATION('abc');
-> 'latin1_swedish_ci' mysql>SELECT COLLATION(_utf8'abc');
-> 'utf8_general_ci'
Returns the connection ID (thread ID) for the connection. Every connection has an ID that is unique among the set of currently connected clients.
mysql> SELECT CONNECTION_ID();
-> 23786
Returns the username and hostname combination for the MySQL account that the server used to authenticate the current client. This account determines your access privileges. As of MySQL 5.0.10, within a stored routine that is defined with the SQL SECURITY DEFINER
characteristic, CURRENT_USER()
returns the creator of the routine. The return value is a string in the utf8
character set.
The value of CURRENT_USER()
can differ from the value of USER()
.
mysql>SELECT USER();
-> 'davida@localhost' mysql>SELECT * FROM mysql.user;
ERROR 1044: Access denied for user ''@'localhost' to database 'mysql' mysql>SELECT CURRENT_USER();
-> '@localhost'
The example illustrates that although the client specified a username of davida
(as indicated by the value of the USER()
function), the server authenticated the client using an anonymous user account (as seen by the empty username part of the CURRENT_USER()
value). One way this might occur is that there is no account listed in the grant tables for davida
.
Returns the default (current) database name as a string in the utf8
character set. If there is no default database, DATABASE()
returns NULL
. Within a stored routine, the default database is the database that the routine is associated with, which is not necessarily the same as the database that is the default in the calling context.
mysql> SELECT DATABASE();
-> 'test'
A SELECT
statement may include a LIMIT
clause to restrict the number of rows the server returns to the client. In some cases, it is desirable to know how many rows the statement would have returned without the LIMIT
, but without running the statement again. To obtain this row count, include a SQL_CALC_FOUND_ROWS
option in the SELECT
statement, and then invoke FOUND_ROWS()
afterward:
mysql>SELECT SQL_CALC_FOUND_ROWS * FROM
->tbl_name
WHERE id > 100 LIMIT 10;
mysql>SELECT FOUND_ROWS();
The second SELECT
returns a number indicating how many rows the first SELECT
would have returned had it been written without the LIMIT
clause.
In the absence of the SQL_CALC_FOUND_ROWS
option in the most recent SELECT
statement, FOUND_ROWS()
returns the number of rows in the result set returned by that statement.
The row count available through FOUND_ROWS()
is transient and not intended to be available past the statement following the SELECT SQL_CALC_FOUND_ROWS
statement. If you need to refer to the value later, save it:
mysql>SELECT SQL_CALC_FOUND_ROWS * FROM ... ;
mysql>SET @rows = FOUND_ROWS();
If you are using SELECT SQL_CALC_FOUND_ROWS
, MySQL must calculate how many rows are in the full result set. However, this is faster than running the query again without LIMIT
, because the result set need not be sent to the client.
SQL_CALC_FOUND_ROWS
and FOUND_ROWS()
can be useful in situations when you want to restrict the number of rows that a query returns, but also determine the number of rows in the full result set without running the query again. An example is a Web script that presents a paged display containing links to the pages that show other sections of a search result. Using FOUND_ROWS()
allows you to determine how many other pages are needed for the rest of the result.
The use of SQL_CALC_FOUND_ROWS
and FOUND_ROWS()
is more complex for UNION
statements than for simple SELECT
statements, because LIMIT
may occur at multiple places in a UNION
. It may be applied to individual SELECT
statements in the UNION
, or global to the UNION
result as a whole.
The intent of SQL_CALC_FOUND_ROWS
for UNION
is that it should return the row count that would be returned without a global LIMIT
. The conditions for use of SQL_CALC_FOUND_ROWS
with UNION
are:
The SQL_CALC_FOUND_ROWS
keyword must appear in the first SELECT
of the UNION
.
The value of FOUND_ROWS()
is exact only if UNION ALL
is used. If UNION
without ALL
is used, duplicate removal occurs and the value of FOUND_ROWS()
is only approximate.
If no LIMIT
is present in the UNION
, SQL_CALC_FOUND_ROWS
is ignored and returns the number of rows in the temporary table that is created to process the UNION
.
LAST_INSERT_ID()
, LAST_INSERT_ID(
expr
)
LAST_INSERT_ID()
(with no argument) returns the first automatically generated value that was set for an AUTO_INCREMENT
column by the most recently executed INSERT
statement to affect such a column. For example, after inserting a row that generates an AUTO_INCREMENT
value, you can get the value like this:
mysql> SELECT LAST_INSERT_ID();
-> 195
The currently executing statement does not affect the value of LAST_INSERT_ID()
. Suppose that you generate an AUTO_INCREMENT
value with one statement, and then refer to LAST_INSERT_ID()
in a multiple-row INSERT
statement that inserts rows into a table with its own AUTO_INCREMENT
column. The value of LAST_INSERT_ID()
will remain stable in the second statement; its value for the second and later rows is not affected by the earlier row insertions. (However, if you mix references to LAST_INSERT_ID()
and LAST_INSERT_ID(
, the effect is undefined.) expr
)
If the previous statement returned an error, the value of LAST_INSERT_ID()
is undefined. For transactional tables, if the statement is rolled back due to an error, the value of LAST_INSERT_ID()
is left undefined. For manual ROLLBACK
, the value of LAST_INSERT_ID()
is not restored to that before the transaction; it remains as it was at the point of the ROLLBACK
.
Within the body of a stored routine (procedure or function) or a trigger, the value of LAST_INSERT_ID()
changes the same way as for statements executed outside the body of these kinds of objects. The effect of a stored routine or trigger upon the value of LAST_INSERT_ID()
that is seen by following statements depends on the kind of routine:
If a stored procedure executes statements that change the value of LAST_INSERT_ID()
, the changed value will be seen by statements that follow the procedure call.
For stored functions and triggers that change the value, the value is restored when the function or trigger ends, so following statements will not see a changed value.
The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT
value generated for most recent statement affecting an AUTO_INCREMENT
column by that client. This value cannot be affected by other clients, even if they generate AUTO_INCREMENT
values of their own. This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions.
The value of LAST_INSERT_ID()
is not changed if you set the AUTO_INCREMENT
column of a row to a non-“magic” value (that is, a value that is not NULL
and not 0
).
Important: If you insert multiple rows using a single INSERT
statement, LAST_INSERT_ID()
returns the value generated for the first inserted row only. The reason for this is to make it possible to reproduce easily the same INSERT
statement against some other server.
For example:
mysql>USE test;
Database changed mysql>CREATE TABLE t (
->id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
->name VARCHAR(10) NOT NULL
->);
Query OK, 0 rows affected (0.09 sec) mysql>INSERT INTO t VALUES (NULL, 'Bob');
Query OK, 1 row affected (0.01 sec) mysql>SELECT * FROM t;
+----+------+ | id | name | +----+------+ | 1 | Bob | +----+------+ 1 row in set (0.01 sec) mysql>SELECT LAST_INSERT_ID();
+------------------+ | LAST_INSERT_ID() | +------------------+ | 1 | +------------------+ 1 row in set (0.00 sec) mysql>INSERT INTO t VALUES
->(NULL, 'Mary'), (NULL, 'Jane'), (NULL, 'Lisa');
Query OK, 3 rows affected (0.00 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> SELECT * FROM t; +----+------+ | id | name | +----+------+ | 1 | Bob | | 2 | Mary | | 3 | Jane | | 4 | Lisa | +----+------+ 4 rows in set (0.01 sec) mysql>SELECT LAST_INSERT_ID();
+------------------+ | LAST_INSERT_ID() | +------------------+ | 2 | +------------------+ 1 row in set (0.00 sec)
Although the second INSERT
statement inserted three new rows into t
, the ID generated for the first of these rows was 2
, and it is this value that is returned by LAST_INSERT_ID()
for the following SELECT
statement.
If you use INSERT IGNORE
and the row is ignored, the AUTO_INCREMENT
counter is not incremented and LAST_INSERT_ID()
returns 0
, which reflects that no row was inserted.
If expr
is given as an argument to LAST_INSERT_ID()
, the value of the argument is returned by the function and is remembered as the next value to be returned by LAST_INSERT_ID()
. This can be used to simulate sequences:
Create a table to hold the sequence counter and initialize it:
mysql>CREATE TABLE sequence (id INT NOT NULL);
mysql>INSERT INTO sequence VALUES (0);
Use the table to generate sequence numbers like this:
mysql>UPDATE sequence SET id=LAST_INSERT_ID(id+1);
mysql>SELECT LAST_INSERT_ID();
The UPDATE
statement increments the sequence counter and causes the next call to LAST_INSERT_ID()
to return the updated value. The SELECT
statement retrieves that value. The mysql_insert_id()
C API function can also be used to get the value. See Section 22.2.3.37, “mysql_insert_id()
”.
You can generate sequences without calling LAST_INSERT_ID()
, but the utility of using the function this way is that the ID value is maintained in the server as the last automatically generated value. It is multi-user safe because multiple clients can issue the UPDATE
statement and get their own sequence value with the SELECT
statement (or mysql_insert_id()
), without affecting or being affected by other clients that generate their own sequence values.
Note that mysql_insert_id()
is only updated after INSERT
and UPDATE
statements, so you cannot use the C API function to retrieve the value for LAST_INSERT_ID(
after executing other SQL statements like expr
)SELECT
or SET
.
ROW_COUNT()
returns the number of rows updated, inserted, or deleted by the preceding statement. This is the same as the row count that the mysql client displays and the value from the mysql_affected_rows()
C API function.
mysql>INSERT INTO t VALUES(1),(2),(3);
Query OK, 3 rows affected (0.00 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql>SELECT ROW_COUNT();
+-------------+ | ROW_COUNT() | +-------------+ | 3 | +-------------+ 1 row in set (0.00 sec) mysql>DELETE FROM t WHERE i IN(1,2);
Query OK, 2 rows affected (0.00 sec) mysql>SELECT ROW_COUNT();
+-------------+ | ROW_COUNT() | +-------------+ | 2 | +-------------+ 1 row in set (0.00 sec)
ROW_COUNT()
was added in MySQL 5.0.1.
This function is a synonym for DATABASE()
. It was added in MySQL 5.0.2.
SESSION_USER()
is a synonym for USER()
.
SYSTEM_USER()
is a synonym for USER()
.
Returns the current MySQL username and hostname as a string in the utf8
character set.
mysql> SELECT USER();
-> 'davida@localhost'
The value indicates the username you specified when connecting to the server, and the client host from which you connected. The value can be different from that of CURRENT_USER()
.
You can extract only the username part like this:
mysql> SELECT SUBSTRING_INDEX(USER(),'@',1);
-> 'davida'
Returns a string that indicates the MySQL server version. The string uses the utf8
character set.
mysql> SELECT VERSION();
-> '5.0.46-standard'
Note that if your version string ends with -log
this means that logging is enabled.
Name | Description |
---|---|
DEFAULT() | Return the default value for a table column |
GET_LOCK() | Get a named lock |
INET_ATON() | Return the numeric value of an IP address |
INET_NTOA() | Return the IP address from a numeric value |
IS_FREE_LOCK() | Checks whether the named lock is free |
IS_USED_LOCK() (v4.1.0) | Checks whether the named lock is in use. Return connection identifier if true. |
MASTER_POS_WAIT() | Block until the slave has read and applied all updates up to the specified position |
NAME_CONST() (v5.0.12) | Causes the column to have the given name |
RELEASE_LOCK() | Releases the named lock |
SLEEP() (v5.0.12) | Sleep for a number of seconds |
UUID() (v4.1.2) | Return a Universal Unique Identifier (UUID) |
VALUES() (v4.1.1) | Defines the values to be used during an INSERT |
Returns the default value for a table column. Starting with MySQL 5.0.2, an error results if the column has no default value.
mysql> UPDATE t SET i = DEFAULT(i)+1 WHERE id < 100;
FORMAT(
X
,D
)
Formats the number X
to a format like '#,###,###.##'
, rounded to D
decimal places, and returns the result as a string. For details, see Section 12.4, “String Functions”.
Tries to obtain a lock with a name given by the string str
, using a timeout of timeout
seconds. Returns 1
if the lock was obtained successfully, 0
if the attempt timed out (for example, because another client has previously locked the name), or NULL
if an error occurred (such as running out of memory or the thread was killed with mysqladmin kill). If you have a lock obtained with GET_LOCK()
, it is released when you execute RELEASE_LOCK()
, execute a new GET_LOCK()
, or your connection terminates (either normally or abnormally). Locks obtained with GET_LOCK()
do not interact with transactions. That is, committing a transaction does not release any such locks obtained during the transaction.
This function can be used to implement application locks or to simulate record locks. Names are locked on a server-wide basis. If a name has been locked by one client, GET_LOCK()
blocks any request by another client for a lock with the same name. This allows clients that agree on a given lock name to use the name to perform cooperative advisory locking. But be aware that it also allows a client that is not among the set of cooperating clients to lock a name, either inadvertently or deliberately, and thus prevent any of the cooperating clients from locking that name. One way to reduce the likelihood of this is to use lock names that are database-specific or application-specific. For example, use lock names of the form db_name.str
or app_name.str
.
mysql>SELECT GET_LOCK('lock1',10);
-> 1 mysql>SELECT IS_FREE_LOCK('lock2');
-> 1 mysql>SELECT GET_LOCK('lock2',10);
-> 1 mysql>SELECT RELEASE_LOCK('lock2');
-> 1 mysql>SELECT RELEASE_LOCK('lock1');
-> NULL
The second RELEASE_LOCK()
call returns NULL
because the lock 'lock1'
was automatically released by the second GET_LOCK()
call.
Note: If a client attempts to acquire a lock that is already held by another client, it blocks according to the timeout
argument. If the blocked client terminates, its thread does not die until the lock request times out. This is a known bug.
Given the dotted-quad representation of a network address as a string, returns an integer that represents the numeric value of the address. Addresses may be 4- or 8-byte addresses.
mysql> SELECT INET_ATON('209.207.224.40');
-> 3520061480
The generated number is always in network byte order. For the example just shown, the number is calculated as 209Ч2563 + 207Ч2562 + 224Ч256 + 40.
INET_ATON()
also understands short-form IP addresses:
mysql> SELECT INET_ATON('127.0.0.1'), INET_ATON('127.1');
-> 2130706433, 2130706433
Note: When storing values generated by INET_ATON()
, it is recommended that you use an INT UNSIGNED
column. If you use a (signed) INT
column, values corresponding to IP addresses for which the first octet is greater than 127 cannot be stored correctly. See Section 11.2, “Numeric Types”.
Given a numeric network address (4 or 8 byte), returns the dotted-quad representation of the address as a string.
mysql> SELECT INET_NTOA(3520061480);
-> '209.207.224.40'
Checks whether the lock named str
is free to use (that is, not locked). Returns 1
if the lock is free (no one is using the lock), 0
if the lock is in use, and NULL
if an error occurs (such as an incorrect argument).
Checks whether the lock named str
is in use (that is, locked). If so, it returns the connection identifier of the client that holds the lock. Otherwise, it returns NULL
.
MASTER_POS_WAIT(
log_name
,log_pos
[,timeout
])
This function is useful for control of master/slave synchronization. It blocks until the slave has read and applied all updates up to the specified position in the master log. The return value is the number of log events the slave had to wait for to advance to the specified position. The function returns NULL
if the slave SQL thread is not started, the slave's master information is not initialized, the arguments are incorrect, or an error occurs. It returns -1
if the timeout has been exceeded. If the slave SQL thread stops while MASTER_POS_WAIT()
is waiting, the function returns NULL
. If the slave is past the specified position, the function returns immediately.
If a timeout
value is specified, MASTER_POS_WAIT()
stops waiting when timeout
seconds have elapsed. timeout
must be greater than 0; a zero or negative timeout
means no timeout.
Returns the given value. When used to produce a result set column, NAME_CONST()
causes the column to have the given name.
mysql> SELECT NAME_CONST('myname', 14);
+--------+
| myname |
+--------+
| 14 |
+--------+
This function was added in MySQL 5.0.12. It is for internal use only. The server uses it when writing statements from stored routines that contain references to local routine variables, as described in Section 17.4, “Binary Logging of Stored Routines and Triggers”, You might see this function in the output from mysqlbinlog.
Releases the lock named by the string str
that was obtained with GET_LOCK()
. Returns 1
if the lock was released, 0
if the lock was not established by this thread (in which case the lock is not released), and NULL
if the named lock did not exist. The lock does not exist if it was never obtained by a call to GET_LOCK()
or if it has previously been released.
The DO
statement is convenient to use with RELEASE_LOCK()
. See Section 13.2.2, “DO
Syntax”.
Sleeps (pauses) for the number of seconds given by the duration
argument, then returns 0. If SLEEP()
is interrupted, it returns 1. The duration may have a fractional part given in microseconds. This function was added in MySQL 5.0.12.
Returns a Universal Unique Identifier (UUID) generated according to “DCE 1.1: Remote Procedure Call” (Appendix A) CAE (Common Applications Environment) Specifications published by The Open Group in October 1997 (Document Number C706, http://www.opengroup.org/public/pubs/catalog/c706.htm).
A UUID is designed as a number that is globally unique in space and time. Two calls to UUID()
are expected to generate two different values, even if these calls are performed on two separate computers that are not connected to each other.
A UUID is a 128-bit number represented by a string of five hexadecimal numbers in aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee
format:
The first three numbers are generated from a timestamp.
The fourth number preserves temporal uniqueness in case the timestamp value loses monotonicity (for example, due to daylight saving time).
The fifth number is an IEEE 802 node number that provides spatial uniqueness. A random number is substituted if the latter is not available (for example, because the host computer has no Ethernet card, or we do not know how to find the hardware address of an interface on your operating system). In this case, spatial uniqueness cannot be guaranteed. Nevertheless, a collision should have very low probability.
Currently, the MAC address of an interface is taken into account only on FreeBSD and Linux. On other operating systems, MySQL uses a randomly generated 48-bit number.
mysql> SELECT UUID();
-> '6ccd780c-baba-1026-9564-0040f4311e29'
Note that UUID()
does not yet work with replication.
In an INSERT ... ON DUPLICATE KEY UPDATE
statement, you can use the VALUES(
function in the col_name
)UPDATE
clause to refer to column values from the INSERT
portion of the statement. In other words, VALUES(
in the col_name
)UPDATE
clause refers to the value of col_name
that would be inserted, had no duplicate-key conflict occurred. This function is especially useful in multiple-row inserts. The VALUES()
function is meaningful only in INSERT ... ON DUPLICATE KEY UPDATE
statements and returns NULL
otherwise. Section 13.2.4.3, “INSERT ... ON DUPLICATE KEY UPDATE
Syntax”.
mysql>INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6)
->ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b);