Rechercher dans le manuel MySQL
12.15 Information Functions
Table 12.19 Information Functions
Name | Description |
---|---|
BENCHMARK() |
Repeatedly execute an expression |
CHARSET() |
Return the character set of the argument |
COERCIBILITY() |
Return the collation coercibility value of the string argument |
COLLATION() |
Return the collation of the string argument |
CONNECTION_ID() |
Return the connection ID (thread ID) for the connection |
CURRENT_ROLE() |
Returns the current active roles |
CURRENT_USER() , CURRENT_USER |
The authenticated user name and host name |
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 |
ICU_VERSION() |
ICU library version |
LAST_INSERT_ID() |
Value of the AUTOINCREMENT column for the last INSERT |
ROLES_GRAPHML() |
Returns a GraphML document representing memory role subgraphs |
ROW_COUNT() |
The number of rows updated |
SCHEMA() |
Synonym for DATABASE() |
SESSION_USER() |
Synonym for USER() |
SYSTEM_USER() |
Synonym for USER() |
USER() |
The user name and host name provided by the client |
VERSION() |
Return a string that indicates the MySQL server version |
The
BENCHMARK()
function executes the expressionexpr
repeatedlycount
times. It may be used to time how quickly MySQL processes the expression. The result value is always0
. The intended use is from within the mysql client, which reports query execution times:- +---------------------------------------------------+
- +---------------------------------------------------+
- | 0 |
- +---------------------------------------------------+
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 tablet
has more than one column or more than one row.Executing a
SELECT
statementexpr
N
times differs from executingSELECT 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 evaluationN
,expr
)N
times each. The latter involves only runtime evaluationN
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 ofBENCHMARK()
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.
Returns the collation coercibility value of the string argument.
- -> 0
- -> 3
- -> 4
- -> 5
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
clause1
No collation Concatenation of strings with different collations 2
Implicit collation Column value, stored routine parameter or local variable 3
System constant USER()
return value4
Coercible Literal string 5
Numeric Numeric or temporal value 5
Ignorable NULL
or an expression derived fromNULL
For more information, see Section 10.8.4, “Collation Coercibility in Expressions”.
Returns the collation of the string argument.
Returns the connection ID (thread ID) for the connection. Every connection has an ID that is unique among the set of currently connected clients.
The value returned by
CONNECTION_ID()
is the same type of value as displayed in theID
column of theINFORMATION_SCHEMA.PROCESSLIST
table, theId
column ofSHOW PROCESSLIST
output, and thePROCESSLIST_ID
column of the Performance Schemathreads
table.- -> 23786
Returns a
utf8
string containing the current active roles for the current session, separated by commas, orNONE
if there are none. The value reflects the setting of thesql_quote_show_create
system variable.Suppose that an account is granted roles as follows:
In sessions for
u1
, the initialCURRENT_ROLE()
value names the default account roles. UsingSET ROLE
changes that:Returns the user name and host name combination for the MySQL account that the server used to authenticate the current client. This account determines your access privileges. The return value is a string in the
utf8
character set.The value of
CURRENT_USER()
can differ from the value ofUSER()
.- -> 'davida@localhost'
- database 'mysql'
- -> '@localhost'
The example illustrates that although the client specified a user name of
davida
(as indicated by the value of theUSER()
function), the server authenticated the client using an anonymous user account (as seen by the empty user name part of theCURRENT_USER()
value). One way this might occur is that there is no account listed in the grant tables fordavida
.Within a stored program or view,
CURRENT_USER()
returns the account for the user who defined the object (as given by itsDEFINER
value) unless defined with theSQL SECURITY INVOKER
characteristic. In the latter case,CURRENT_USER()
returns the object's invoker.Triggers and events have no option to define the
SQL SECURITY
characteristic, so for these objects,CURRENT_USER()
returns the account for the user who defined the object. To return the invoker, useUSER()
orSESSION_USER()
.The following statements support use of the
CURRENT_USER()
function to take the place of the name of (and, possibly, a host for) an affected user or a definer; in such cases,CURRENT_USER()
is expanded where and as needed:For information about the implications that this expansion of
CURRENT_USER()
has for replication, see Section 17.4.1.8, “Replication of CURRENT_USER()”.Returns the default (current) database name as a string in the
utf8
character set. If there is no default database,DATABASE()
returnsNULL
. 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.If there is no default database,
DATABASE()
returnsNULL
.A
SELECT
statement may include aLIMIT
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 theLIMIT
, but without running the statement again. To obtain this row count, include anSQL_CALC_FOUND_ROWS
option in theSELECT
statement, and then invokeFOUND_ROWS()
afterward:The second
SELECT
returns a number indicating how many rows the firstSELECT
would have returned had it been written without theLIMIT
clause.In the absence of the
SQL_CALC_FOUND_ROWS
option in the most recent successfulSELECT
statement,FOUND_ROWS()
returns the number of rows in the result set returned by that statement. If the statement includes aLIMIT
clause,FOUND_ROWS()
returns the number of rows up to the limit. For example,FOUND_ROWS()
returns 10 or 60, respectively, if the statement includesLIMIT 10
orLIMIT 50, 10
.The row count available through
FOUND_ROWS()
is transient and not intended to be available past the statement following theSELECT SQL_CALC_FOUND_ROWS
statement. If you need to refer to the value later, save it: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 withoutLIMIT
, because the result set need not be sent to the client.SQL_CALC_FOUND_ROWS
andFOUND_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. UsingFOUND_ROWS()
enables you to determine how many other pages are needed for the rest of the result.The use of
SQL_CALC_FOUND_ROWS
andFOUND_ROWS()
is more complex forUNION
statements than for simpleSELECT
statements, becauseLIMIT
may occur at multiple places in aUNION
. It may be applied to individualSELECT
statements in theUNION
, or global to theUNION
result as a whole.The intent of
SQL_CALC_FOUND_ROWS
forUNION
is that it should return the row count that would be returned without a globalLIMIT
. The conditions for use ofSQL_CALC_FOUND_ROWS
withUNION
are:The
SQL_CALC_FOUND_ROWS
keyword must appear in the firstSELECT
of theUNION
.The value of
FOUND_ROWS()
is exact only ifUNION ALL
is used. IfUNION
withoutALL
is used, duplicate removal occurs and the value ofFOUND_ROWS()
is only approximate.If no
LIMIT
is present in theUNION
,SQL_CALC_FOUND_ROWS
is ignored and returns the number of rows in the temporary table that is created to process theUNION
.
Beyond the cases described here, the behavior of
FOUND_ROWS()
is undefined (for example, its value following aSELECT
statement that fails with an error).ImportantFOUND_ROWS()
is not replicated reliably using statement-based replication. This function is automatically replicated using row-based replication.The version of the International Components for Unicode (ICU) library used to support regular expression operations (see Section 12.5.2, “Regular Expressions”). This function is primarily intended for use in test cases.
LAST_INSERT_ID()
,LAST_INSERT_ID(
expr
)With no argument,
LAST_INSERT_ID()
returns aBIGINT UNSIGNED
(64-bit) value representing the first automatically generated value successfully inserted for anAUTO_INCREMENT
column as a result of the most recently executedINSERT
statement. The value ofLAST_INSERT_ID()
remains unchanged if no rows are successfully inserted.With an argument,
LAST_INSERT_ID()
returns an unsigned integer.For example, after inserting a row that generates an
AUTO_INCREMENT
value, you can get the value like this:- -> 195
The currently executing statement does not affect the value of
LAST_INSERT_ID()
. Suppose that you generate anAUTO_INCREMENT
value with one statement, and then refer toLAST_INSERT_ID()
in a multiple-rowINSERT
statement that inserts rows into a table with its ownAUTO_INCREMENT
column. The value ofLAST_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 toLAST_INSERT_ID()
andLAST_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 ofLAST_INSERT_ID()
is left undefined. For manualROLLBACK
, the value ofLAST_INSERT_ID()
is not restored to that before the transaction; it remains as it was at the point of theROLLBACK
.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 ofLAST_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 is 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 anAUTO_INCREMENT
column by that client. This value cannot be affected by other clients, even if they generateAUTO_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 theAUTO_INCREMENT
column of a row to a non-“magic” value (that is, a value that is notNULL
and not0
).ImportantIf 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 sameINSERT
statement against some other server.For example:
- );
- +----+------+
- | id | name |
- +----+------+
- | 1 | Bob |
- +----+------+
- +------------------+
- +------------------+
- | 1 |
- +------------------+
- +----+------+
- | id | name |
- +----+------+
- | 1 | Bob |
- | 2 | Mary |
- | 3 | Jane |
- | 4 | Lisa |
- +----+------+
- +------------------+
- +------------------+
- | 2 |
- +------------------+
Although the second
INSERT
statement inserted three new rows intot
, the ID generated for the first of these rows was2
, and it is this value that is returned byLAST_INSERT_ID()
for the followingSELECT
statement.If you use
INSERT IGNORE
and the row is ignored, theLAST_INSERT_ID()
remains unchanged from the current value (or 0 is returned if the connection has not yet performed a successfulINSERT
) and, for non-transactional tables, theAUTO_INCREMENT
counter is not incremented. ForInnoDB
tables, theAUTO_INCREMENT
counter is incremented ifinnodb_autoinc_lock_mode
is set to1
or2
, as demonstrated in the following example:- +----------------------------+
- | @@innodb_autoinc_lock_mode |
- +----------------------------+
- | 1 |
- +----------------------------+
- # Insert two rows
- # With auto_increment_offset=1, the inserted rows
- # result in an AUTO_INCREMENT value of 3
- *************************** 1. row ***************************
- Table: t
- # LAST_INSERT_ID() returns the first automatically generated
- # value that is successfully inserted for the AUTO_INCREMENT column
- +------------------+
- +------------------+
- | 1 |
- +------------------+
- # The attempted insertion of duplicate rows fail but errors are ignored
- Query OK, 0 rows affected (0.00 sec)
- # With innodb_autoinc_lock_mode=1, the AUTO_INCREMENT counter
- # is incremented for the ignored rows
- *************************** 1. row ***************************
- Table: t
- # The LAST_INSERT_ID is unchanged because the previous insert was unsuccessful
- +------------------+
- +------------------+
- | 1 |
- +------------------+
For more information, see Section 15.6.1.4, “AUTO_INCREMENT Handling in InnoDB”.
If
expr
is given as an argument toLAST_INSERT_ID()
, the value of the argument is returned by the function and is remembered as the next value to be returned byLAST_INSERT_ID()
. This can be used to simulate sequences:Create a table to hold the sequence counter and initialize it:
Use the table to generate sequence numbers like this:
The
UPDATE
statement increments the sequence counter and causes the next call toLAST_INSERT_ID()
to return the updated value. TheSELECT
statement retrieves that value. Themysql_insert_id()
C API function can also be used to get the value. See Section 28.7.7.38, “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 theUPDATE
statement and get their own sequence value with theSELECT
statement (ormysql_insert_id()
), without affecting or being affected by other clients that generate their own sequence values.Note that
mysql_insert_id()
is only updated afterINSERT
andUPDATE
statements, so you cannot use the C API function to retrieve the value forLAST_INSERT_ID(
after executing other SQL statements likeexpr
)SELECT
orSET
.Returns a
utf8
string containing a GraphML document representing memory role subgraphs. TheROLE_ADMIN
orSUPER
privilege is required to see content in the<graphml>
element. Otherwise, the result shows only an empty element:ROW_COUNT()
returns a value as follows:DDL statements: 0. This applies to statements such as
CREATE TABLE
orDROP TABLE
.DML statements other than
SELECT
: The number of affected rows. This applies to statements such asUPDATE
,INSERT
, orDELETE
(as before), but now also to statements such asALTER TABLE
andLOAD DATA INFILE
.SELECT
: -1 if the statement returns a result set, or the number of rows “affected” if it does not. For example, forSELECT * FROM t1
,ROW_COUNT()
returns -1. ForSELECT * FROM t1 INTO OUTFILE '
,file_name
'ROW_COUNT()
returns the number of rows written to the file.SIGNAL
statements: 0.
For
UPDATE
statements, the affected-rows value by default is the number of rows actually changed. If you specify theCLIENT_FOUND_ROWS
flag tomysql_real_connect()
when connecting to mysqld, the affected-rows value is the number of rows “found”; that is, matched by theWHERE
clause.For
REPLACE
statements, the affected-rows value is 2 if the new row replaced an old row, because in this case, one row was inserted after the duplicate was deleted.For
INSERT ... ON DUPLICATE KEY UPDATE
statements, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values. If you specify theCLIENT_FOUND_ROWS
flag, the affected-rows value is 1 (not 0) if an existing row is set to its current values.The
ROW_COUNT()
value is similar to the value from themysql_affected_rows()
C API function and the row count that the mysql client displays following statement execution.- Query OK, 3 rows affected (0.00 sec)
- +-------------+
- +-------------+
- | 3 |
- +-------------+
- Query OK, 2 rows affected (0.00 sec)
- +-------------+
- +-------------+
- | 2 |
- +-------------+
ImportantROW_COUNT()
is not replicated reliably using statement-based replication. This function is automatically replicated using row-based replication.This function is a synonym for
DATABASE()
.SESSION_USER()
is a synonym forUSER()
.SYSTEM_USER()
is a synonym forUSER()
.Returns the current MySQL user name and host name as a string in the
utf8
character set.The value indicates the user name 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()
.Returns a string that indicates the MySQL server version. The string uses the
utf8
character set. The value might have a suffix in addition to the version number. See the description of theversion
system variable in Section 5.1.8, “Server System Variables”.This function is unsafe for statement-based replication. A warning is logged if you use this function when
binlog_format
is set toSTATEMENT
.
Traduction non disponible
Le manuel MySQL n'est pas encore traduit en français sur l'infobrol. Seule la version anglaise est disponible pour l'instant.
Document créé le 26/06/2006, dernière modification le 26/10/2018
Source du document imprimé : https://www.gaudry.be/mysql-rf-information-functions.html
L'infobrol est un site personnel dont le contenu n'engage que moi. Le texte est mis à disposition sous licence CreativeCommons(BY-NC-SA). Plus d'info sur les conditions d'utilisation et sur l'auteur.
Références
Ces références et liens indiquent des documents consultés lors de la rédaction de cette page, ou qui peuvent apporter un complément d'information, mais les auteurs de ces sources ne peuvent être tenus responsables du contenu de cette page.
L'auteur de ce site est seul responsable de la manière dont sont présentés ici les différents concepts, et des libertés qui sont prises avec les ouvrages de référence. N'oubliez pas que vous devez croiser les informations de sources multiples afin de diminuer les risques d'erreurs.