![]() |
|
|
Go to the first, previous, next, last section, table of contents.
13 SQL Statement SyntaxThis chapter describes the syntax for the SQL statements supported in MySQL. 13.1 Data Manipulation Statements13.1.1
|
| Status Variable | Meaning |
Delayed_insert_threads | Number of handler threads |
Delayed_writes | Number of rows written with INSERT DELAYED
|
Not_flushed_delayed_rows | Number of rows waiting to be written |
SHOW STATUS statement or
by executing a mysqladmin extended-status command.
Note that INSERT DELAYED is slower than a normal INSERT if the
table is not in use. There is also the additional overhead for the server
to handle a separate thread for each table for which there are delayed rows.
This means that you should use INSERT DELAYED only when you are
really sure that you need it!
LOAD DATA INFILE Syntax
LOAD DATA [LOW_PRIORITY | CONCURRENT] [LOCAL] INFILE 'file_name.txt'
[REPLACE | IGNORE]
INTO TABLE tbl_name
[FIELDS
[TERMINATED BY '\t']
[[OPTIONALLY] ENCLOSED BY '']
[ESCAPED BY '\\' ]
]
[LINES
[STARTING BY '']
[TERMINATED BY '\n']
]
[IGNORE number LINES]
[(col_name,...)]
The LOAD DATA INFILE statement reads rows from a text file into a
table at a very high speed.
For more information about the efficiency of INSERT versus
LOAD DATA INFILE and speeding up LOAD DATA INFILE,
section 7.2.14 Speed of INSERT Statements.
You can also load data files by using the mysqlimport utility; it
operates by sending a LOAD DATA INFILE statement to the server. The
--local option causes mysqlimport to read data files from the
client host. You can specify the --compress option to get better
performance over slow networks if the client and server support the
compressed protocol.
See section 8.10 The mysqlimport Data Import Program.
If you specify the LOW_PRIORITY keyword, execution of the
LOAD DATA statement is delayed until no other clients are reading
from the table.
If you specify the CONCURRENT keyword with a MyISAM table that
satisfies the condition for concurrent inserts (that is, it contains no free
blocks in the middle),
then other threads can retrieve data from the table while LOAD DATA
is executing. Using this option affects the performance of LOAD DATA
a bit, even if no other thread is using the table at the same time.
If the LOCAL keyword is specified, it is
interpreted with respect to the client end of the connection:
LOCAL is specified, the file is read by the client program on the
client host and sent to the server.
LOCAL is not specified, the
file must be located on the server host and is read directly by the server.
LOCAL is available in MySQL 3.22.6 or later.
For security reasons, when reading text files located on the server, the
files must either reside in the database directory or be readable by all.
Also, to use LOAD DATA INFILE on server files, you must have the
FILE privilege.
See section 5.5.3 Privileges Provided by MySQL.
Using LOCAL is a bit slower than letting the server access the files
directly, because the contents of the file must be sent over the connection
by the client to the server. On the other hand, you do not need the
FILE privilege to load local files.
As of MySQL 3.23.49 and MySQL 4.0.2 (4.0.13 on Windows),
LOCAL works only if your server
and your client both have been enabled to allow it. For example, if
mysqld was started with --local-infile=0, LOCAL will
not work.
See section 5.4.4 Security Issues with LOAD DATA LOCAL.
If you need LOAD DATA to read from a pipe, you can use the
following technique (here we load the listing of the '/' directory into a
table):
mkfifo /mysql/db/x/x chmod 666 /mysql/db/x/x find / -ls > /mysql/db/x/x mysql -e "LOAD DATA INFILE 'x' INTO TABLE x" x
If you are using a version of MySQL older than 3.23.25,
you can use this technique only with LOAD DATA LOCAL INFILE.
If you are using MySQL before Version 3.23.24, you can't read from a
FIFO with LOAD DATA INFILE. If you need to read from a FIFO (for
example, the output from gunzip), use LOAD DATA LOCAL INFILE
instead.
When locating files on the server host, the server uses the following rules:
Note that these rules mean that a file named as `./myfile.txt' is read from
the server's data directory, whereas the same file named as `myfile.txt' is
read from the database directory of the default database. For example,
the following LOAD DATA statement reads the file `data.txt'
from the database directory for db1 because db1 is the current
database, even though the statement explicitly loads the file into a
table in the db2 database:
mysql> USE db1; mysql> LOAD DATA INFILE 'data.txt' INTO TABLE db2.my_table;
The REPLACE and IGNORE keywords control handling of input
records that duplicate existing records on unique key values.
If you specify REPLACE, input rows replace existing rows (in other
words, rows that have the same value for a primary or unique index as an
existing row). See section 13.1.6 REPLACE Syntax.
If you specify IGNORE, input rows that duplicate an existing row
on a unique key value are skipped. If you don't specify either option,
the behavior depends on whether or not the LOCAL keyword is specified.
Without LOCAL, an error occurs when a duplicate key value is
found, and the rest of the text file is ignored. With LOCAL,
the default behavior is the same as if IGNORE is specified;
this is because the server has no way to stop transmission of the file
in the middle of the operation.
If you want to ignore foreign key constraints during the load operation, you
can issue a SET FOREIGN_KEY_CHECKS=0 statement before executing
LOAD DATA.
If you use LOAD DATA INFILE on an empty MyISAM table, all
non-unique indexes are created in a separate batch (as for
REPAIR TABLE). This normally makes LOAD DATA INFILE much faster
when you have many indexes. Normally this is very fast, but in some
extreme cases, you can create the indexes even faster by turning them off
with ALTER TABLE .. DISABLE KEYS before loading the file into the
table and using ALTER TABLE .. ENABLE KEYS to re-create the indexes
after loading the file.
See section 7.2.14 Speed of INSERT Statements.
LOAD DATA INFILE is the complement of SELECT ... INTO OUTFILE.
See section 13.1.7 SELECT Syntax.
To write data from a table to a file, use SELECT ... INTO OUTFILE.
To read the file back into a table, use LOAD DATA INFILE.
The syntax of the FIELDS and LINES clauses is the same for
both statements. Both clauses are optional, but FIELDS
must precede LINES if both are specified.
If you specify a FIELDS clause,
each of its subclauses (TERMINATED BY, [OPTIONALLY] ENCLOSED
BY, and ESCAPED BY) is also optional, except that you must
specify at least one of them.
If you don't specify a FIELDS clause, the defaults are the
same as if you had written this:
FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\'
If you don't specify a LINES clause, the default
is the same as if you had written this:
LINES TERMINATED BY '\n' STARTING BY ''
In other words, the defaults cause LOAD DATA INFILE to act as follows
when reading input:
Conversely, the defaults cause SELECT ... INTO OUTFILE to act as
follows when writing output:
Note that to write FIELDS ESCAPED BY '\\', you must specify two
backslashes for the value to be read as a single backslash.
Note: If you have generated the text file on a Windows system, you
might have to use LINES TERMINATED BY '\r\n' to read the file
properly, because Windows programs typically use two characters as a line
terminator. Some programs, such as WordPad, might use \r as a line
terminator when writing files. To read such files, use LINES
TERMINATED BY '\r'.
If all the lines you want to read in have a common prefix that you want
to ignore, you can use LINES STARTING BY 'prefix_string' to skip
over the prefix (and anything before it). If a line doesn't include the
prefix, the entire line is skipped. Note that
prefix_string may be in the middle of the line!
Example:
mysql> LOAD DATA INFILE '/tmp/test.txt'
-> INTO TABLE test LINES STARTING BY "xxx";
With this you can read in a file that contains something like:
xxx"Row",1 something xxx"Row",2
And just get the data ("row",1) and ("row",2).
The IGNORE number LINES option can be used to ignore lines at
the start of the file. For example, you can use IGNORE 1 LINES
to skip over an initial header line containing column names:
mysql> LOAD DATA INFILE '/tmp/test.txt'
-> INTO TABLE test IGNORE 1 LINES;
When you use SELECT ... INTO OUTFILE in tandem with LOAD
DATA INFILE to write data from a database into a file and then read
the file back into the database later, the field- and line-handling
options for both statements must match. Otherwise, LOAD DATA
INFILE will not interpret the contents of the file properly. Suppose
that you use SELECT ... INTO OUTFILE to write a file with
fields delimited by commas:
mysql> SELECT * INTO OUTFILE 'data.txt'
-> FIELDS TERMINATED BY ','
-> FROM table2;
To read the comma-delimited file back in, the correct statement would be:
mysql> LOAD DATA INFILE 'data.txt' INTO TABLE table2
-> FIELDS TERMINATED BY ',';
If instead you tried to read in the file with the statement shown here, it
wouldn't work because it instructs LOAD DATA INFILE to look for
tabs between fields:
mysql> LOAD DATA INFILE 'data.txt' INTO TABLE table2
-> FIELDS TERMINATED BY '\t';
The likely result is that each input line would be interpreted as a single field.
LOAD DATA INFILE can be used to read files obtained from
external sources, too. For example, a file in dBASE format will have
fields separated by commas and enclosed within double quotes. If lines in
the file are terminated by newlines, the statement shown here
illustrates the field- and line-handling options you would use to load
the file:
mysql> LOAD DATA INFILE 'data.txt' INTO TABLE tbl_name
-> FIELDS TERMINATED BY ',' ENCLOSED BY '"'
-> LINES TERMINATED BY '\n';
Any of the field- or line-handling options can specify an empty string
(''). If not empty, the FIELDS [OPTIONALLY] ENCLOSED BY
and FIELDS ESCAPED BY values must be a single character. The
FIELDS TERMINATED BY, LINES STARTING BY, and LINES
TERMINATED BY values can be more than one character. For example, to write
lines that are terminated by carriage return/linefeed pairs, or to read a
file containing such lines, specify a LINES TERMINATED BY '\r\n'
clause.
To read a file containing jokes that are separated by lines consisting
of %%, you can do this
mysql> CREATE TABLE jokes
-> (a INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> joke TEXT NOT NULL);
mysql> LOAD DATA INFILE '/tmp/jokes.txt' INTO TABLE jokes
-> FIELDS TERMINATED BY ''
-> LINES TERMINATED BY '\n%%\n' (joke);
FIELDS [OPTIONALLY] ENCLOSED BY controls quoting of fields. For
output (SELECT ... INTO OUTFILE), if you omit the word
OPTIONALLY, all fields are enclosed by the ENCLOSED BY
character. An example of such output (using a comma as the field
delimiter) is shown here:
"1","a string","100.20" "2","a string containing a , comma","102.20" "3","a string containing a \" quote","102.20" "4","a string containing a \", quote and comma","102.20"
If you specify OPTIONALLY, the ENCLOSED BY character is
used only to enclose CHAR and VARCHAR fields:
1,"a string",100.20 2,"a string containing a , comma",102.20 3,"a string containing a \" quote",102.20 4,"a string containing a \", quote and comma",102.20
Note that occurrences of the ENCLOSED BY character within a
field value are escaped by prefixing them with the ESCAPED BY
character. Also note that if you specify an empty ESCAPED BY
value, it is possible to generate output that cannot be read properly by
LOAD DATA INFILE. For example, the preceding output just shown would
appear as follows if the escape character is empty. Observe that the
second field in the fourth line contains a comma following the quote, which
(erroneously) appears to terminate the field:
1,"a string",100.20 2,"a string containing a , comma",102.20 3,"a string containing a " quote",102.20 4,"a string containing a ", quote and comma",102.20
For input, the ENCLOSED BY character, if present, is stripped
from the ends of field values. (This is true whether or not OPTIONALLY
is specified; OPTIONALLY has no effect on input interpretation.)
Occurrences of the ENCLOSED BY character preceded by the
ESCAPED BY character are interpreted as part of the current
field value.
If the field begins with the ENCLOSED BY character, instances
of that character are recognized as terminating a field value only
if followed by the field or line TERMINATED BY sequence.
To avoid ambiguity, occurrences of the ENCLOSED BY character
within a field value can be doubled and will be interpreted as a
single instance of the character. For example, if ENCLOSED
BY '"' is specified, quotes are handled as shown here:
"The ""BIG"" boss" -> The "BIG" boss The "BIG" boss -> The "BIG" boss The ""BIG"" boss -> The ""BIG"" boss
FIELDS ESCAPED BY controls how to write or read special characters.
If the FIELDS ESCAPED BY character is not empty, it is used to prefix
the following characters on output:
FIELDS ESCAPED BY character
FIELDS [OPTIONALLY] ENCLOSED BY character
FIELDS TERMINATED BY and
LINES TERMINATED BY values
0 (what is actually written following the escape character is
ASCII `0', not a zero-valued byte)
If the FIELDS ESCAPED BY character is empty, no characters are
escaped and NULL is output as NULL, not \N. It is
probably not a good idea to specify an empty escape character,
particularly if field values in your data contain any of the characters
in the list just given.
For input, if the FIELDS ESCAPED BY character is not empty, occurrences
of that character are stripped and the following character is taken literally
as part of a field value. The exceptions are an escaped `0' or
`N' (for example, \0 or \N if the escape character is
`\'). These sequences are interpreted as ASCII NUL (a zero-valued
byte) and NULL. The rules for NULL handling are described later
in this section.
For more information about `\'-escape syntax, see section 9.1 Literal Values.
In certain cases, field- and line-handling options interact:
LINES TERMINATED BY is an empty string and FIELDS
TERMINATED BY is non-empty, lines are also terminated with
FIELDS TERMINATED BY.
FIELDS TERMINATED BY and FIELDS ENCLOSED BY values
are both empty (''), a fixed-row (non-delimited) format is used.
With fixed-row format, no delimiters are used between fields (but you
can still have a line terminator). Instead, column values are written
and read using the ``display'' widths of the columns. For example, if a
column is declared as INT(7), values for the column are written
using seven-character fields. On input, values for the column are obtained
by reading seven characters.
LINES TERMINATED BY is still used to separate lines. If a line
doesn't contain all fields, the rest of the columns are set to their
default values. If you don't have a line terminator, you should set this
to ''. In this case, the text file must contain all fields for
each row.
Fixed-row format also affects handling of NULL values, as described
later.
Note that fixed-size format will not work if you are using a multi-byte
character set.
Handling of NULL values varies according to the FIELDS and
LINES options in use:
FIELDS and LINES values, NULL is
written as a field value of \N for output, and a field value of
\N is read as NULL for input (assuming that the ESCAPED BY
character is `\').
FIELDS ENCLOSED BY is not empty, a field containing the literal
word NULL as its value is read as a NULL value. This differs
from the word NULL enclosed within FIELDS ENCLOSED BY
characters, which is read as the string 'NULL'.
FIELDS ESCAPED BY is empty, NULL is written as the word
NULL.
FIELDS TERMINATED BY and
FIELDS ENCLOSED BY are both empty), NULL is written as an empty
string. Note that this causes both NULL values and empty strings in
the table to be indistinguishable when written to the file because they are
both written as empty strings. If you need to be able to tell the two apart
when reading the file back in, you should not use fixed-row format.
Some cases are not supported by LOAD DATA INFILE:
FIELDS TERMINATED BY and FIELDS ENCLOSED
BY both empty) and BLOB or TEXT columns.
LOAD DATA INFILE won't be able to interpret the input properly.
For example, the following FIELDS clause would cause problems:
FIELDS TERMINATED BY '"' ENCLOSED BY '"'
FIELDS ESCAPED BY is empty, a field value that contains an occurrence
of FIELDS ENCLOSED BY or LINES TERMINATED BY
followed by the FIELDS TERMINATED BY value will cause LOAD
DATA INFILE to stop reading a field or line too early.
This happens because LOAD DATA INFILE cannot properly determine
where the field or line value ends.
The following example loads all columns of the persondata table:
mysql> LOAD DATA INFILE 'persondata.txt' INTO TABLE persondata;
By default, when no column list is provided at the end of the LOAD
DATA INFILE statement, input lines are expected to contain a field for each
table column. If you want to load only some of a table's columns, specify a
column list:
mysql> LOAD DATA INFILE 'persondata.txt'
-> INTO TABLE persondata (col1,col2,...);
You must also specify a column list if the order of the fields in the input file differs from the order of the columns in the table. Otherwise, MySQL cannot tell how to match up input fields with table columns.
If an input line has too many fields, the extra fields are ignored and the number of warnings is incremented.
If an input line has too few fields, the table columns for which input
fields are missing are set to their default values. Default value assignment
is described in section 13.2.6 CREATE TABLE Syntax.
An empty field value is interpreted differently than if the field value is missing:
0.
These are the same values that result if you assign an empty
string explicitly to a string, numeric, or date or time type explicitly
in an INSERT or UPDATE statement.
TIMESTAMP columns are set to the current date and time only if there
is a NULL value for the column (that is, \N), or (for the
first TIMESTAMP column only) if the TIMESTAMP column is
omitted from the field list when a field list is specified.
LOAD DATA INFILE regards all input as strings, so you can't use
numeric values for ENUM or SET columns the way you can with
INSERT statements. All ENUM and SET values must be
specified as strings!
When the LOAD DATA INFILE
statement finishes, it returns an information string in the following format:
Records: 1 Deleted: 0 Skipped: 0 Warnings: 0
If you are using the C API, you can get information about the statement by
calling the mysql_info() function.
See section 21.2.3.31 mysql_info().
Warnings occur under the same circumstances as when values are inserted
via the INSERT statement (see section 13.1.4 INSERT Syntax), except
that LOAD DATA INFILE also generates warnings when there are too few
or too many fields in the input row. The warnings are not stored anywhere;
the number of warnings can be used only as an indication of whether everything went
well.
From MySQL 4.1.1 on, you can use SHOW WARNINGS to get a list of the
first max_error_count warnings as information about what went wrong.
See section 13.5.4.20 SHOW WARNINGS Syntax.
Before MySQL 4.1.1, only a warning count is available to indicate that
something went wrong. If you get warnings and want to know exactly why you
got them, one way to do this is to dump the table into another file using
SELECT ... INTO OUTFILE and compare the file to your original input
file.
REPLACE Syntax
REPLACE [LOW_PRIORITY | DELAYED]
[INTO] tbl_name [(col_name,...)]
VALUES ({expr | DEFAULT},...),(...),...
Or:
REPLACE [LOW_PRIORITY | DELAYED]
[INTO] tbl_name
SET col_name={expr | DEFAULT}, ...
Or:
REPLACE [LOW_PRIORITY | DELAYED]
[INTO] tbl_name [(col_name,...)]
SELECT ...
REPLACE works exactly like INSERT, except that if an old
record in the table has the same value as a new record for a PRIMARY
KEY or a UNIQUE index, the old record is deleted before the new
record is inserted.
See section 13.1.4 INSERT Syntax.
Note that unless the table has a PRIMARY KEY or UNIQUE index,
using a REPLACE statement makes no sense. It becomes equivalent to
INSERT, because there is no index to be used to determine whether a new
row duplicates another.
Values for all columns are taken from the values specified in the
REPLACE statement. Any missing columns are set to their default
values, just as happens for INSERT. You can't refer to values from
the old row and use them in the new row. It appeared that you could do this
in some old MySQL versions, but that was a bug that has been corrected.
To be able to use REPLACE, you must have INSERT and
DELETE privileges for the table.
The REPLACE statement returns a count to indicate the number of rows
affected. This is the sum of the rows deleted and inserted. If the count is 1
for a single-row REPLACE, a row was inserted and no rows were deleted.
If the count is greater than 1, one or more old rows were deleted before the
new row was inserted. It is possible for a single row to replace more than one
old row if the table contains multiple unique indexes and the new row
duplicates values for different old rows in different unique indexes.
The affected-rows count makes it easy to determine whether REPLACE
only added a row or whether it also replaced any rows: Check whether the
count is 1 (added) or greater (replaced).
If you are using the C API, the affected-rows count can be obtained using the
mysql_affected_rows() function.
Currently, you cannot replace into a table and select from the same table in a subquery.
Here follows in more detail the algorithm that is used
(it is also used with LOAD DATA ... REPLACE):
SELECT Syntax
SELECT
[ALL | DISTINCT | DISTINCTROW ]
[HIGH_PRIORITY]
[STRAIGHT_JOIN]
[SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
[SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
select_expr, ...
[INTO OUTFILE 'file_name' export_options
| INTO DUMPFILE 'file_name']
[FROM table_references
[WHERE where_definition]
[GROUP BY {col_name | expr | position}
[ASC | DESC], ... [WITH ROLLUP]]
[HAVING where_definition]
[ORDER BY {col_name | expr | position}
[ASC | DESC] , ...]
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
[PROCEDURE procedure_name(argument_list)]
[FOR UPDATE | LOCK IN SHARE MODE]]
SELECT is used to retrieve rows selected from one or more tables.
Support for UNION statements and subqueries is available as of MySQL
4.0 and 4.1, respectively.
See section 13.1.7.2 UNION Syntax and section 13.1.8 Subquery Syntax.
JOIN Syntax.
WHERE followed by
an expression that indicates the condition or conditions that rows
must satisfy to be selected.
SELECT can also be used to retrieve rows computed without reference to
any table.
For example:
mysql> SELECT 1 + 1;
-> 2
All clauses used must be given in exactly the order shown in the syntax
description. For example,
a HAVING clause must come after any GROUP BY clause and before
any ORDER BY clause.
AS alias_name.
The alias is used as the expression's column name and can be used in
GROUP BY,
ORDER BY, or HAVING clauses. For example:
mysql> SELECT CONCAT(last_name,', ',first_name) AS full_name
-> FROM mytable ORDER BY full_name;
The AS keyword is optional when aliasing a select_expr.
The preceding example could have been written like this:
mysql> SELECT CONCAT(last_name,', ',first_name) full_name
-> FROM mytable ORDER BY full_name;
Because the AS is optional, a subtle problem can occur
if you forget the comma between two select_expr expressions: MySQL
interprets the second as an alias name. For example, in the following
statement, columnb is treated as an alias name:
mysql> SELECT columna columnb FROM mytable;
WHERE clause,
because the column value might not yet be determined when the
WHERE clause is executed.
See section A.5.4 Problems with Column Aliases.
FROM table_references clause indicates the tables from which to
retrieve rows. If you name more than one table, you are performing a
join. For information on join syntax, see section 13.1.7.1 JOIN Syntax.
For each table specified, you can optionally specify an alias.
tbl_name [[AS] alias]
[[USE INDEX (key_list)]
| [IGNORE INDEX (key_list)]
| [FORCE INDEX (key_list)]]
The use of
USE INDEX,
IGNORE INDEX,
FORCE INDEX
to give the optimizer hints about how to choose indexes is described in
section 13.1.7.1 JOIN Syntax.
In MySQL 4.0.14, you can use SET max_seeks_for_key=value as an
alternative way to force MySQL to prefer key scans instead of table scans.
DUAL as a dummy
table name in situations where no tables are referenced:
mysql> SELECT 1 + 1 FROM DUAL;
-> 2
DUAL is purely a compatibility feature. Some other servers require
this syntax.
tbl_name AS alias_name or
tbl_name alias_name:
mysql> SELECT t1.name, t2.salary FROM employee AS t1, info AS t2
-> WHERE t1.name = t2.name;
mysql> SELECT t1.name, t2.salary FROM employee t1, info t2
-> WHERE t1.name = t2.name;
WHERE clause, you can use any of the functions that
MySQL supports, except for aggregate (summary) functions.
See section 12 Functions and Operators.
ORDER BY and
GROUP BY clauses using column names, column aliases, or column
positions. Column positions are integers and begin with 1:
mysql> SELECT college, region, seed FROM tournament
-> ORDER BY region, seed;
mysql> SELECT college, region AS r, seed AS s FROM tournament
-> ORDER BY r, s;
mysql> SELECT college, region, seed FROM tournament
-> ORDER BY 2, 3;
To sort in reverse order, add the DESC (descending) keyword to the
name of the column in the ORDER BY clause that you are sorting by.
The default is ascending order; this can be specified explicitly using
the ASC keyword.
Use of column positions is deprecated because the syntax has been removed from
the SQL standard.
GROUP BY, output rows are sorted according to the
GROUP BY columns as if you had an ORDER BY for the same columns.
MySQL has extended the GROUP BY clause as of version 3.23.34 so that
you can also specify ASC and DESC after columns named in the
clause:
SELECT a, COUNT(b) FROM test_table GROUP BY a DESC
GROUP BY to allow you to
select fields that are not mentioned in the GROUP BY clause.
If you are not getting the results you expect from your query, please
read the GROUP BY description.
See section 12.9 Functions and Modifiers for Use with GROUP BY Clauses.
GROUP BY allows a WITH ROLLUP modifier.
See section 12.9.2 GROUP BY Modifiers.
HAVING clause can refer to any column or alias named in a
select_expr. It is applied nearly last, just before items are
sent to the client, with no optimization.
(LIMIT is applied after HAVING.)
HAVING for items that
should be in the WHERE clause. For example, do not write this:
mysql> SELECT col_name FROM tbl_name HAVING col_name > 0;Write this instead:
mysql> SELECT col_name FROM tbl_name WHERE col_name > 0;
HAVING clause can refer to aggregate functions, which the
WHERE clause cannot:
mysql> SELECT user, MAX(salary) FROM users
-> GROUP BY user HAVING MAX(salary)>10;
However, that does not work in older MySQL servers (before version 3.22.5).
Instead, you can use a column alias in the select list and refer to the
alias in the HAVING clause:
mysql> SELECT user, MAX(salary) AS max_salary FROM users
-> GROUP BY user HAVING max_salary>10;
LIMIT clause can be used to constrain the number of rows returned
by the SELECT statement. LIMIT takes one or two numeric
arguments, which must be integer constants.
With two arguments, the first argument specifies the offset of the first row to
return, and the second specifies the maximum number of rows to return.
The offset of the initial row is 0 (not 1):
mysql> SELECT * FROM table LIMIT 5,10; # Retrieve rows 6-15For compatibility with PostgreSQL, MySQL also supports the
LIMIT row_count OFFSET offset syntax.
To retrieve all rows from a certain offset up to the end of the result set,
you can use some large number for the second parameter. This statement
retrieves all rows from the 96th row to the last:
mysql> SELECT * FROM table LIMIT 95,18446744073709551615;With one argument, the value specifies the number of rows to return from the beginning of the result set:
mysql> SELECT * FROM table LIMIT 5; # Retrieve first 5 rowsIn other words,
LIMIT n is equivalent to LIMIT 0,n.
SELECT ... INTO OUTFILE 'file_name' form of SELECT writes
the selected rows to a file. The file is created on the server host, so you
must have the FILE privilege to use this syntax. The
file cannot already exist, which among other things prevents files such as
`/etc/passwd' and database tables from being destroyed.
The SELECT ... INTO OUTFILE statement is intended primarily to let
you very quickly dump a table on the server machine. If you want to create
the resulting file on some client host other than the server host, you can't use
SELECT ... INTO OUTFILE. In that case, you should instead use some
command like mysql -e "SELECT ..." > file_name on the client host to generate the file.
SELECT ... INTO OUTFILE is the complement of LOAD DATA
INFILE; the syntax for the export_options part of the statement
consists of the same FIELDS and LINES clauses that are used
with the LOAD DATA INFILE statement.
See section 13.1.5 LOAD DATA INFILE Syntax.
FIELDS ESCAPED BY controls how to write special characters.
If the FIELDS ESCAPED BY character is not empty, it is used to prefix
the following characters on output:
FIELDS ESCAPED BY character
FIELDS [OPTIONALLY] ENCLOSED BY character
FIELDS TERMINATED BY and
LINES TERMINATED BY values
0 (what is actually written following the escape character is
ASCII `0', not a zero-valued byte)
FIELDS ESCAPED BY character is empty, no characters are
escaped and NULL is output as NULL, not \N. It is
probably not a good idea to specify an empty escape character,
particularly if field values in your data contain any of the characters
in the list just given.
The reason for the above is that you must escape any FIELDS
TERMINATED BY, ENCLOSED BY, ESCAPED BY, or LINES TERMINATED BY
characters to reliably be able to read the file back. ASCII NUL is
escaped to make it easier to view with some pagers.
The resulting file doesn't have to conform to SQL syntax, so nothing
else need be escaped.
Here is an example that produces a file in the comma-separated values format
used by many programs:
SELECT a,b,a+b INTO OUTFILE '/tmp/result.text' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n' FROM test_table;
INTO DUMPFILE instead of INTO OUTFILE, MySQL writes
only one row into the file, without any column or line termination and
without performing any escape processing. This is useful if you want to
store a BLOB value in a file.
INTO OUTFILE or INTO
DUMPFILE is writable by all users on the server host. The reason for
this is that the MySQL server can't create a file that is owned by anyone
other than the user it's running as (you should never run mysqld as
root). The file thus must be world-writable so that you can
manipulate its contents.
PROCEDURE clause names a procedure that should process the data
in the result set. For an example, see section 24.3.1 Procedure Analyse.
FOR UPDATE on a storage engine that uses page or row locks,
rows examined by the query are write-locked until the end of the current
transaction. Using IN SHARE MODE sets a shared lock that prevents
other transactions from updating or deleting the examined rows.
See section 15.11.4 Locking Reads SELECT ... FOR UPDATE and SELECT ... LOCK IN SHARE MODE.
Following the SELECT keyword, you can give a number of options
that affect the operation of the statement.
The ALL, DISTINCT, and DISTINCTROW options specify
whether duplicate rows should be returned. If none of these options are
given, the default is ALL (all matching rows are returned).
DISTINCT and DISTINCTROW are synonyms and specify that
duplicate rows in the result set should be removed.
HIGH_PRIORITY, STRAIGHT_JOIN, and options beginning with
SQL_ are MySQL extensions to standard SQL.
HIGH_PRIORITY will give the SELECT higher priority than
a statement that updates a table. You should use this only for queries
that are very fast and must be done at once. A SELECT HIGH_PRIORITY
query that is issued while the table is locked for reading will run even if
there is already an update statement waiting for the table to be free.
HIGH_PRIORITY cannot be used with SELECT statements that
are part of a UNION.
STRAIGHT_JOIN forces the optimizer to join the tables in the order in
which they are listed in the FROM clause. You can use this to speed up
a query if the optimizer joins the tables in non-optimal order.
See section 7.2.1 EXPLAIN Syntax (Get Information About a SELECT).
STRAIGHT_JOIN also can be used in the table_references list.
See section 13.1.7.1 JOIN Syntax.
SQL_BIG_RESULT can be used with GROUP BY or DISTINCT
to tell the optimizer that the result set will have many rows. In this case,
MySQL will directly use disk-based temporary tables if needed.
MySQL will also, in this case, prefer sorting to using a
temporary table with a key on the GROUP BY elements.
SQL_BUFFER_RESULT forces the result to be put into a temporary
table. This helps MySQL free the table locks early and helps
in cases where it takes a long time to send the result set to the client.
SQL_SMALL_RESULT can be used
with GROUP BY or DISTINCT to tell the optimizer that the
result set will be small. In this case, MySQL uses fast
temporary tables to store the resulting table instead of using sorting. In
MySQL 3.23 and up, this shouldn't normally be needed.
SQL_CALC_FOUND_ROWS (available in MySQL 4.0.0 and up) tells MySQL
to calculate how many rows there would be in the result set, disregarding
any LIMIT clause. The number of rows can then be retrieved with
SELECT FOUND_ROWS().
See section 12.8.3 Information Functions.
Before MySQL 4.1.0, this option does not work with
LIMIT 0, which is optimized to return instantly (resulting in a
row count of 0).
See section 7.2.12 How MySQL Optimizes LIMIT.
SQL_CACHE tells MySQL to store the query result in the query cache if
you are using a query_cache_type value of 2 or DEMAND.
For a query that uses UNION or subqueries, this option takes effect
to be used in any SELECT of the query.
See section 5.11 The MySQL Query Cache.
SQL_NO_CACHE tells MySQL not to store the query result
in the query cache. See section 5.11 The MySQL Query Cache.
For a query that uses UNION or subqueries, this
option takes effect to be used in any SELECT of the query.
JOIN Syntax
MySQL supports the following JOIN syntaxes for the
table_references part of SELECT statements and multiple-table
DELETE and UPDATE statements:
table_reference, table_reference
table_reference [INNER | CROSS] JOIN table_reference [join_condition]
table_reference STRAIGHT_JOIN table_reference
table_reference LEFT [OUTER] JOIN table_reference [join_condition]
table_reference NATURAL [LEFT [OUTER]] JOIN table_reference
{ OJ table_reference LEFT OUTER JOIN table_reference
ON conditional_expr }
table_reference RIGHT [OUTER] JOIN table_reference [join_condition]
table_reference NATURAL [RIGHT [OUTER]] JOIN table_reference
table_reference is defined as:
tbl_name [[AS] alias]
[[USE INDEX (key_list)]
| [IGNORE INDEX (key_list)]
| [FORCE INDEX (key_list)]]
join_condition is defined as:
ON conditional_expr | USING (column_list)
You should generally not have any conditions in the ON part that are
used to restrict which rows you want in the result set, but rather specify
these conditions in the WHERE clause. There are exceptions to this rule.
Note that INNER JOIN syntax allows a join_condition only from
MySQL 3.23.17 on. The same is true for JOIN and CROSS JOIN only
as of MySQL 4.0.11.
The { OJ ... LEFT OUTER JOIN ...} syntax shown in the preceding list
exists only for compatibility with ODBC.
tbl_name AS alias_name or
tbl_name alias_name:
mysql> SELECT t1.name, t2.salary FROM employee AS t1, info AS t2
-> WHERE t1.name = t2.name;
mysql> SELECT t1.name, t2.salary FROM employee t1, info t2
-> WHERE t1.name = t2.name;
ON conditional is any conditional expression of the form that can
be used in a WHERE clause.
ON or
USING part in a LEFT JOIN, a row with all columns set to
NULL is used for the right table. You can use this fact to find
records in a table that have no counterpart in another table:
mysql> SELECT table1.* FROM table1
-> LEFT JOIN table2 ON table1.id=table2.id
-> WHERE table2.id IS NULL;
This example finds all rows in table1 with an id value that is
not present in table2 (that is, all rows in table1 with no
corresponding row in table2). This assumes that table2.id is
declared NOT NULL.
See section 7.2.9 How MySQL Optimizes LEFT JOIN and RIGHT JOIN.
USING (column_list) clause names a list of columns that must
exist in both tables. The following two clauses are semantically identical:
a LEFT JOIN b USING (c1,c2,c3) a LEFT JOIN b ON a.c1=b.c1 AND a.c2=b.c2 AND a.c3=b.c3
NATURAL [LEFT] JOIN of two tables is defined to be
semantically equivalent to an INNER JOIN or a LEFT JOIN
with a USING clause that names all columns that exist in both
tables.
INNER JOIN and , (comma) are semantically equivalent in
the absence of a join condition: both will produce a Cartesian product
between the specified tables (that is, each and every row in the first table
will be joined onto all rows in the second table).
RIGHT JOIN works analogously to LEFT JOIN. To keep code
portable across databases, it's recommended to use LEFT JOIN
instead of RIGHT JOIN.
STRAIGHT_JOIN is identical to JOIN, except that the left table
is always read before the right table. This can be used for those (few)
cases for which the join optimizer puts the tables in the wrong order.
As of MySQL 3.23.12, you can give hints about which index MySQL
should use when retrieving information from a table. By specifying
USE INDEX (key_list), you can tell MySQL to use only one of the
possible indexes to find rows in the table. The alternative syntax
IGNORE INDEX (key_list) can be used to tell MySQL to not use some
particular index. These hints are useful if EXPLAIN shows that MySQL
is using the wrong index from the list of possible indexes.
From MySQL 4.0.9 on, you can also use FORCE INDEX. This acts likes
USE INDEX (key_list) but with the addition that a table scan
is assumed to be very expensive. In other words, a table scan will
only be used if there is no way to use one of the given indexes to
find rows in the table.
USE KEY, IGNORE KEY, and FORCE KEY are synonyms for
USE INDEX, IGNORE INDEX, and FORCE INDEX.
Note: USE INDEX, IGNORE INDEX, and FORCE INDEX
only affect which indexes are used when MySQL decides how to find rows in
the table and how to do the join. They do not affect whether an index will
be used when resolving an ORDER BY or GROUP BY.
Some join examples:
mysql> SELECT * FROM table1,table2 WHERE table1.id=table2.id;
mysql> SELECT * FROM table1 LEFT JOIN table2 ON table1.id=table2.id;
mysql> SELECT * FROM table1 LEFT JOIN table2 USING (id);
mysql> SELECT * FROM table1 LEFT JOIN table2 ON table1.id=table2.id
-> LEFT JOIN table3 ON table2.id=table3.id;
mysql> SELECT * FROM table1 USE INDEX (key1,key2)
-> WHERE key1=1 AND key2=2 AND key3=3;
mysql> SELECT * FROM table1 IGNORE INDEX (key3)
-> WHERE key1=1 AND key2=2 AND key3=3;
See section 7.2.9 How MySQL Optimizes LEFT JOIN and RIGHT JOIN.
UNION SyntaxSELECT ... UNION [ALL | DISTINCT] SELECT ... [UNION [ALL | DISTINCT] SELECT ...]
UNION is used to combine the result from many SELECT
statements into one result set. UNION is available from MySQL 4.0.0
on.
Selected columns listed in corresponding positions of each SELECT
statement should have the same type. (For example, the first column selected
by the first statement should have the same type as the first column selected
by the other statements.) The column names used in
the first SELECT statement are used as the column names for the
results returned.
The SELECT statements are normal select statements, but with the
following restrictions:
SELECT statement can have INTO OUTFILE.
HIGH_PRIORITY cannot be used with SELECT statements that
are part of a UNION. If you specify it for the first SELECT,
it has no effect. If you specify it for any subsequent SELECT
statements, a syntax error results.
If you don't use the keyword ALL for the UNION, all
returned rows will be unique, as if you had done a DISTINCT for
the total result set. If you specify ALL, you will get all
matching rows from all the used SELECT statements.
The DISTINCT keyword is an optional word (introduced in MySQL 4.0.17).
It does nothing, but is allowed in the syntax as required by the SQL standard.
Before MySQL 4.1.2, you cannot mix UNION ALL and UNION
DISTINCT in the same query. If you use ALL for one
UNION, it is used for all of them. As of MySQL 4.1.2, mixed
UNION types are treated such that a DISTINCT union overrides
any ALL union to its left. A DISTINCT union can be produced
explicitly by using UNION DISTINCT or implicitly by using UNION
with no following DISTINCT or ALL keyword.
If you want to use an ORDER BY or LIMIT clause to sort or limit
the entire UNION result, parenthesize the individual SELECT
statements and place the ORDER BY or LIMIT after the last one.
The following example uses both clauses:
(SELECT a FROM tbl_name WHERE a=10 AND B=1) UNION (SELECT a FROM tbl_name WHERE a=11 AND B=2) ORDER BY a LIMIT 10;
This kind of ORDER BY cannot use column references that include a
table name (that is, names in tbl_name.col_name format). Instead,
provide a column alias in the first SELECT statement and refer to the
alias in the ORDER BY, or else refer to the column in the ORDER
BY using its column position. (An alias is preferable because use of
column positions is deprecated.)
To apply ORDER BY or LIMIT to an individual SELECT,
place the clause inside the parentheses that enclose the SELECT:
(SELECT a FROM tbl_name WHERE a=10 AND B=1 ORDER BY a LIMIT 10) UNION (SELECT a FROM tbl_name WHERE a=11 AND B=2 ORDER BY a LIMIT 10);
The types and lengths of the columns in the result set of a UNION
take into account the values retrieved by all the SELECT statements.
Before MySQL 4.1.1, a limitation of UNION is that only the values from
the first SELECT are used to determine result column types and lengths.
This could result in value truncation if, for example, the first
SELECT retrieves shorter values than the second SELECT:
mysql> SELECT REPEAT('a',1) UNION SELECT REPEAT('b',10);
+---------------+
| REPEAT('a',1) |
+---------------+
| a |
| b |
+---------------+
That limitation has been removed as of MySQL 4.1.1:
mysql> SELECT REPEAT('a',1) UNION SELECT REPEAT('b',10);
+---------------+
| REPEAT('a',1) |
+---------------+
| a |
| bbbbbbbbbb |
+---------------+
A subquery is a SELECT statement inside another statement.
Starting with MySQL 4.1, all subquery forms and operations that the SQL standard requires are supported, as well as a few features that are MySQL-specific.
With MySQL versions prior to 4.1, it was necessary to work around or avoid the use of subqueries. In many cases, subqueries can successfully be rewritten using joins and other methods. See section 13.1.8.11 Rewriting Subqueries as Joins for Earlier MySQL Versions.
Here is an example of a subquery:
SELECT * FROM t1 WHERE column1 = (SELECT column1 FROM t2);
In this example, SELECT * FROM t1 ... is the outer query
(or outer statement), and (SELECT column1 FROM t2) is the
subquery.
We say that the subquery is nested in the outer query, and in fact
it's possible to nest subqueries within other subqueries, to a great depth.
A subquery must always appear within parentheses.
The main advantages of subqueries are:
Here is an example statement that shows the major points about subquery syntax as specified by the SQL standard and supported in MySQL:
DELETE FROM t1
WHERE s11 > ANY
(SELECT COUNT(*) /* no hint */ FROM t2
WHERE NOT EXISTS
(SELECT * FROM t3
WHERE ROW(5*t2.s1,77)=
(SELECT 50,11*s1 FROM t4 UNION SELECT 50,77 FROM
(SELECT * FROM t5) AS t5)));
A subquery can return a scalar (a single value), a single row, a single column, or a table (one or more rows of one or more columns). These are called scalar, column, row, and table subqueries. Subqueries that return a particular kind of result often can be used only in certain contexts, as described in the following sections.
There are few restrictions on the type of statements in which subqueries can be used:
SELECT, INSERT, UPDATE, DELETE,
SET, or DO.
SELECT can contain:
DISTINCT, GROUP BY, ORDER BY, LIMIT,
joins, index hints, UNION constructs, comments, functions, and so on.
One restriction is that currently you cannot modify a table and select from
the same table in a subquery. This applies to statements such as
DELETE, INSERT, REPLACE, and UPDATE.
In its simplest form, a subquery is a scalar subquery that returns a single
value. A scalar subquery is a simple operand, and you can use it wherever a
single column value or literal is legal, and you can expect it to have those
characteristics that all operands have: a data type, a length, an indication
whether it can be NULL, and so on. For example:
CREATE TABLE t1 (s1 INT, s2 CHAR(5) NOT NULL); INSERT INTO t1 VALUES(100, 'abcde'); SELECT (SELECT s2 FROM t1);
The subquery in this SELECT returns a single value ('abcde')
that has a data type of CHAR, a length of 5, a character set and
collation equal to the defaults in effect at CREATE TABLE time, and
an indication that the value in the column can be NULL. In fact,
almost all subqueries can be NULL. If the table used in the example
were empty, the value of the subquery would be NULL.
When you see examples in the following sections that contain the rather
spartan construct (SELECT column1 FROM t1), imagine that your own
code will contain much more diverse and complex constructions.
For example, suppose that we make two tables:
CREATE TABLE t1 (s1 INT); INSERT INTO t1 VALUES (1); CREATE TABLE t2 (s1 INT); INSERT INTO t2 VALUES (2);
Then perform a SELECT:
SELECT (SELECT s1 FROM t2) FROM t1;
The result will be 2 because there is a row in t2 containing a
column s1 that has a value of 2.
A scalar subquery can be part of an expression. Don't forget the parentheses, even if the subquery is an operand that provides an argument for a function. For example:
SELECT UPPER((SELECT s1 FROM t1)) FROM t2;
The most common use of a subquery is in the form:
non_subquery_operand comparison_operator (subquery)
Where comparison_operator is one of these operators:
= > < >= <= <>
For example:
... 'a' = (SELECT column1 FROM t1)
At one time the only legal place for a subquery was on the right side of a comparison, and you might still find some old DBMSs that insist on this.
Here is an example of a common-form subquery comparison that you cannot do
with a join. It finds all the values in table t1 that are equal to a
maximum value in table t2:
SELECT column1 FROM t1
WHERE column1 = (SELECT MAX(column2) FROM t2);
Here is another example, which again is impossible with a join because it
involves aggregating for one of the tables. It finds all rows in table
t1 containing a value that occurs twice in a given column:
SELECT * FROM t1 AS t
WHERE 2 = (SELECT COUNT(*) FROM t1 WHERE t1.id = t.id);
For a comparison performed with one of these comparison operators, the
subquery must return a scalar, with the exception that = can be used
with row subqueries.
See section 13.1.8.5 Row Subqueries.
ANY, IN, and SOMESyntax:
operand comparison_operator ANY (subquery) operand IN (subquery) operand comparison_operator SOME (subquery)
The ANY keyword, which must follow a comparison operator, means
``return TRUE if the comparison is TRUE for ANY of the
values in the column that the subquery returns.''
For example:
SELECT s1 FROM t1 WHERE s1 > ANY (SELECT s1 FROM t2);
Suppose that there is a row in table t1 containing (10).
The expression is TRUE if table t2 contains (21,14,7)
because there is a value 7 in t2 that is less than 10.
The expression is FALSE if table t2 contains (20,10),
or if table t2 is empty. The expression is UNKNOWN if table
t2 contains (NULL,NULL,NULL).
The word IN is an alias for = ANY. Thus these two statements
are the same:
SELECT s1 FROM t1 WHERE s1 = ANY (SELECT s1 FROM t2); SELECT s1 FROM t1 WHERE s1 IN (SELECT s1 FROM t2);
However, NOT IN is not an alias for <> ANY, but for
<> ALL. See section 13.1.8.4 Subqueries with ALL.
The word SOME is an alias for ANY. Thus these two statements
are the same:
SELECT s1 FROM t1 WHERE s1 <> ANY (SELECT s1 FROM t2); SELECT s1 FROM t1 WHERE s1 <> SOME (SELECT s1 FROM t2);
Use of the word SOME is rare, but this example shows why it might be
useful. To most people's ears, the English phrase ``a is not equal to any
b'' means ``there is no b which is equal to a,'' but that isn't what is
meant by the SQL syntax. Using <> SOME instead helps ensure that
everyone understands the true meaning of the query.
ALLSyntax:
operand comparison_operator ALL (subquery)
The word ALL, which must follow a comparison operator, means
``return TRUE if the comparison is TRUE for ALL of
the values in the column that the subquery returns.''
For example:
SELECT s1 FROM t1 WHERE s1 > ALL (SELECT s1 FROM t2);
Suppose that there is a row in table t1 containing (10).
The expression is TRUE if table t2 contains (-5,0,+5)
because 10 is greater than all three values in t2.
The expression is FALSE if table t2 contains
(12,6,NULL,-100) because there is a single value 12 in table t2
that is greater than 10.
The expression is UNKNOWN if table t2 contains (0,NULL,1).
Finally, if table t2 is empty, the result is TRUE.
You might think the result should be UNKNOWN, but
sorry, it's TRUE. So, rather oddly, the following statement
is TRUE when table t2 is empty:
SELECT * FROM t1 WHERE 1 > ALL (SELECT s1 FROM t2);
But this statement is UNKNOWN when table t2 is empty:
SELECT * FROM t1 WHERE 1 > (SELECT s1 FROM t2);
In addition, the following statement is UNKNOWN when table t2
is empty:
SELECT * FROM t1 WHERE 1 > ALL (SELECT MAX(s1) FROM t2);
In general, tables with NULL values and empty tables are
edge cases. When writing subquery code, always consider whether
you have taken those two possibilities into account.
NOT IN is an alias for <> ALL. Thus these two statements
are the same:
SELECT s1 FROM t1 WHERE s1 <> ALL (SELECT s1 FROM t2); SELECT s1 FROM t1 WHERE s1 NOT IN (SELECT s1 FROM t2);
The discussion to this point has been of scalar or column subqueries, that is, subqueries that return a single value or a column of values. A row subquery is a subquery variant that returns a single row and can thus return more than one column value. Here are two examples:
SELECT * FROM t1 WHERE (1,2) = (SELECT column1, column2 FROM t2); SELECT * FROM t1 WHERE ROW(1,2) = (SELECT column1, column2 FROM t2);
The queries here are both TRUE if table t2 has
a row where column1 = 1 and column2 = 2.
The expressions (1,2) and ROW(1,2) are sometimes called
row constructors. The two are equivalent.
They are legal in other contexts, too. For example, the following two
statements are semantically equivalent (although currently only the second one
can be optimized):
SELECT * FROM t1 WHERE (column1,column2) = (1,1); SELECT * FROM t1 WHERE column1 = 1 AND column2 = 1;
The normal use of row constructors, though, is for comparisons with
subqueries that return two or more columns. For example, the following query answers
the request, ``find all rows in table t1 that also exist in table
t2'':
SELECT column1,column2,column3
FROM t1
WHERE (column1,column2,column3) IN
(SELECT column1,column2,column3 FROM t2);
EXISTS and NOT EXISTS
If a subquery returns any rows at all, then EXISTS subquery is
TRUE, and NOT EXISTS subquery is FALSE.
For example:
SELECT column1 FROM t1 WHERE EXISTS (SELECT * FROM t2);
Traditionally, an EXISTS subquery starts with SELECT *, but it
could begin with SELECT 5 or SELECT column1 or anything at
all. MySQL ignores the SELECT list in such a subquery, so it
doesn't matter.
For the preceding example, if t2 contains any rows, even rows with
nothing but NULL values, then the EXISTS condition is
TRUE. This is actually an unlikely example, since almost always a
[NOT] EXISTS subquery will contain correlations.
Here are some more realistic examples:
SELECT DISTINCT store_type FROM Stores
WHERE EXISTS (SELECT * FROM Cities_Stores
WHERE Cities_Stores.store_type = Stores.store_type);
SELECT DISTINCT store_type FROM Stores
WHERE NOT EXISTS (SELECT * FROM Cities_Stores
WHERE Cities_Stores.store_type = Stores.store_type);
SELECT DISTINCT store_type FROM Stores S1
WHERE NOT EXISTS (
SELECT * FROM Cities WHERE NOT EXISTS (
SELECT * FROM Cities_Stores
WHERE Cities_Stores.city = Cities.city
AND Cities_Stores.store_type = Stores.store_type));
The last example is a double-nested NOT EXISTS query. That is, it has a
NOT EXISTS clause within a NOT EXISTS clause. Formally, it
answers the question ``does a city exist with a store that is not in
Stores?'' But it's easier to say that a nested NOT EXISTS answers
the question ``is x TRUE for all y?''
A correlated subquery is a subquery that contains a reference to a table that also appears in the outer query. For example:
SELECT * FROM t1 WHERE column1 = ANY
(SELECT column1 FROM t2 WHERE t2.column2 = t1.column2);
Notice that the subquery contains a reference to a column
of t1, even though the subquery's FROM clause doesn't mention
a table t1. So, MySQL looks outside the subquery, and finds t1 in the
outer query.
Suppose that table t1 contains a row where column1 = 5 and
column2 = 6; meanwhile, table t2 contains a row where
column1 = 5 and column2 = 7. The simple expression
... WHERE column1 = ANY (SELECT column1 FROM t2) would be
TRUE, but in this example, the WHERE clause within the
subquery is FALSE (because (5,6) is not equal to (5,7)),
so the subquery as a whole is FALSE.
Scoping rule: MySQL evaluates from inside to outside. For example:
SELECT column1 FROM t1 AS x
WHERE x.column1 = (SELECT column1 FROM t2 AS x
WHERE x.column1 = (SELECT column1 FROM t3
WHERE x.column2 = t3.column1));
In this statement, x.column2 must be a column in table t2 because
SELECT column1 FROM t2 AS x ... renames t2. It is not a
column in table t1 because SELECT column1 FROM t1 ... is an
outer query that is farther out.
For subqueries in HAVING or ORDER BY clauses, MySQL also
looks for column names in the outer select list.
For certain cases, a correlated subquery is optimized. For example:
val IN (SELECT key_val FROM tbl_name WHERE correlated_condition)
Otherwise, they are inefficient and likely to be slow. Rewriting the query as a join might improve performance.
FROM clause
Subqueries are legal in a SELECT statement's FROM clause.
The syntax that you'll actually see is:
SELECT ... FROM (subquery) AS name ...
The AS name clause is mandatory, because every table in a
FROM clause must have a name. Any columns in the subquery
select list must have unique names. You can find this syntax described
elsewhere in this manual, where the term used is ``derived tables.''
For illustration, assume that you have this table:
CREATE TABLE t1 (s1 INT, s2 CHAR(5), s3 FLOAT);
Here's how to use a subquery in the FROM clause, using
the example table:
INSERT INTO t1 VALUES (1,'1',1.0);
INSERT INTO t1 VALUES (2,'2',2.0);
SELECT sb1,sb2,sb3
FROM (SELECT s1 AS sb1, s2 AS sb2, s3*2 AS sb3 FROM t1) AS sb
WHERE sb1 > 1;
Result: 2, '2', 4.0.
Here's another example: Suppose that you want to know the average of a set of sums for a grouped table. This won't work:
SELECT AVG(SUM(column1)) FROM t1 GROUP BY column1;
But this query will provide the desired information:
SELECT AVG(sum_column1)
FROM (SELECT SUM(column1) AS sum_column1
FROM t1 GROUP BY column1) AS t1;
Notice that the column name used within the subquery
(sum_column1) is recognized in the outer query.
Subqueries in the FROM clause can return a scalar, column, row, or
table. At the moment, subqueries in the FROM clause cannot be
correlated subqueries.
Subqueries in the FROM clause will be executed even for the
EXPLAIN statement (that is, derived temporary tables will be built).
This occurs because upper level queries need information about all tables
during optimization phase.
There are some new error returns that apply only to subqueries. This section groups them together because reviewing them will help remind you of some points.
ERROR 1235 (ER_NOT_SUPPORTED_YET) SQLSTATE = 42000 Message = "This ve