You are on page 1of 6

the following two statements are semantically equivalent (and are handled in the same way by

the optimizer):

SELECT * FROM t1 WHERE (column1,column2) = (1,1);


SELECT * FROM t1 WHERE column1 = 1 AND column2 = 1;

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);

SELECT college, region, seed FROM tournament


ORDER BY region, seed;

SELECT college, region AS r, seed AS s FROM tournament


ORDER BY r, s;

(SELECT ... ORDER BY a) ORDER BY a DESC;

Columns selected for output can be referred to in ORDER BY and GROUP BY clauses using

column names, column aliases, or column positions. Column positions are integers and begin

with 1
SELECT college, region, seed FROM tournament
ORDER BY 2, 3;

SELECT col_name FROM tbl_name WHERE col_name > 0;

The HAVING clause can refer to aggregate functions, which the WHERE clause cannot:
SELECT user, MAX(salary) FROM users
GROUP BY user HAVING MAX(salary) > 10;

SELECT * FROM tbl LIMIT 5,10; # Retrieve rows 6-15

13.2.10.2 JOIN Syntax

MySQL supports the following JOIN syntax for the table_references part

of SELECT statements and multiple-table DELETEand UPDATE statements:


in MySQL, JOIN, CROSS JOIN, and INNER JOIN are syntactic equivalents (they can replace

each other). In standard SQL, they are not equivalent. INNER JOIN is used with

an ON clause, CROSS JOIN is used otherwise.

13.2.11.8 Derived Tables

A derived table is an expression that generates a table within the scope of a

query FROM clause. For example, a subquery in a SELECT statement FROM clause is a derived

table:
SELECT ... FROM (subquery) [AS] tbl_name ...

ALTER TABLE t2 DROP COLUMN c, DROP COLUMN d;

CREATE VIEW Syntax


CREATE
[OR REPLACE]
[ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]
[DEFINER = { user | CURRENT_USER }]
[SQL SECURITY { DEFINER | INVOKER }]
VIEW view_name [(column_list)]
AS select_statement
[WITH [CASCADED | LOCAL] CHECK OPTION]

 It is not possible to create an index on a view.

 Indexes can be used for views processed using the merge algorithm. However, a view
that is processed with the temptable algorithm is unable to take advantage of indexes
on its underlying tables (although indexes can be used during generation of the
temporary tables).

You can use DROP TABLE or ALTER TABLE to drop or alter a table that is used in a view

definition. No warning results from the DROP or ALTER operation,

mysql> CREATE TABLE t (qty INT, price INT);


mysql> INSERT INTO t VALUES(3, 50);
mysql> CREATE VIEW v AS SELECT qty, price, qty*price AS value FROM t;
mysql> SELECT * FROM v;
+------+-------+-------+
| qty | price | value |
+------+-------+-------+
| 3 | 50 | 150 |
+------+-------+-------+

DROP VIEW Syntax


DROP VIEW [IF EXISTS]
view_name [, view_name] ...
[RESTRICT | CASCADE]

ALTER VIEW Syntax


ALTER
[ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]
[DEFINER = { user | CURRENT_USER }]
[SQL SECURITY { DEFINER | INVOKER }]
VIEW view_name [(column_list)]
AS select_statement
[WITH [CASCADED | LOCAL] CHECK OPTION]

 The SELECT statement cannot refer to system variables or user-defined variables.


 Within a stored program, the SELECT statement cannot refer to program parameters or
local variables.
 The SELECT statement cannot refer to prepared statement parameters.
 Any table or view referred to in the definition must exist. If, after the view has been
created, a table or view that the definition refers to is dropped, use of the view results
in an error. To check a view definition for problems of this kind, use the CHECK
TABLE statement.
 The definition cannot refer to a TEMPORARY table, and you cannot create
a TEMPORARY view.
 You cannot associate a trigger with a view.

 Aliases for column names in the SELECT statement are checked against the maximum
column length of 64 characters (not the maximum alias length of 256 characters).
ORDER BY is permitted in a view definition, but it is ignored if you select from a view using a

statement that has its own ORDER BY.

CREATE EVENT Syntax


CREATE
[DEFINER = { user | CURRENT_USER }]
EVENT
[IF NOT EXISTS]
event_name
ON SCHEDULE schedule
[ON COMPLETION [NOT] PRESERVE]
[ENABLE | DISABLE | DISABLE ON SLAVE]
[COMMENT 'string']
DO event_body;

schedule:
AT timestamp [+ INTERVAL interval] ...
| EVERY interval
[STARTS timestamp [+ INTERVAL interval] ...]
[ENDS timestamp [+ INTERVAL interval] ...]

interval:
quantity {YEAR | QUARTER | MONTH | DAY | HOUR | MINUTE |
WEEK | SECOND | YEAR_MONTH | DAY_HOUR | DAY_MINUTE |
DAY_SECOND | HOUR_MINUTE | HOUR_SECOND | MINUTE_SECOND}

This statement creates and schedules a new event. The event will not run unless the Event

Scheduler is enabled.

CREATE INDEX Syntax


CREATE [UNIQUE | FULLTEXT | SPATIAL] INDEX index_name
[index_type]
ON tbl_name (key_part,...)
[index_option]
[algorithm_option | lock_option] ...

key_part: {col_name [(length)] | (expr)} [ASC | DESC]

index_option:
KEY_BLOCK_SIZE [=] value
| index_type
| WITH PARSER parser_name
| COMMENT 'string'
| {VISIBLE | INVISIBLE}

index_type:
USING {BTREE | HASH}

algorithm_option:
ALGORITHM [=] {DEFAULT | INPLACE | COPY}

lock_option:
LOCK [=] {DEFAULT | NONE | SHARED | EXCLUSIVE}

Optimization and Indexes

The best way to improve the performance of SELECT operations is to create indexes on one
or more of the columns that are tested in the query. The index entries act like pointers to
the table rows, allowing the query to quickly determine which rows match a condition in
the WHERE clause, and retrieve the other column values for those rows. All MySQL data types
can be indexed.
Although it can be tempting to create an indexes for every possible column used in a query,
unnecessary indexes waste space and waste time for MySQL to determine which indexes to
use. Indexes also add to the cost of inserts, updates, and deletes because each index must
be updated. You must find the right balance to achieve fast queries using the optimal set of
indexes.

Indexes are used to find rows with specific column values quickly. Without an index, MySQL

must begin with the first row and then read through the entire table to find the relevant rows.

The larger the table, the more this costs. If the table has an index for the columns in question,

MySQL can quickly determine the position to seek to in the middle of the data file without

having to look at all the data. This is much faster than reading every row sequentially.

Primary Key Optimization


The primary key for a table represents the column or set of columns that you use in your
most vital queries. It has an associated index, for fast query performance. Query
performance benefits from the NOT NULL optimization, because it cannot include
any NULL values. With the InnoDB storage engine, the table data is physically organized to
do ultra-fast lookups and sorts based on the primary key column or columns.
If your table is big and important, but does not have an obvious column or set of columns to
use as a primary key, you might create a separate column with auto-increment values to use
as the primary key. These unique IDs can serve as pointers to corresponding rows in other
tables when you join tables using foreign keys.

Foreign Key Optimization


If a table has many columns, and you query many different combinations of columns, it
might be efficient to split the less-frequently used data into separate tables with a few
columns each, and relate them back to the main table by duplicating the numeric ID column
from the main table. That way, each small table can have a primary key for fast lookups of
its data, and you can query just the set of columns that you need using a join operation.
Depending on how the data is distributed, the queries might perform less I/O and take up
less cache memory because the relevant columns are packed together on disk. (To
maximize performance, queries try to read as few data blocks as possible from disk; tables
with only a few columns can fit more rows in each data block.)

CREATE INDEX Syntax


CREATE [UNIQUE | FULLTEXT | SPATIAL] INDEX index_name
[index_type]
ON tbl_name (key_part,...)
[index_option]
[algorithm_option | lock_option] ...

key_part: {col_name [(length)] | (expr)} [ASC | DESC]


index_option:
KEY_BLOCK_SIZE [=] value
| index_type
| WITH PARSER parser_name
| COMMENT 'string'
| {VISIBLE | INVISIBLE}

index_type:
USING {BTREE | HASH}

algorithm_option:
ALGORITHM [=] {DEFAULT | INPLACE | COPY}

lock_option:
LOCK [=] {DEFAULT | NONE | SHARED | EXCLUSIVE}

Suppose that a table has the following specification:

CREATE TABLE test (


id INT NOT NULL,
last_name CHAR(30) NOT NULL,
first_name CHAR(30) NOT NULL,
PRIMARY KEY (id),
INDEX name (last_name,first_name)
);

You might also like