MySQL Summary - Quick Reference

Access Privilege System

Connecting to MySQL server

Shell>mysql [-h host_name] [-u uer_name] [-p your_password]

The initial root password is empty.

Privileges provided by MySQL

Privigele

Column

Context

Description

select

select_priv

Tables

Allow you to perform operations on rows in existing tables in a database.




insert

insert_priv

update

update_priv

delete

delete_priv

index

index_priv

Allow to create or remove indexes.

alter

alter_priv

Allows to use ALTER TABLE

create

create_priv

Databases, tables or indexes

Allows to create new databases and tables

drop

drop_priv

Databases or tables

Allows to drop databases and tables

grant

grant_priv

Alow you to give to other users those privileges you yourself possess.

reference

reference_priv


reload

reload_priv

Server administration

Are used for administrative operations.

shutdown

shutdown_priv

process

process _priv

file

file_priv

File access on server

Gives you permission to read and write files on the server using the LOAD INFILE and SELECT ... INTO OUTFILE.



Administrative commands that each administrative privilege allows you to execute

Privilege

Commands permitted to privilege holders

reload

reload, refresh, flush-privileges, flush-hosts, flush-logs, flush-tables

shutdown

shutdown

Process

processlist, kill

How the privilege system works

MySQL consideres both your hostname and user name in identifying you.

Involves two stages:

The server uses user, db and host at both stages of access control.

Table name

user

db

host

Scope fields

host

host

host


user

db

db


password

user


Privilege fields

select_priv

select_priv

select_priv


insert_priv

insert_priv

insert_priv


update_priv

update_priv

update_priv


delete_priv

delete_priv

delete_priv


index_priv

index_priv

index_priv


alter_priv

alter_priv

alter_priv


create_priv

create_priv

create_priv


drop_priv

drop_priv

drop_priv


grant_priv

grant_priv

grant_priv


reload_priv




shutdown_priv




process_priv




file_priv





For the second stage of access control, the server may, if the request involves tables, additionally consult the tables_priv and columns_priv:

Table Name

tables_priv

columns_priv

Scope fields

host

host


db

db


user

user


table_name

table_name



column_name

Privilege fields

table_priv

column_priv


column_priv


Other fields

timestamp

timestamp


grantor




Scope Fields

host

CHAR(60)

user

CHAR(16)

password

CHAR(16)

db

CHAR(64) and CHAR(60) for tables_priv and columns_priv tables.

The default value for each string is the empty string.



In the user, db and host tables all privilege fields are declared as ENUM('Y','N') - The defaul is 'N'.

Table name

Field name

Possible set elements

tables_priv

table_priv

'Select', 'Insert', 'Delete', 'Create', 'Drop', 'Grant', 'References', 'Index', 'Alter'

tables_priv

column_priv

'Select', 'Insert', 'Delete', 'References'

columns_priv

column_priv

'Select', 'Insert', 'Delete', 'References'

Adding new user privileges to MySQL

...

MySQL language reference

Lierals

Strings

A string is a sequence of characters, surrounded by either single quote (´'´) or double quote (´”´) characters.

Escape sequences:


Desc

\0

An ASCII 0 (NUL) character.

\n

A newline character.

\t

A tab character.

\r

A carriage return character.

\b

A backspace character.

\'

A single quote (´ ' ´) character.

\“

A double quote (´ ” ´) character.

\\

A backslash (´\´) character.

\%

A ´%´ character. This is used to search for literal instances of ´%´ in contexts where ´%´ would otherwise be intercepted as a wildcard character.

\_

A '_' character. This is used to search for literal instances of '_' in contexts where '_' would otherwise be interpreted as a wildcard character.

Numbers

Integers are represented as a sequence of digits. Floats use '.' as a decimal separator. Either type of number may be preceded by '-' to indicate a negative value.

Hexadecimal values

In number context acts like an 64 bit precision. In string context these acts like string where each pair of hex digits is converted to a character.

Hexadecimal strings is often used by ODBC to give values for BLOB columns.

NULL values

Are represented by \N.

Database, table, index, column and alias names

Indentifier

Max length

Allowed characters

Database

64

Any character that is allowed

Table

64


Column

64

All characters

Alias

255

All characters

You can't have ASCII(0) or ASCII(255) in an identifier.

If the identifier is a restricted word of contains special characters you must always quote it with ' when you use it.

In MySQL you can refer to a column using any of the following forms:

Column reference

Meaning

col_name

Column col_name from whichever table used in the query contains a column of that name.

tbl_name.col_name

Column col_name from table tbl_name of the current database.

db_name.tbl_name.col_name

Column name from table tbl_name of the database db_name. This form is available in MySQL 3.22 or later.

'column_name'

A column that is that a keyword od contains special characters.

Case sensitive in names

The case sensitivity of the underlying operating system determines the case sensitivity of the database and tables names.

Aliases on tables are case sensitive.

Aliases on columns are case insensitive.

User variables

Syntax: @variablename. Consists in any alphanumeric characters from the current character set. Variables don´t have to be inicailized. They contains NULL by default and can store an integer, real or a string value.

Column types

M

Maximum display size. The maximum legal size is 255.

D

Applies to floating-point types and indicate the number of digits following the decimal point. The maximum possible value is 30, but should be no greater than M-2.


Square brackets indicate parts of type specifiers that are optional.


If you specify ZEROFILL for a column, MySQL will automatically ad the UNSIGNED attribute to the column.

Numeric types

Type

Description

TINYINT [(M)] [UNSIGNED] [ZEROFILL]
1 byte

A very small integer. The signed range is -128 to 127. The unsigned range is 0 to 255.

SMALLINT [(M)] [UNSIGNED] [ZEROFILL]
2 bytes

A small integer. The signed range is -32768 to 32767. The unsigned range is 0 to 65535.

MEDIUMINT [(M)] [UNSIGNED] [ZEROFILL]
3 bytes

A medium-size integer. The signed range is -8388608 to 8388607. The unsigned range is 0 to 16777215.

INT [(M)] [UNSIGNED] [ZEROFILL]
4 bytes

A normal-size integer. The signed range is -2147483648 to 2147483647. The unsigned range is 0 to 4294967295.

INTEGER [(M)] [UNSIGNED] [ZEROFILL]
4 bytes

This is a synonym for INT.

BIGINT [(M)] [UNSIGNED] [ZEROFILL]
8 bytes

A large integer. The signed range is -9223372036854775808 to 9223372036854775807. The unsigned range is 0 to 18446744073709551615. Note that all arithmetic is done using signed BIGINT or DOUBLE values, so you shouldn't use unsigned big integers larger than 9223372036854775807 (63 bits) except with bit functions! Note that -, + and * will use BIGINT arithmetic when both arguments are INTEGER values! This means that if you multiply two big integers (or results from functions that return integers) you may get unexpected results if the result is larger than 9223372036854775807. A floating-point number. Cannot be unsigned. precision can be <=24 for a single precision floating point number and between 25 and 53 for a double precision floating point number. these types are like the FLOAT and DOUBLE types described immediately below. FLOAT(X) have the same ranges as the corresponding FLOAT and DOUBLE types, but the display size and number of decimals is undefined. In MySQL 3.23, this is a true floating point value. In earlier MySQL versions, FLOAT(precision) always has 2 decimals. This syntax is provided for ODBC compatibility.

FLOAT [(M,D)] [ZEROFILL]
4 if X <= 24 or 8 if 25 <= X <= 53
FLOAT
4 bytes

A small (single-precision) floating-point number. Cannot be unsigned. Allowable values are -3.402823466E+38 to -1.175494351E-38, 0 and 1.175494351E-38 to 3.402823466E+38. The M is the display width and D is the number of decimals. FLOAT without an argument or with an argument of <= 24 stands for a single-precision floating point number.

DOUBLE [(M,D)] [ZEROFILL]
8 bytes

A normal-size (double-precision) floating-point number. Cannot be unsigned. Allowable values are -1.7976931348623157E+308 to -2.2250738585072014E-308, 0 and 2.2250738585072014E-308 to 1.7976931348623157E+308. The M is the display width and D is the number of decimals. DOUBLE without an argument or FLOAT(X) where 25 <= X <= 53 stands for a double-precision floating point number.

DOUBLEPRECISION [(M,D)] [ZEROFILL]

These are synonyms for DOUBLE.
8 bytes

REAL [(M,D)] [ZEROFILL]

DECIMAL [(M,D)] [ZEROFILL]
M bytes (D+2, if M < D)

An unpacked floating-point number. Cannot be unsigned. Behaves like a CHAR column: ``unpacked'' means the number is stored as a string, using one character for each digit of the value. The decimal point, and, for negative numbers, the `-' sign is not counted in M. If D is 0, values will have no decimal point or fractional part. The maximum range of DECIMAL values is the same as for DOUBLE, but the actual range for a given DECIMAL column may be constrained by the choice of M and D. If D is left out it's set to 0. If M is left out it's set to 10. Note that in MySQL 3.22 the M argument includes the sign and the decimal point.

NUMERIC [(M,D)] [ZEROFILL]
M bytes (D+2, if M < D)

This is a synonym for DECIMAL.





Date and time types

Type

Description

DATE
3 bytes

A date. The supported range is '1000-01-01' to '9999-12-31'. MySQL displays DATE values in 'YYYY-MM-DD' format, but allows you to assign values to DATE columns using either strings or numbers.

DATETIME
8 bytes

A date and time combination. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59'. MySQL displays DATETIME values in 'YYYY-MM-DD HH:MM:SS' format, but allows you to assign values to DATETIME columns using either strings or numbers.

TIMESTAMP [(M)]
4 bytes

A timestamp. The range is '1970-01-01 00:00:00' to sometime in the year 2037. MySQL displays TIMESTAMP values in YYYYMMDDHHMMSS, YYMMDDHHMMSS, YYYYMMDD or YYMMDD format, depending on whether M is 14 (or missing), 12, 8 or 6, but allows you to assign values to TIMESTAMP columns using either strings or numbers. A TIMESTAMP column is useful for recording the date and time of an INSERT or UPDATE operation because it is automatically set to the date and time of the most recent operation if you don't give it a value yourself. You can also set it to the current date and time by assigning it a NULL value.

TIME
3 bytes

A time. The range is '-838:59:59' to '838:59:59'. MySQL displays TIME values in 'HH:MM:SS' format, but allows you to assign values to TIME columns using either strings or numbers.

YEAR [(2/4)]
1 byte

A year in 2- or 4- digit formats (default is 4-digit). The allowable values are 1901 to 2155, and 0000 in the 4 year format and 1970-2069 if you use the 2 digit format (70-69). MySQL displays YEAR values in YYYY format, but allows you to assign values to YEAR columns using either strings or numbers. (The YEAR type is new in MySQL 3.22.)



String (characters) types

Type

Description

CHAR(M) [BINARY]
M bytes, 1 <= M <= 255

A fixed-length string that is always right-padded with spaces to the specified length when stored. The range of M is 1 to 255 characters. Trailing spaces are removed when the value is retrieved. CHAR values are sorted and compared in case-insensitive fashion according to the default character set unless the BINARY keyword is given. NATIONAL CHAR (short form NCHAR) is the ANSI SQL way to define that a CHAR column should use the default CHARACTER set. This is default in MySQL. CHAR is a shorthand for CHARACTER.

[NATIONAL] VARCHAR(M) [BINARY]
L+1 bytes, where L <= M and 1 <= M <= 255

A variable-length string. Note: Trailing spaces are removed when the value is stored (this differs from the ANSI SQL specification). The range of M is 1 to 255 characters. VARCHAR values are sorted and compared in case-insensitive fashion unless the BINARY keyword is given. VARCHAR is a shorthand for CHARACTER VARYING.
TINYBLOB, TINYTEXT
L+1 bytes, where L < 2^8
A BLOB or TEXT column with a maximum length of 255 (2^8 - 1) characters.
BLOB, TEXT
L+2 bytes, where L < 2^16
A BLOB or TEXT column with a maximum length of 65535 (2^16 - 1) characters.
MEDIUMBLOB, MEDIUMTEXT
L+3 bytes, where L < 2^24
A BLOB or TEXT column with a maximum length of 16777215 (2^24 - 1) characters.
LONGBLOB, LONGTEXT
L+4 bytes, where L < 2^32
A BLOB or TEXT column with a maximum length of 4294967295 (2^32 - 1) characters.
ENUM('value1','value2',...)
1 or 2 bytes, depending on the number of enumeration values (65535 values maximum)
An enumeration. A string object that can have only one value, chosen from the list of values 'value1', 'value2', ..., or NULL. An ENUM can have a maximum of 65535 distinct values.
SET('value1','value2',...)
1, 2, 3, 4 or 8 bytes, depending on the number of set members (64 members maximum)
A set. A string object that can have zero or more values, each of which must be chosen from the list of values 'value1', 'value2', ... A SET can have a maximum of 64 members.

Column Indexes

All MySQL column types can be indexed. A table may have up to 16 indexes. The maximum index length is 256 bytes. An index may consist of uo to 15 columns.

Using column types from other datavbase engines

Other vendor type

MySQL type

BINARY (NUM)

CHAR(NUM) BINARY

CHAR VARYING(NUM)

VARCHAR(NUM)

FLOAT4

FLOAT

FLOAT8

DOUBLE

INT1

TINYINT

INT2

SMALLINT

INT3

MEDIUMINT

INT4

INT

INT8

BIGINT

LONG VARBINARY

MEDIUMBLOB

LONG VARCHAR

MEDIUMTEXT

MIDDLEINT

MEDIUMINT

VARBINARY(NUM)

VARCHAR(NUM) BINARY

Functions for use in SELECT and WHERE clauses.

Grouping functions

( ... )
Parentheses. Use these to force the order of evaluation in an expression.

Normal arithmetic operations

The usual arithmetic operators are available. Note that in the case of -, + and *, the result is calculated with BIGINT (64-bit) precision if both arguments are integers!

Bit functions

Operator

Description

Example

|
Bitwise OR
mysql> select 29 | 15;
        -> 31
&
Bitwise AND
mysql> select 29 & 15;
        -> 13
<<
Shifts a longlong (BIGINT) number to the left.
mysql> select 1 << 2
        -> 4
>>
Shifts a longlong (BIGINT) number to the right.
mysql> select 4 >> 2
        -> 1
~
Invert all bits.
mysql> select 5 & ~1
        -> 4
BIT_COUNT(N)
Returns the number of bits that are set in the argument N.
mysql> select BIT_COUNT(29);
        -> 4


Logical operations

All logical functions return 1 (TRUE) or 0 (FALSE).

Operator

Description

Example

NOT
!
Logical NOT. Returns 1 if the argument is 0, otherwise returns 0. Exception: NOT NULL returns NULL.
mysql> select NOT 1;
        -> 0
mysql> select NOT NULL;
        -> NULL
mysql> select ! (1+1);
        -> 0
mysql> select ! 1+1;

-> 1

The last example returns 1 because the expression evaluates the same way as (!1)+1.
OR
||
Logical OR. Returns 1 if either argument is not 0 and not NULL.
mysql> select 1 || 0;
        -> 1
mysql> select 0 || 0;
        -> 0
mysql> select 1 || NULL;
        -> 1

AND
&&

Logical AND. Returns 0 if either argument is 0 or NULL, otherwise returns 1.
mysql> select 1 && NULL;
        -> 0
mysql> select 1 && 0;
        -> 0



Comparision operators

Comparison operations result in a value of 1 (TRUE), 0 (FALSE) or NULL.

Operator

Description / Example

=
Equal 
mysql> select 1 = 0;
        -> 0
mysql> select '0' = 0;
        -> 1
mysql> select '0.0' = 0;
        -> 1
mysql> select '0.01' = 0;
        -> 0
mysql> select '.01' = 0.01;
        -> 1
<>
!=
Not equal
mysql> select '.01' <> '0.01';
-> 1
mysql> select .01 <> '0.01';
-> 0
mysql> select 'zapp' <> 'zappp';
-> 1
<=
Less than or equal
mysql> select 0.1 <= 2;
        -> 1

<

Less than
mysql> select 2 <= 2;
        -> 1
>=
Greater than or equal
mysql> select 2 >= 2;
        -> 1

>

Greater than
mysql> select 2 > 2;
        -> 0
<=>
Null safe equal
mysql> select 1 <=> 1, NULL <=> NULL, 1 <=> NULL;
        -> 1 1 0
IS NULL
IS NOT NULL
Test whether or not a value is or is not NULL  
mysql> select 1 IS NULL, 0 IS NULL, NULL IS NULL:
        -> 0 0 1
mysql> select 1 IS NOT NULL, 0 IS NOT NULL, NULL IS NOT NULL;
        -> 1 1 0
expr BETWEEN min AND max
If expr is greater than or equal to min and expr is less than or equal to max, BETWEEN returns 1, otherwise it returns 0. This is equivalent to the expression (min <= expr AND expr <= max) if all the arguments are of the same type. The first argument (expr) determines how the comparison is performed. If expr is a case-insensitive string expression, a case-insensitive string comparison is done. If expr is a case-sensitive string expression, a case-sensitive string comparison is done. If expr is an integer expression, an integer comparison is done. Otherwise, a floating-point (real) comparison is done.  
mysql> select 1 BETWEEN 2 AND 3;
        -> 0
mysql> select 'b' BETWEEN 'a' AND 'c';
        -> 1
mysql> select 2 BETWEEN 2 AND '3';
        -> 1
mysql> select 2 BETWEEN 2 AND 'x-3';
        -> 0
Expr IN (value,...)
Returns 1 if expr is any of the values in the IN list, else returns 0. If all values are constants, then all values are evaluated according to the type of expr and sorted. The search for the item is then done using a binary search. This means IN is very quick if the IN value list consists entirely of constants. If expr is a case-sensitive string expression, the string comparison is performed in case-sensitive fashion.  
mysql> select 2 IN (0,3,5,'wefwf');
        -> 0
mysql> select 'wefwf' IN (0,3,5,'wefwf');
        -> 1
expr NOT IN (value,...)
Same as NOT (expr IN (value,...)).
ISNULL(expr)
If expr is NULL, ISNULL() returns 1, otherwise it returns 0.
mysql> select ISNULL(1+1);
-> 0
mysql> select ISNULL(1/0);
-> 1
Note that a comparison of NULL values using = will always be false!
COALESCE(list)
Returns first non-NULL element in list.
mysql> select COALESCE(NULL,1);
        -> 1
mysql> select COALESCE(NULL,NULL,NULL);
        -> NULL
INTERVAL(N,N1,N2,N3,...)
Returns 0 if N < N1, 1 if N < N2 and so on. All arguments are treated as integers. It is required that N1 < N2 < N3 < ... < Nn for this function to work correctly. This is because a binary search is used (very fast).  
mysql> select INTERVAL(23, 1, 15, 17, 30, 44, 200);
        -> 3
mysql> select INTERVAL(10, 1, 10, 100, 1000);
        -> 2
mysql> select INTERVAL(22, 23, 30, 44, 200);
        -> 0



String comparision functions

Normally, if any expression in a string comparison is case sensitive, the comparison is performed in case-sensitive fashion.

expr LIKE pat [ESCAPE 'escape-char']
Pattern matching using SQL simple regular expression comparison. Returns 1 (TRUE) or 0 (FALSE). With LIKE you can use the following two wildcard characters in the pattern:

%

Matches any number of characters, even zero characters

_

Matches exactly one character

mysql> select 'David!' LIKE 'David_';
        -> 1
mysql> select 'David!' LIKE '%D%v%';
        -> 1
        
To test for literal instances of a wildcard character, precede the character with the escape character. If you don't specify the ESCAPE character, `\' is assumed:

\%

Matches one % character

\_

Matches one _ character

mysql> select 'David!' LIKE 'David\_';
        -> 0
mysql> select 'David_' LIKE 'David\_';
        -> 1
        
To specify a different escape character, use the ESCAPE clause:
mysql> select 'David_' LIKE 'David|_' ESCAPE '|';
        -> 1
        
LIKE is allowed on numeric expressions! (This is a MySQL extension to the ANSI SQL LIKE.)
mysql> select 10 LIKE '1%';
        -> 1
        
Note: Because MySQL uses the C escape syntax in strings (e.g., `\n'), you must double any `\' that you use in your LIKE strings. For example, to search for `\n', specify it as `\\n'. To search for `\', specify it as `\\\\' (the backslashes are stripped once by the parser, and another time when the pattern match is done, leaving a single backslash to be matched).
expr NOT LIKE pat [ESCAPE 'escape-char']
Same as NOT (expr LIKE pat [ESCAPE 'escape-char']).
expr REGEXP pat
expr RLIKE pat
Performs a pattern match of a string expression expr against a pattern pat. The pattern can be an extended regular expression. See section H Description of MySQL regular expression syntax. Returns 1 if expr matches pat, otherwise returns 0. RLIKE is a synonym for REGEXP, provided for mSQL compatibility. Note: Because MySQL uses the C escape syntax in strings (e.g., `\n'), you must double any `\' that you use in your REGEXP strings. In MySQL 3.23.4 REGEXP is case insensitive for normal (not binary) strings.
mysql> select 'Monty!' REGEXP 'm%y%%';
        -> 0
mysql> select 'Monty!' REGEXP '.*';
        -> 1
mysql> select 'new*\n*line' REGEXP 'new\\*.\\*line';
        -> 1
mysql> select "a" REGEXP "A", "a" REGEXP BINARY "A";
        -> 1  0
        
REGEXP and RLIKE use the current character set (ISO-8859-1 Latin1 by default) when deciding the type of a character.
expr NOT REGEXP pat
expr NOT RLIKE pat
Same as NOT (expr REGEXP pat).
STRCMP(expr1,expr2)
STRCMP() returns 0 if the strings are the same, -1 if the first argument is smaller than the second according to the current sort order, and 1 otherwise.
mysql> select STRCMP('text', 'text2');
        -> -1
mysql> select STRCMP('text2', 'text');
        -> 1
mysql> select STRCMP('text', 'text');
        -> 0

Cast opertors

BINARY
The BINARY operator casts the string following it to a binary string. This is an easy way to force a column comparison to be case sensitive even if the column isn't defined as BINARY or BLOB.
mysql> select "a" = "A";
        -> 1
mysql> select BINARY "a" = "A";
        -> 0
        
BINARY was introduced in MySQL 3.23.0

Control flow functions

IFNULL(expr1,expr2)
If expr1 is not NULL, IFNULL() returns expr1, else it returns expr2. IFNULL() returns a numeric or string value, depending on the context in which it is used.
mysql> select IFNULL(1,0);
        -> 1
mysql> select IFNULL(0,10);
        -> 0
mysql> select IFNULL(1/0,10);
        -> 10
mysql> select IFNULL(1/0,'yes');
        -> 'yes'
        
IF(expr1,expr2,expr3)
If expr1 is TRUE (expr1 <> 0 and expr1 <> NULL) then IF() returns expr2, else it returns expr3. IF() returns a numeric or string value, depending on the context in which it is used.
mysql> select IF(1>2,2,3);
        -> 3
mysql> select IF(1<2,'yes','no');
        -> 'yes'
mysql> select IF(strcmp('test','test1'),'yes','no');
        -> 'no'
        
expr1 is evaluated as an integer value, which means that if you are testing floating-point or string values, you should do so using a comparison operation.
mysql> select IF(0.1,1,0);
        -> 0
mysql> select IF(0.1<>0,1,0);
        -> 1
        
In the first case above, IF(0.1) returns 0 because 0.1 is converted to an integer value, resulting in a test of IF(0). This may not be what you expect. In the second case, the comparison tests the original floating-point value to see whether it is non-zero. The result of the comparison is used as an integer.
CASE value WHEN [compare-value] THEN result [WHEN [compare-value] THEN result ...] [ELSE result] END
CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...] [ELSE result] END
The first version returns the result where value=compare-value. The second version returns the result for the first condition which is true. If there was no matching result value, then the result after ELSE is returned. If there is no ELSE part then NULL is returned.
mysql> SELECT CASE 1 WHEN 1 THEN "one" WHEN 2 THEN "two" ELSE "more" END;
       -> "one"
mysql> SELECT CASE WHEN 1>0 THEN "true" ELSE "false" END;
       -> "true"
mysql> SELECT CASE BINARY "B" when "a" then 1 when "b" then 2 END;
       -> NULL

Mathematical functions

All mathematical functions return NULL in case of an error.

Function

Description

ABS(X)
Returns the absolute value of X
SIGN(X)

Returns the sign of the argument as -1, 0 or 1, depending on whether X is negative, zero, or positive.
MOD(N,M)
%
Modulo (like the % operator in C). Returns the remainder of N divided by M.
FLOOR(X)
Returns the largest integer value not greater than X.
CEILING(X)
Returns the smallest integer value not less than X.
ROUND(X)
Returns the argument X, rounded to an integer.
ROUND(X,D)
Returns the argument X, rounded to a number with D decimals. If D is 0, the result will have no decimal point or fractional part.
EXP(X)

Returns the value of e (the base of natural logarithms) raised to the power of X.
LOG(X)
Returns the natural logarithm of X. If you want the log of a number X to some arbitary base B, use the formula LOG(X)/LOG(B).
LOG10(X)
Returns the base-10 logarithm of X.
POW(X,Y)
POWER(X,Y)
Returns the value of X raised to the power of Y.
SQRT(X)
Returns the non-negative square root of X.
PI()
Returns the value of PI.
COS(X)
Returns the cosine of X, where X is given in radians.
SIN(X)
Returns the sine of X, where X is given in radians.
TAN(X)
Returns the tangent of X, where X is given in radians.
ACOS(X)
Returns the arc cosine of X, that is, the value whose cosine is X. Returns NULL if X is not in the range -1 to 1.
ASIN(X)
Returns the arc sine of X, that is, the value whose sine is X. Returns NULL if X is not in the range -1 to 1.
ATAN(X)
Returns the arc tangent of X, that is, the value whose tangent is X.
ATAN2(X,Y)

Returns the arc tangent of the two variables X and Y. It is similar to calculating the arc tangent of Y / X, except that the signs of both arguments are used to determine the quadrant of the result.
COT(X)
Returns the cotangent of X.
RAND()
RAND(N)

Returns a random floating-point value in the range 0 to 1.0. If an integer argument N is specified, it is used as the seed value.
LEAST(X,Y,...)

With two or more arguments, returns the smallest (minimum-valued) argument. The arguments are compared using the following rules:
  • If the return value is used in an INTEGER context, or all arguments are integer-valued, they are compared as integers.
  • If the return value is used in a REAL context, or all arguments are real-valued, they are compared as reals.
  • If any argument is a case-sensitive string, the arguments are compared as case-sensitive strings.
  • In other cases, the arguments are compared as case-insensitive strings.
GREATEST(X,Y,...)

Returns the largest (maximum-valued) argument. The arguments are compared using the same rules as for LEAST.
In MySQL versions prior to 3.22.5, you can use MAX() instead of GREATEST.
DEGREES(X)
Returns the argument X, converted from radians to degrees.
RADIANS(X)
Returns the argument X, converted from degrees to radians.
TRUNCATE(X,D)

Returns the number X, truncated to D decimals. If D is 0, the result will have no decimal point or fractional part.

String Functions

Function / Description

ASCII(str)
Returns the ASCII code value of the leftmost character of the string str. Returns 0 if str is the empty string. Returns NULL if str is NULL.
ORD(str)
If the leftmost character of the string str is a multi-byte character, returns the code of multi-byte character by returning the ASCII code value of the character in the format of: ((first byte ASCII code)*256+(second byte ASCII code))[*256+third byte ASCII code...]. If the leftmost character is not a multi-byte character, returns the same value as the like ASCII() function does.
CONV(N,from_base,to_base)
Converts numbers between different number bases. Returns a string representation of the number N, converted from base from_base to base to_base. Returns NULL if any argument is NULL. The argument N is interpreted as an integer, but may be specified as an integer or a string. The minimum base is 2 and the maximum base is 36. If to_base is a negative number, N is regarded as a signed number. Otherwise, N is treated as unsigned. CONV works with 64-bit precision.
BIN(N)
Returns a string representation of the binary value of N, where N is a longlong (BIGINT) number. This is equivalent to CONV(N,10,2). Returns NULL if N is NULL.
OCT(N)
Returns a string representation of the octal value of N, where N is a longlong number. This is equivalent to CONV(N,10,8). Returns NULL if N is NULL.
HEX(N)
Returns a string representation of the hexadecimal value of N, where N is a longlong (BIGINT) number. This is equivalent to CONV(N,10,16). Returns NULL if N is NULL
CHAR(N,...)
CHAR() interprets the arguments as integers and returns a string consisting of the characters given by the ASCII code values of those integers. NULL values are skipped.
CONCAT(str1,str2,...)
Returns the string that results from concatenating the arguments. Returns NULL if any argument is NULL. May have more than 2 arguments. A numeric argument is converted to the equivalent string form.
LENGTH(str)
OCTET_LENGTH(str)
CHAR_LENGTH(str)
CHARACTER_LENGTH(str)
Returns the length of the string str.
Note that for CHAR_LENGTH() multi-byte characters are only counted once.
LOCATE(substr,str)
POSITION(substr IN str)
Returns the position of the first occurrence of substring substr in string str. Returns 0 if substr is not in str. .
LOCATE(substr,str,pos)
Returns the position of the first occurrence of substring substr in string str, starting at position pos. Returns 0 if substr is not in str
INSTR(str,substr)
Returns the position of the first occurrence of substring substr in string str. This is the same as the two-argument form of LOCATE(), except that the arguments are swapped.
LPAD(str,len,padstr)
Returns the string str, left-padded with the string padstr until str is len characters long.
RPAD(str,len,padstr)
Returns the string str, right-padded with the string padstr until str is len characters long.
LEFT(str,len)
Returns the leftmost len characters from the string str.
RIGHT(str,len)
Returns the rightmost len characters from the string str.
SUBSTRING(str,pos,len)
SUBSTRING(str FROM pos FOR len)
MID(str,pos,len)
Returns a substring len characters long from string str, starting at position pos. The variant form that uses FROM is ANSI SQL92 syntax.
SUBSTRING(str,pos)
SUBSTRING(str FROM pos)
Returns a substring from string str starting at position pos.
SUBSTRING_INDEX(str,delim,count)
Returns the substring from string str after count occurrences of the delimiter delim. If count is positive, everything to the left of the final delimiter (counting from the left) is returned. If count is negative, everything to the right of the final delimiter (counting from the right) is returned.
LTRIM(str)
Returns the string str with leading space characters removed.
RTRIM(str)
Returns the string str with trailing space characters removed.
TRIM([[BOTH | LEADING | TRAILING] [remstr] FROM] str)
Returns the string str with all remstr prefixes and/or suffixes removed. If none of the specifiers BOTH, LEADING or TRAILING are given, BOTH is assumed. If remstr is not specified, spaces are removed.
SOUNDEX(str)
Returns a soundex string from str. Two strings that sound ``about the same'' should have identical soundex strings. A ``standard'' soundex string is 4 characters long, but the SOUNDEX() function returns an arbitrarily long string. You can use SUBSTRING() on the result to get a ``standard'' soundex string. All non-alphanumeric characters are ignored in the given string. All international alpha characters outside the A-Z range are treated as vowels.
SPACE(N)
Returns a string consisting of N space characters.
REPLACE(str,from_str,to_str)
Returns the string str with all all occurrences of the string from_str replaced by the string to_str.
REPEAT(str,count)
Returns a string consisting of the string str repeated count times. If count <= 0, returns an empty string. Returns NULL if str or count are NULL.
REVERSE(str)
Returns the string str with the order of the characters reversed.
INSERT(str,pos,len,newstr)
Returns the string str, with the substring beginning at position pos and len characters long replaced by the string newstr.
ELT(N,str1,str2,str3,...)
Returns str1 if N = 1, str2 if N = 2, and so on. Returns NULL if N is less than 1 or greater than the number of arguments. ELT() is the complement of FIELD().
FIELD(str,str1,str2,str3,...)
Returns the index of str in the str1, str2, str3, ... list. Returns 0 if str is not found. FIELD() is the complement of ELT().
FIND_IN_SET(str,strlist)
Returns a value 1 to N if the string str is in the list strlist consisting of N substrings. A string list is a string composed of substrings separated by `,' characters. If the first argument is a constant string and the second is a column of type SET, the FIND_IN_SET() function is optimized to use bit arithmetic! Returns 0 if str is not in strlist or if strlist is the empty string. Returns NULL if either argument is NULL. This function will not work properly if the first argument contains a `,'.
MAKE_SET(bits,str1,str2,...)
Returns a set (a string containing substrings separated by `,' characters) consisting of the strings that have the corresponding bit in bits set. str1 corresponds to bit 0, str2 to bit 1, etc. NULL strings in str1, str2, ... are not appended to the result.
EXPORT_SET(bits,on,off,[separator,[number_of_bits]])
Returns a string where for every bit set in 'bit', you get a 'on' string and for every reset bit you get an 'off' string. Each string is separated with 'separator' (default ',') and only 'number_of_bits' (default 64) of 'bits' is used.
LCASE(str)
LOWER(str)

Returns the string str with all characters changed to lowercase according to the current character set mapping (the default is ISO-8859-1 Latin1). This function is multi-byte safe.
UCASE(str)
UPPER(str)

Returns the string str with all characters changed to uppercase according to the current character set mapping (the default is ISO-8859-1 Latin1).
LOAD_FILE(file_name)
Reads the file and returns the file contents as a string. The file must be on the server, you must specify the full pathname to the file, and you must have the file privilege. The file must be readable by all and be smaller than max_allowed_packet. If the file doesn't exist or can't be read due to one of the above reasons, the function returns NULL.

Date and time functions

Function / Description

DAYOFWEEK(date)
Returns the weekday index for date (1 = Sunday, 2 = Monday, ... 7 = Saturday). These index values correspond to the ODBC standard.
WEEKDAY(date)
Returns the weekday index for date (0 = Monday, 1 = Tuesday, ... 6 = Sunday).
DAYOFMONTH(date)
Returns the day of the month for date, in the range 1 to 31.
DAYOFYEAR(date)
Returns the day of the year for date, in the range 1 to 366.
MONTH(date)
Returns the month for date, in the range 1 to 12.
DAYNAME(date)
Returns the name of the weekday for date.
MONTHNAME(date)
Returns the name of the month for date.
QUARTER(date)
Returns the quarter of the year for date, in the range 1 to 4.
WEEK(date)
WEEK(date,first)
With a single argument, returns the week for date, in the range 0 to 52, for locations where Sunday is the first day of the week. The two-argument form of WEEK() allows you to specify whether the week starts on Sunday or Monday. The week starts on Sunday if the second argument is 0, on Monday if the second argument is 1.
YEAR(date)
Returns the year for date, in the range 1000 to 9999.
HOUR(time)
Returns the hour for time, in the range 0 to 23.
MINUTE(time)
Returns the minute for time, in the range 0 to 59.
SECOND(time)
Returns the second for time, in the range 0 to 59.
PERIOD_ADD(P,N)
Adds N months to period P (in the format YYMM or YYYYMM). Returns a value in the format YYYYMM. Note that the period argument P is not a date value.
PERIOD_DIFF(P1,P2)
Returns the number of months between periods P1 and P2. P1 and P2 should be in the format YYMM or YYYYMM. Note that the period arguments P1 and P2 are not date values.
DATE_ADD(date,INTERVAL expr type)
DATE_SUB(date,INTERVAL expr type)
ADDDATE(date,INTERVAL expr type)
SUBDATE(date,INTERVAL expr type)
These functions perform date arithmetic. They are new for MySQL 3.22. ADDDATE() and SUBDATE() are synonyms for DATE_ADD() and DATE_SUB(). In MySQL 3.23, you can use + and - instead of DATE_ADD() and DATE_SUB(). (See example) date is a DATETIME or DATE value specifying the starting date. expr is an expression specifying the interval value to be added or substracted from the starting date. expr is a string; it may start with a `-' for negative intervals. type is a keyword indicating how the expression should be interpreted. The EXTRACT(type FROM date) function returns the 'type' interval from the date. The following table shows how the type and expr arguments are related:

type value

Meaning

Expected expr format

SECOND

Seconds

SECONDS

MINUTE

Minutes

MINUTES

HOUR

Hours

HOURS

DAY

Days

DAYS

MONTH

Months

MONTHS

YEAR

Years

YEARS

MINUTE_SECOND

Minutes and seconds

"MINUTES:SECONDS"

HOUR_MINUTE

Hours and minutes

"HOURS:MINUTES"

DAY_HOUR

Days and hours

"DAYS HOURS"

YEAR_MONTH

Years and months

"YEARS-MONTHS"

HOUR_SECOND

Hours, minutes,

"HOURS:MINUTES:SECONDS"

DAY_MINUTE

Days, hours, minutes

"DAYS HOURS:MINUTES"

DAY_SECOND

Days, hours, minutes, seconds

"DAYS HOURS:MINUTES:SECONDS"

MySQL allows any punctuation delimiter in the expr format. The ones shown in the table are the suggested delimiters. If the date argument is a DATE value and your calculations involve only YEAR, MONTH and DAY parts (that is, no time parts), the result is a DATE value. Otherwise the result is a DATETIME value.
If you specify an interval value that is too short (does not include all the interval parts that would be expected from the type keyword), MySQL assumes you have left out the leftmost parts of the interval value. For example, if you specify a type of DAY_SECOND, the value of expr is expected to have days, hours, minutes and seconds parts. If you specify a value like "1:10", MySQL assumes that the days and hours parts are missing and the value represents minutes and seconds. In other words, "1:10" DAY_SECOND is interpreted in such a way that it is equivalent to "1:10" MINUTE_SECOND. This is analogous to the way that MySQL interprets TIME values as representing elapsed time rather than as time of day. If you use really incorrect dates, the result is NULL. If you add MONTH, YEAR_MONTH or YEAR and the resulting date has a day that is larger than the maximum day for the new month, the day is adjusted to the maximum days in the new month.
Note from the preceding example that the word INTERVAL and the type keyword are not case sensitive.
TO_DAYS(date)
Given a date date, returns a daynumber (the number of days since year 0).
TO_DAYS() is not intended for use with values that precede the advent of the Gregorian calendar (1582).
FROM_DAYS(N)
Given a daynumber N, returns a DATE value.

FROM_DAYS() is not intended for use with values that precede the advent of the Gregorian calendar (1582).

DATE_FORMAT(date,format)
Formats the date value according to the format string. The following specifiers may be used in the format string:
All other characters are just copied to the result without interpretation.
As of MySQL 3.23, the % is required before a format specifier characters. In earlier versions of MySQL, % was optional.

%M

Month name (January..December)

%W

Weekday name (Sunday..Saturday)

%D

Day of the month with english suffix (1st, 2nd, 3rd, etc.)

%Y

Year, numeric, 4 digits

%y

Year, numeric, 2 digits

%a

Abbreviated weekday name (Sun..Sat)

%d

Day of the month, numeric (00..31)

%e

Day of the month, numeric (0..31)

%m

Month, numeric (01..12)

%c

Month, numeric (1..12)

%b

Abbreviated month name (Jan..Dec)

%j

Day of year (001..366)

%H

Hour (00..23)

%k

Hour (0..23)

%h

Hour (01..12)

%I

Hour (01..12)

%l

Hour (1..12)

%i

Minutes, numeric (00..59)

%r

Time, 12-hour (hh:mm:ss [AP]M)

%T

Time, 24-hour (hh:mm:ss)

%S

Seconds (00..59)

%s

Seconds (00..59)

%p

AM or PM

%w

Day of the week (0=Sunday..6=Saturday)

%U

Week (0..52), where Sunday is the first day of the week

%u

Week (0..52), where Monday is the first day of the week

%%

A literal `%'.

TIME_FORMAT(time,format)
This is used like the DATE_FORMAT() function above, but the format string may contain only those format specifiers that handle hours, minutes and seconds. Other specifiers produce a NULL value or 0.
CURDATE()
CURRENT_DATE
Returns today's date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the function is used in a string or numeric context.
CURTIME()
CURRENT_TIME
Returns the current time as a value in 'HH:MM:SS' or HHMMSS format, depending on whether the function is used in a string or numeric context.
NOW()
SYSDATE()
CURRENT_TIMESTAMP
Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS format, depending on whether the function is used in a string or numeric context.
UNIX_TIMESTAMP()
UNIX_TIMESTAMP(date)
If called with no argument, returns a Unix timestamp (seconds since '1970-01-01 00:00:00' GMT). If UNIX_TIMESTAMP() is called with a date argument, it returns the value of the argument as seconds since '1970-01-01 00:00:00' GMT. date may be a DATE string, a DATETIME string, a TIMESTAMP, or a number in the format YYMMDD or YYYYMMDD in local time.
When UNIX_TIMESTAMP is used on a TIMESTAMP column, the function will receive the value directly, with no implicit ``string-to-unix-timestamp'' conversion.
FROM_UNIXTIME(unix_timestamp)
Returns a representation of the unix_timestamp argument as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS format, depending on whether the function is used in a string or numeric context.
FROM_UNIXTIME(unix_timestamp,format)
Returns a string representation of the Unix timestamp, formatted according to the format string. format may contain the same specifiers as those listed in the entry for the DATE_FORMAT() function.
SEC_TO_TIME(seconds)
Returns the seconds argument, converted to hours, minutes and seconds, as a value in 'HH:MM:SS' or HHMMSS format, depending on whether the function is used in a string or numeric context.
TIME_TO_SEC(time)
Returns the time argument, converted to seconds.

Miscellaneous functions

Function / Description

DATABASE()
Returns the current database name.
If there is no current database, DATABASE() returns the empty string.
USER()
SYSTEM_USER()
SESSION_USER()
Returns the current MySQL user name.
In MySQL 3.22.11 or later, this includes the client hostname as well as the username. You can extract just the username part like this (which works whether or not the value includes a hostname part):
PASSWORD(str)
Calculates a password string from the plaintext password str. This is the function that is used for encrypting MySQL passwords for storage in the Password column of the user grant table.
PASSWORD() encryption is non-reversible. PASSWORD() does not perform password encryption in the same way that Unix passwords are encrypted. You should not assume that if your Unix password and your MySQL password are the same, PASSWORD() will result in the same encrypted value as is stored in the Unix password file. See ENCRYPT().
ENCRYPT(str[,salt])
Encrypt str using the Unix crypt() system call. The salt argument should be a string with two characters. (As of MySQL 3.22.16, salt may be longer than two characters.)
If crypt() is not available on your system, ENCRYPT() always returns NULL. ENCRYPT() ignores all but the first 8 characters of str, at least on some systems. This will be determined by the behavior of the underlying crypt() system call.
ENCODE(str,pass_str)
Encrypt str using pass_str as the password. To decrypt the result, use DECODE(). The results is a binary string. If you want to save it in a column, use a BLOB column type.
DECODE(crypt_str,pass_str)
Descrypts the encrypted string crypt_str using pass_str as the password. crypt_str should be a string returned from ENCODE().
MD5(string)
Calculates a MD5 checksum for the string. Value is returned as a 32 long hex number that may, for example, be used as a hash key.
This is a "RSA Data Security, Inc. MD5 Message-Digest Algorithm".
LAST_INSERT_ID([expr])
Returns the last automatically generated value that was inserted into an AUTO_INCREMENT column.
The last ID that was generated is maintained in the server on a per-connection basis. It will not be changed by another client. It will not even be changed if you update another AUTO_INCREMENT column with a non-magic value (that is, a value that is not NULL and not 0). If expr is given as an argument to LAST_INSERT_ID() in an UPDATE clause, then the value of the argument is returned as a LAST_INSERT_ID() value. This can be used to simulate sequences: First create the table:
mysql> create table sequence (id int not null);
mysql> insert into sequence values (0);
                                        
                                        
Then the table can be used to generate sequence numbers like this:
mysql> update sequence set id=LAST_INSERT_ID(id+1);
                                        
                                        
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. You can retrieve the new ID as you would read any normal AUTO_INCREMENT value in MySQL. For example, LAST_INSERT_ID() (without an argument) will return the new ID. The C API function mysql_insert_id() can also be used to get the value.
FORMAT(X,D)
Formats the number X to a format like '#,###,###.##', rounded to D decimals. If D is 0, the result will have no decimal point or fractional part.
VERSION()
Returns a string indicating the MySQL server version.
GET_LOCK(str,timeout)
Tries to obtain a lock with a name given by the string str, with a timeout of timeout seconds. Returns 1 if the lock was obtained successfully, 0 if the attempt timed out, or NULL if an error occurred (such as running out of memory or the thread was killed with mysqladmin kill). A lock is released when you execute RELEASE_LOCK(), execute a new GET_LOCK() or the thread terminates. This function can be used to implement application locks or to simulate record locks. It blocks requests by other clients for locks with the same name; clients that agree on a given lock string name can use the string to perform cooperative advisory locking.
Note that the second RELEASE_LOCK() call returns NULL because the lock "lock1" was automatically released by the second GET_LOCK() call.
RELEASE_LOCK(str)
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 wasn't locked by this thread (in which case the lock is not released) and NULL if the named lock didn't exist. The lock will not exist if it was never obtained by a call to GET_LOCK() or if it already has been released.
BENCHMARK(count,expr)
The BENCHMARK() function executes the expression expr repeatedly count times. It may be used to time how fast MySQL processes the expression. The result value is always 0. The intended use is in the mysql client, which reports query execution times.
The time reported is elapsed time on the client end, not CPU time on the server end. It may be advisable to execute BENCHMARK() several times, and interpret the result with regard to how heavily loaded the server machine is.

Functions for use with GROUP BY clause

Function / Description

COUNT(expr)
Returns a count of the number of non-NULL values in the rows retrieved by a SELECT statement.
COUNT(*) is somewhat different in that it returns a count of the number of rows retrieved, whether or not they contain NULL values. COUNT(*) is optimized to return very quickly if the SELECT retrieves from one table, no other columns are retrieved and there is no WHERE clause.
COUNT(DISTINCT expr,[expr...])
Returns a count of the number of different values.
In MySQL you can get the number of distinct expressions combinations by giving a list of expressions. In ANSI SQL you would have to do a concatenation of all expressions inside CODE(DISTINCT ..).
AVG(expr)
Returns the average value of expr.
MIN(expr)
MAX(expr)
Returns the minimum or maximum value of expr. MIN() and MAX() may take a string argument; in such cases they return the minimum or maximum string value.
SUM(expr)
Returns the sum of expr. Note that if the return set has no rows, it returns NULL!
STD(expr)
STDDEV(expr)
Returns the standard deviation of expr. This is an extension to ANSI SQL. The STDDEV() form of this function is provided for Oracle compatability.
BIT_OR(expr)
Returns the bitwise OR of all bits in expr. The calculation is performed with 64-bit (BIGINT precision.
BIT_AND(expr)
Returns the bitwise AND of all bits in expr. The calculation is performed with 64-bit (BIGINT precision.

CREATE DATABASE syntax

CREATE DATABASE db_name

DROP DATABASE syntax

DROP DATABASE [IF EXISTS] db_name

DROP DATABASE drops all tables in the database and deletes the database.

CREATE TABLE syntax

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name [(create_definition,...)]
[table_options] [select_statement]

create_definition:
  col_name type [NOT NULL | NULL] [DEFAULT default_value] [AUTO_INCREMENT]
            [PRIMARY KEY] [reference_definition]
  or    PRIMARY KEY (index_col_name,...)
  or    KEY [index_name] (index_col_name,...)
  or    INDEX [index_name] (index_col_name,...)
  or    UNIQUE [INDEX] [index_name] (index_col_name,...)
  or    [CONSTRAINT symbol] FOREIGN KEY index_name (index_col_name,...)
            [reference_definition]
  or    CHECK (expr)

type:
        TINYINT[(length)] [UNSIGNED] [ZEROFILL]
  or    SMALLINT[(length)] [UNSIGNED] [ZEROFILL]
  or    MEDIUMINT[(length)] [UNSIGNED] [ZEROFILL]
  or    INT[(length)] [UNSIGNED] [ZEROFILL]
  or    INTEGER[(length)] [UNSIGNED] [ZEROFILL]
  or    BIGINT[(length)] [UNSIGNED] [ZEROFILL]
  or    REAL[(length,decimals)] [UNSIGNED] [ZEROFILL]
  or    DOUBLE[(length,decimals)] [UNSIGNED] [ZEROFILL]
  or    FLOAT[(length,decimals)] [UNSIGNED] [ZEROFILL]
  or    DECIMAL(length,decimals) [UNSIGNED] [ZEROFILL]
  or    NUMERIC(length,decimals) [UNSIGNED] [ZEROFILL]
  or    CHAR(length) [BINARY]
  or    VARCHAR(length) [BINARY]
  or    DATE
  or    TIME
  or    TIMESTAMP
  or    DATETIME
  or    TINYBLOB
  or    BLOB
  or    MEDIUMBLOB
  or    LONGBLOB
  or    TINYTEXT
  or    TEXT
  or    MEDIUMTEXT
  or    LONGTEXT
  or    ENUM(value1,value2,value3,...)
  or    SET(value1,value2,value3,...)

index_col_name:
        col_name [(length)]

reference_definition:
        REFERENCES tbl_name [(index_col_name,...)]
                   [MATCH FULL | MATCH PARTIAL]
                   [ON DELETE reference_option]
                   [ON UPDATE reference_option]

reference_option:
        RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT

table_options:
        TYPE = {ISAM | MYISAM | HEAP}
or      AUTO_INCREMENT = #
or      AVG_ROW_LENGTH = #
or      CHECKSUM = {0 | 1}
or      COMMENT = "string"
or      MAX_ROWS = #
or      MIN_ROWS = #
or      PACK_KEYS = {0 | 1}
or      PASSWORD = "string"
or      DELAY_KEY_WRITE = {0 | 1}
or      ROW_FORMAT= { default | dynamic | static | compressed }

select_statement:
        [IGNORE | REPLACE] SELECT ...  (Some legal select statement)

CREATE TABLE creates a table with the given name in the current database.

ALTER TABLE syntax

ALTER [IGNORE] TABLE tbl_name alter_spec [, alter_spec ...]

alter_specification:
        ADD [COLUMN] create_definition [FIRST | AFTER column_name ]
  or    ADD INDEX [index_name] (index_col_name,...)
  or    ADD PRIMARY KEY (index_col_name,...)
  or    ADD UNIQUE [index_name] (index_col_name,...)
  or    ALTER [COLUMN] col_name {SET DEFAULT literal | DROP DEFAULT}
  or    CHANGE [COLUMN] old_col_name create_definition
  or    MODIFY [COLUMN] create_definition
  or    DROP [COLUMN] col_name
  or    DROP PRIMARY KEY
  or    DROP INDEX index_name
  or    RENAME [AS] new_tbl_name
  or    table_options

ALTER TABLE allows you to change the structure of an existing table.

OPTIMIZE TABLE syntax

OPTIMIZE TABLE tbl_name

OPTIMZE TABLE should be used if you have deleted a large part of a table or if you have made many changes to a table with variable-length rows (tables that have VARCHAR, BLOB or TEXT columns). Deleted records are maintained in a linked list and subsequent INSERT operations reuse old record positions. You can use OPTIMIZE TABLE to reclaim the unused space.

DROP TABLE syntax

DROP TABLE [IF EXISTS] tbl_name [, tbl_name,...]

DROP TABLE removes one or more tables. All table data and the table definition are removed, so be careful with this command!

In MySQL 3.22 or later, you can use the keywords IF EXISTS to prevent an error from occurring for tables that don't exist.

DELETE syntax

DELETE [LOW_PRIORITY] FROM tbl_name
    [WHERE where_definition] [LIMIT rows]

DELETE deletes rows from tbl_name that satisfy the condition given by where_definition, and returns the number of records deleted.

If you issue a DELETE with no WHERE clause, all rows are deleted.

SELECT syntax

SELECT [STRAIGHT_JOIN] [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [HIGH_PRIORITY]
       [DISTINCT | DISTINCTROW | ALL]
    select_expression,...
    [INTO {OUTFILE | DUMPFILE} 'file_name' export_options]
    [FROM table_references
        [WHERE where_definition]
        [GROUP BY col_name,...]
        [HAVING where_definition]
        [ORDER BY {unsigned_integer | col_name | formula} [ASC | DESC] ,...]
        [LIMIT [offset,] rows]
        [PROCEDURE procedure_name] ]

SELECT is used to retrieve rows selected from one or more tables. select_expression indicates the columns you want to retrieve. SELECT may also be used to retrieve rows computed without reference to any table.

JOIN syntax

MySQL supports the following JOIN syntaxes for use in SELECT statements:

table_reference, table_reference
table_reference [CROSS] JOIN table_reference
table_reference INNER JOIN table_reference
table_reference STRAIGHT_JOIN table_reference
table_reference LEFT [OUTER] JOIN table_reference ON conditional_expr
table_reference LEFT [OUTER] JOIN table_reference USING (column_list)
table_reference NATURAL LEFT [OUTER] JOIN table_reference
{ oj table_reference LEFT OUTER JOIN table_reference ON conditional_expr }

The last LEFT OUTER JOIN syntax shown above exists only for compatibility with ODBC.

INSERT syntax

    INSERT [LOW_PRIORITY | DELAYED] [IGNORE]
        [INTO] tbl_name [(col_name,...)]
        VALUES (expression,...),(...),...
or  INSERT [LOW_PRIORITY | DELAYED] [IGNORE]
        [INTO] tbl_name [(col_name,...)]
        SELECT ...
or  INSERT [LOW_PRIORITY | DELAYED] [IGNORE]
        [INTO] tbl_name
        SET col_name=expression, col_name=expression, ...

INSERT inserts new rows into an existing table. The INSERT ... VALUES form of the statement inserts rows based on explicitly-specified values. The INSERT ... SELECT form inserts rows selected from another table or tables. The INSERT ... VALUES form with multiple value lists is supported in MySQL 3.22.5 or later. The col_name=expression syntax is supported in MySQL 3.22.10 or later.

REPLACE syntax

    REPLACE [LOW_PRIORITY | DELAYED]
        [INTO] tbl_name [(col_name,...)]
        VALUES (expression,...)
or  REPLACE [LOW_PRIORITY | DELAYED]
        [INTO] tbl_name [(col_name,...)]
        SELECT ...
or  REPLACE [LOW_PRIORITY | DELAYED]
        [INTO] tbl_name
        SET col_name=expression, col_name=expression,...

REPLACE works exactly like INSERT, except that if an old record in the table has the same value as a new record on a unique index, the old record is deleted before the new record is inserted.

LOAD DATA INFILE syntax

LOAD DATA [LOW_PRIORITY] [LOCAL] INFILE 'file_name.txt' [REPLACE | IGNORE]
    INTO TABLE tbl_name
    [FIELDS
        [TERMINATED BY '\t']
        [OPTIONALLY] ENCLOSED BY '']
        [ESCAPED BY '\\' ]]
    [LINES 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. If the LOCAL keyword is specified, the file is read from the client host. If LOCAL is not specified, the file must be located on the server. (LOCAL is available in MySQL 3.22.6 or later.)

UPDATE syntax

UPDATE [LOW_PRIORITY] tbl_name SET col_name1=expr1,col_name2=expr2,...
    [WHERE where_definition] [LIMIT #]

UPDATE updates columns in existing table rows with new values. The SET clause indicates which columns to modify and the values they should be given. The WHERE clause, if given, specifies which rows should be updated. Otherwise all rows are updated.

USE syntax

USE db_name

The USE db_name statement tells MySQL to use the db_name database as the default database for subsequent queries. The database remains current until the end of the session, or until another USE statement is issued.

FLUSH syntax (clearing caches)

FLUSH flush_option [,flush_option]

You should use the FLUSH command if you want to clear some of the internal caches MySQL uses. To execute FLUSH, you must have the reload privilege.

flush_option can be any of the following:

HOSTS

Empties the host cache tables. You should flush the host tables if some of your hosts change IP number or if you get the error message Host ... is blocked. When more than max_connect_errors errors occur in a row for a given host while connection to the MySQL server, MySQL assumes something is wrong and blocks the host from further connection requests. Flushing the host tables allows the host to attempt to connect again. You can start mysqld with -O max_connection_errors=999999999 to avoid this error message.

LOGS

Closes and reopens the standard and update log files. If you have specified the update log file without an extension, the extension number of the new update log file will be incremented by one relative to the previous file.

PRIVILEGES

Reloads the privileges from the grant tables in the mysql database.

TABLES

Closes all open tables.

STATUS

Resets most status variables to zero.

You can also access each of the commands shown above with the mysqladmin utility, using the flush-hosts, flush-logs, reload or flush-tables commands.

KILL syntax

KILL thread_id

Each connection to mysqld runs in a separate thread. You can see which threads are running with the SHOW PROCESSLIST command, and kill a thread with the KILL thread_id command.

SHOW syntax (get information about tables, columns, ...)

   SHOW DATABASES [LIKE wild]
or SHOW TABLES [FROM db_name] [LIKE wild]
or SHOW COLUMNS FROM tbl_name [FROM db_name] [LIKE wild]
or SHOW INDEX FROM tbl_name [FROM db_name]
or SHOW STATUS
or SHOW VARIABLES [LIKE wild]
or SHOW [FULL] PROCESSLIST
or SHOW TABLE STATUS [FROM db_name] [LIKE wild]
or SHOW GRANTS FOR user

SHOW provides information about databases, tables, columns or the server. If the LIKE wild part is used, the wild string can be a string that uses the SQL `%' and `_' wildcard characters.

EXPLAIN syntax (get information about a SELECT)

    EXPLAIN tbl_name
or  EXPLAIN SELECT select_options

EXPLAIN tbl_name is a synonym for DESCRIBE tbl_name or SHOW COLUMNS FROM tbl_name.

When you precede a SELECT statement with the keyword EXPLAIN, MySQL explains how it would process the SELECT, providing information about how tables are joined and in which order.

DESCRIBE syntax (get information about columns)

{DESCRIBE | DESC} tbl_name {col_name | wild}

DESCRIBE provides information about a table's columns. col_name may be a column name or a string containing the SQL `%' and `_' wildcard characters.

LOCK TABLES/UNLOCK TABLES syntax

LOCK TABLES tbl_name [AS alias] {READ | [LOW_PRIORITY] WRITE}
            [, tbl_name {READ | [LOW_PRIORITY] WRITE} ...]
...
UNLOCK TABLES

LOCK TABLES locks tables for the current thread. UNLOCK TABLES releases any locks held by the current thread. All tables that are locked by the current thread are automatically unlocked when the thread issues another LOCK TABLES, or when the connection to the server is closed.

SET OPTION syntax

SET [OPTION] SQL_VALUE_OPTION= value, ...

SET OPTION sets various options that affect the operation of the server or your client. Any option you set remains in effect until the current session ends, or until you set the option to a different value.

GRANT and REMOVE syntax

GRANT priv_type [(column_list)] [, priv_type [(column_list)] ...]
    ON {tbl_name | * | *.* | db_name.*}
    TO user_name [IDENTIFIED BY 'password']
        [, user_name [IDENTIFIED BY 'password'] ...]
    [WITH GRANT OPTION]

REVOKE priv_type [(column_list)] [, priv_type [(column_list)] ...]
    ON {tbl_name | * | *.* | db_name.*}
    FROM user_name [, user_name ...]

GRANT is implemented in MySQL 3.22.11 or later. For earlier MySQL versions, the GRANT statement does nothing.

CREATE INDEX syntax

CREATE [UNIQUE] INDEX index_name ON tbl_name (col_name[(length)],... )

The CREATE INDEX statement doesn't do anything in MySQL prior to version 3.22. In 3.22 or later, CREATE INDEX is mapped to an ALTER TABLE statement to create indexes.

Normally, you create all indexes on a table at the time the table itself is created with CREATE TABLE.

DROP INDEX syntax

DROP INDEX index_name ON tbl_name

DROP INDEX drops the index named index_name from the table tbl_name. DROP INDEX doesn't do anything in MySQL prior to version 3.22. In 3.22 or later, DROP INDEX is mapped to an ALTER TABLE statement to drop the index.

Comment syntax

The MySQL server supports the # to end of line, -- to end of line and /* in-line or multiple-line */ comment styles:

mysql> select 1+1;     # This comment continues to the end of line
mysql> select 1+1;     -- This comment continues to the end of line 
mysql> select 1 /* this is an in-line comment */ + 1;
mysql> select 1+
/*
this is a
multiple-line comment
*/
1;

Note that the -- comment style requires you to have at least one space after the --!

CREATE FUNCTION/DROP FUNCTION syntax

CREATE [AGGREGATE] FUNCTION function_name RETURNS {STRING|REAL|INTEGER}
       SONAME shared_library_name

DROP FUNCTION function_name

A user-definable function (UDF) is a way to extend MySQL with a new function that works like native (built in) MySQL functions such as ABS() and CONCAT().

AGGREGATE is a new option for MySQL 3.23. An AGGREGATE function works exactly like a native MySQL GROUP function like SUM or COUNT().

CREATE FUNCTION saves the function's name, type and shared library name in the mysql.func system table. You must have the insert and delete privileges for the mysql database to create and drop functions.

All active functions are reloaded each time the server starts, unless you start mysqld with the --skip-grant-tables option. In this case, UDF initialization is skipped and UDFs are unavailable. (An active function is one that has been loaded with CREATE FUNCTION and not removed with DROP FUNCTION.)

For instructions on writing user-definable functions, see section 14 Adding new functions to MySQL. For the UDF mechanism to work, functions must be written in C or C++, your operating system must support dynamic loading and you must have compiled mysqld dynamically (not static).

Reserved words

action

add

aggregate

all

alter

after

and

as

asc

avg

avg_row_length

auto_increment

between

bigint

bit

binary

blob

bool

both

by

cascade

case

char

character

change

check

checksum

column

columns

comment

constraint

create

cross

current_date

current_time

current_timestamp

data

database

databases

date

datetime

day

day_hour

day_minute

day_second

dayofmonth

dayofweek

dayofyear

dec

decimal

default

delayed

delay_key_write

delete

desc

describe

distinct

distinctrow

double

drop

end

else

escape

escaped

enclosed

enum

explain

exists

fields

file

first

float

float4

float8

flush

foreign

from

for

full

function

global

grant

grants

group

having

heap

high_priority

hour

hour_minute

hour_second

hosts

identified

ignore

in

index

infile

inner

insert

insert_id

int

integer

interval

int1

int2

int3

int4

int8

into

if

is

isam

join

key

keys

kill

last_insert_id

leading

left

length

like

lines

limit

load

local

lock

logs

long

longblob

longtext

low_priority

max

max_rows

match

mediumblob

mediumtext

mediumint

middleint

min_rows

minute

minute_second

modify

month

monthname

myisam

natural

numeric

no

not

null

on

optimize

option

optionally

or

order

outer

outfile

pack_keys

partial

password

precision

primary

procedure

process

processlist

privileges

read

real

references

reload

regexp

rename

replace

restrict

returns

revoke

rlike

row

rows

second

select

set

show

shutdown

smallint

soname

sql_big_tables

sql_big_selects

sql_low_priority_updates

sql_log_off

sql_log_update

sql_select_limit

sql_small_result

sql_big_result

sql_warnings

straight_join

starting

status

string

table

tables

temporary

terminated

text

then

time

timestamp

tinyblob

tinytext

tinyint

trailing

to

type

use

using

unique

unlock

unsigned

update

usage

values

varchar

variables

varying

varbinary

with

write

when

where

year

year_month

zerofill