MySQL Tutorial
- Keys, Constraints and Indexes
- Privileges and Passwords
- Database Administration
- Programming
- Comparison Operators
- Query Types
- Joins
- Aliases
- Clauses
- SQL Functions
- Conditions
- Tables and Views
- Functions
- ASCII Function
- CHAR_LENGTH Function
- CHARACTER_LENGTH Function
- CONCAT Function
- CONCAT_WS Function
- FIELD Function
- FIND_IN_SET Function
- FORMAT Function
- INSERT Function
- INSTR Function
- LCASE Function
- LEFT Function
- LENGTH Function
- LOCATE Function
- LOWER Function
- LPAD Function
- LTRIM Function
- MID Function
- POSITION Function
- REPEAT Function
- REPLACE Function
- REVERSE Function
- RIGHT Function
- RPAD Function
- RTRIM Function
- SPACE Function
- STRCMP Function
- SUBSTR Function
- SUBSTRING Function
- SUBSTRING_INDEX Function
- TRIM Function
- UCASE Function
- UPPER Function
- ABS Function
- ACOS Function
- ASIN Function
- ATAN Function
- ATAN2 Function
- AVG Function
- CEIL Function
- CEILING Function
- COS Function
- COT Function
- COUNT Function
- DEGREES Function
- DIV Function
- EXP Function
- FLOOR Function
- GREATEST Function
- LEAST Function
- LN Function
- LOG Function
- LOG10 Function
- LOG2 Function
- MAX Function
- MIN Function
- MOD Function
- PI Function
- POW Function
- POWER Function
- RADIANS Function
- RAND Function
- ROUND Function
- SIGN Function
- SIN Function
- SQRT Function
- SUM Function
- TAN Function
- TRUNCATE Function
- ADDDATE Function
- ADDTIME Function
- CURDATE Function
- CURRENT_DATE Function
- CURRENT_TIME Function
- CURRENT_TIMESTAMP Function
- CURTIME Function
- DATE Function
- DATE_ADD Function
- DATE_FORMAT Function
- DATE_SUB Function
- DATEDIFF Function
- DAY Function
- DAYNAME Function
- DAYOFMONTH Function
- DAYOFWEEK Function
- DAYOFYEAR Function
- EXTRACT Function
- FROM_DAYS Function
- HOUR Function
- LAST_DAY Function
- LOCALTIME Function
- LOCALTIMESTAMP Function
- MAKEDATE Function
- MAKETIME Function
- MICROSECOND Function
- MINUTE Function
- MONTH Function
- MONTHNAME Function
- NOW Function
- PERIOD_ADD Function
- PERIOD_DIFF Function
- QUARTER Function
- SEC_TO_TIME Function
- SECOND Function
- STR_TO_DATE Function
- SUBDATE Function
- SUBTIME Function
- SYSDATE Function
- TIME Function
- TIME_FORMAT Function
- TIME_TO_SEC Function
- TIMEDIFF Function
- TIMESTAMP Function
- TO_DAYS Function
- WEEK Function
- WEEKDAY Function
- WEEKOFYEAR Function
- YEAR Function
- YEARWEEK Function
- BIN Function
- BINARY Function
- CASE Function
- CAST Function
- COALESCE Function
- CONNECTION_ID Function
- CONV Function
- CONVERT Function
- CURRENT_USER Function
- DATABASE Function
- IF Function
- IFNULL Function
- ISNULL Function
- LAST_INSERT_ID Function
- NULLIF Function
- SESSION_USER Function
- SYSTEM_USER Function
- USER Function
- VERSION Function
- ENCRYPT Function
- MD5 Function
- OLD_PASSWORD Function
- PASSWORD Function
This MySQL tutorial explains how to create and drop a primary key in MySQL with syntax and examples.
In MySQL a primary key is a single field or combination of fields that uniquely defines a record. None of the fields that are part of the primary key can contain a NULL value. A table can have only one primary key.
- In MySQL a primary key is created using either a CREATE TABLE statement or an ALTER TABLE statement.
- You use the ALTER TABLE statement in MySQL to drop disable or enable a primary key.
You can create a primary key in MySQL with the CREATE TABLE statement.
The syntax to create a primary key using the CREATE TABLE statement in MySQL is:
CREATE TABLE table_name
(
column1 column_definition
column2 column_definition
...
CONSTRAINT constraint_name
PRIMARY KEY USING BTREE | HASH (column1 column2 ... column_n)
);
table_name The name of the table that you wish to create. column1 column2 The columns that you wish to create in the table. See the MySQL CREATE TABLE statement for more detailed CREATE TABLE syntax as this is an over-simplification to demonstrate how to create a primary Key. constraint_name The name of the primary key. column1 column2 ... column_n The columns that make up the primary key.
Let's look at an example of how to create a primary key using the CREATE TABLE statement in MySQL.
CREATE TABLE contacts
( contact_id INT(11) NOT NULL AUTO_INCREMENT
last_name VARCHAR(30) NOT NULL
first_name VARCHAR(25)
birthday DATE
CONSTRAINT contacts_pk PRIMARY KEY (contact_id)
);
In this example we've created a primary key on the contacts table called contacts_pk. It consists of only one column - the contact_id column.
We could also create a primary key with more than one field as in the example below:
CREATE TABLE contacts
( last_name VARCHAR(30) NOT NULL
first_name VARCHAR(25) NOT NULL
birthday DATE
CONSTRAINT contacts_pk PRIMARY KEY (last_name first_name)
);
This example creates a primary key called contacts_pk that is made up of a combination of the last_name and first_name columns. So each combination of last_name and first_name must be unique in the contacts table.
You can create a primary key in MySQL with the ALTER TABLE statement.
The syntax to create a primary key using the ALTER TABLE statement in MySQL is:
ALTER TABLE table_name
ADD CONSTRAINT constraint_name
PRIMARY KEY USING BTREE | HASH (column1 column2 ... column_n)
table_name The name of the table to modify. constraint_name The name of the primary key. column1 column2 ... column_n The columns that make up the primary key.
Let's look at an example of how to create a primary key using the ALTER TABLE statement in MySQL.
ALTER TABLE contacts
ADD CONSTRAINT contacts_pk
PRIMARY KEY (contact_id);
In this example we've created a primary key on the existing contacts table called contacts_pk. It consists of the contact_id column.
We could also create a primary key with more than one field as in the example below:
ALTER TABLE contacts
ADD CONSTRAINT contacts_pk
PRIMARY KEY (last_name first_name);
This example we've created a primary key called contacts_pk that is made up of a combination of the last_name and first_name columns.
You can drop a primary key in MySQL using the ALTER TABLE statement.
The syntax to drop a primary key in MySQL is:
ALTER TABLE table_name
DROP PRIMARY KEY;
table_name The name of the table to modify.
Let's look at an example of how to drop a primary key using the ALTER TABLE statement in MySQL.
ALTER TABLE contacts
DROP PRIMARY KEY;
In this example we've dropped the primary key on the contacts table. We do not need to specify the name of the primary key as there can only be one on a table.
This MySQL tutorial explains how to create add and drop unique constraints in MySQL with syntax and examples.
A unique constraint is a single field or combination of fields that uniquely defines a record. Some of the fields can contain null values as long as the combination of values is unique.
Primary Key | Unique Constraint |
---|---|
None of the fields that are part of the primary key can contain a null value. | Some of the fields that are part of the unique constraint can contain null values as long as the combination of values is unique. |
The syntax for creating a unique constraint using a CREATE TABLE statement in MySQL is:
CREATE TABLE table_name
(
column1 datatype NULL | NOT NULL
column2 datatype NULL | NOT NULL
...
CONSTRAINT constraint_name UNIQUE (uc_col1 uc_col2 ... uc_col_n)
);
table_name The name of the table that you wish to create. column1 column2 The columns that you wish to create in the table. constraint_name The name of the unique constraint. uc_col1 uc_col2 ... uc_col_n The columns that make up the unique constraint.
Let's look at an example of how to create a unique constraint in MySQL using the CREATE TABLE statement.
CREATE TABLE contacts
( contact_id INT(11) PRIMARY KEY AUTO_INCREMENT
reference_number INT(11) NOT NULL
last_name VARCHAR(30) NOT NULL
first_name VARCHAR(25)
birthday DATE
CONSTRAINT reference_unique UNIQUE (reference_number)
);
In this example we've created a unique constraint on the contacts table called reference_unique. It consists of only one field - the reference_number field.
We could also create a unique constraint with more than one field as in the example below:
CREATE TABLE contacts
( contact_id INT(11) PRIMARY KEY AUTO_INCREMENT
reference_number INT(11) NOT NULL
last_name VARCHAR(30) NOT NULL
first_name VARCHAR(25)
birthday DATE
CONSTRAINT contact_name_unique UNIQUE (last_name first_name)
);
The syntax for creating a unique constraint using an ALTER TABLE statement in MySQL is:
ALTER TABLE table_name
ADD CONSTRAINT constraint_name UNIQUE (column1 column2 ... column_n);
table_name The name of the table to modify. This is the table that you wish to add a unique constraint to. constraint_name The name of the unique constraint. column1 column2 ... column_n The columns that make up the unique constraint.
Let's look at an example of how to add a unique constraint to an existing table in MySQL using the ALTER TABLE statement.
ALTER TABLE contacts
ADD CONSTRAINT reference_unique UNIQUE (reference_number);
In this example we've created a unique constraint on the existing contacts table called reference_unique. It consists of the field called reference_number.
We could also create a unique constraint with more than one field as in the example below:
ALTER TABLE contacts
ADD CONSTRAINT contact_name_unique UNIQUE (last_name first_name);
The syntax for dropping a unique constraint in MySQL is:
ALTER TABLE table_name
DROP INDEX constraint_name;
table_name The name of the table to modify. This is the table that you wish to remove the unique constraint from. constraint_name The name of the unique constraint to remove.
Let's look at an example of how to remove a unique constraint from a table in MySQL.
ALTER TABLE contacts
DROP INDEX reference_unique;
In this example we're dropping a unique constraint on the contacts table called reference_unique.
This MySQL tutorial explains how to create drop and rename indexes in MySQL with syntax and examples.
An index is a performance-tuning method of allowing faster retrieval of records. An index creates an entry for each value that appears in the indexed columns.
There are 2 ways to create an index. You can either create an index when you first create a table using the CREATE TABLE statement or you can use the CREATE INDEX statement after the table has been created.
The syntax to create an index using the CREATE TABLE statement in MySQL is:
CREATE TABLE table_name
(
column1 datatype NULL | NOT NULL
column2 datatype NULL | NOT NULL
...
column_n datatype NULL | NOT NULL
INDEX index_name USING BTREE | HASH
(index_col1 (length) ASC | DESC
index_col2 (length) ASC | DESC
...
index_col_n (length) ASC | DESC )
);
OR
The syntax to create an index using the CREATE INDEX statement in MySQL is:
CREATE UNIQUE | FULLTEXT | SPATIAL INDEX index_name
USING BTREE | HASH
ON table_name
(index_col1 (length) ASC | DESC
index_col2 (length) ASC | DESC
...
index_col_n (length) ASC | DESC );
UNIQUE Optional. The UNIQUE modifier indicates that the combination of values in the indexed columns must be unique. FULLTEXT Optional. The FULLTEXT modifier indexes the entire column and does not allow prefixing. InnoDB and MyISAM tables support this option. SPATIAL Optional. The SPATIAL modifier indexes the entire column and does not allow indexed columns to contain NULL values. InnoDB (starting in MySQL 5.7) and MyISAM tables support this option. index_name The name to assign to the index. table_name The name of the table in which to create the index. index_col1 index_col2 ... index_col_n The columns to use in the index. length Optional. If specified only a prefix of the column is indexed not the entire column. For non-binary string columns this value is the given number of characters of the column to index. For binary string columns this value is the given number of bytes of the column to index. ASC Optional. The index is sorted in ascending order for that column. DESC Optional. The index is sorted in descending order for that column.
Let's look at an example of how to create an index in MySQL using the CREATE TABLE statement. This statement would both create the table as well as the index at the same time.
For example:
CREATE TABLE contacts
( contact_id INT(11) NOT NULL AUTO_INCREMENT
last_name VARCHAR(30) NOT NULL
first_name VARCHAR(25)
birthday DATE
CONSTRAINT contacts_pk PRIMARY KEY (contact_id)
INDEX contacts_idx (last_name first_name)
);
In this example we've created the contacts table as well as an index called contacts_idx which consists of the last_name and first_name columns.
Next we will show you how to create the table first and then create the index using the CREATE INDEX statement.
For example:
CREATE TABLE contacts
( contact_id INT(11) NOT NULL AUTO_INCREMENT
last_name VARCHAR(30) NOT NULL
first_name VARCHAR(25)
birthday DATE
CONSTRAINT contacts_pk PRIMARY KEY (contact_id)
);
CREATE INDEX contacts_idx
ON contacts (last_name first_name);
In this example the CREATE TABLE statement would create the contacts table. The CREATE INDEX statement would create an index called contacts_idx that consists of the last_name and the first_name fields.
To create a unique index on a table you need to specify the UNIQUE keyword when creating the index. Again this can be done with either a CREATE TABLE statement or a CREATE INDEX statement.
For example:
CREATE TABLE contacts
( contact_id INT(11) NOT NULL AUTO_INCREMENT
last_name VARCHAR(30) NOT NULL
first_name VARCHAR(25)
birthday DATE
CONSTRAINT contacts_pk PRIMARY KEY (contact_id)
UNIQUE INDEX contacts_idx (last_name first_name)
);
OR
CREATE TABLE contacts
( contact_id INT(11) NOT NULL AUTO_INCREMENT
last_name VARCHAR(30) NOT NULL
first_name VARCHAR(25)
birthday DATE
CONSTRAINT contacts_pk PRIMARY KEY (contact_id)
);
CREATE UNIQUE INDEX contacts_idx
ON contacts (last_name first_name);
Both of these examples would create a unique index on the last_name and first_name fields so that the combination of these fields must always contain a unique value with no duplicates. This is a great way to enforce integrity within your database if you require unique values in columns that are not part of your primary key.
You can drop an index in MySQL using the DROP INDEX statement.
The syntax to drop an index using the DROP INDEX statement in MySQL is:
DROP INDEX index_name
ON table_name;
index_name The name of the index to drop. table_name The name of the table where the index was created.
Let's look at an example of how to drop an index in MySQL.
For example:
DROP INDEX contacts_idx
ON contacts;
In this example we've dropped an index called contacts_idx from the contacts table.
You can rename an index in MySQL. Depending on your version of MySQL there are two different syntaxes.
The syntax to rename an index using the ALTER TABLE statement in MySQL 5.6 and later is:
ALTER TABLE table_name
DROP INDEX index_name
ADD INDEX new_index_name USING BTREE | HASH
(index_col1 (length) ASC | DESC
index_col2 (length) ASC | DESC
...
index_col_n (length) ASC | DESC );
OR
The syntax to rename an index in MySQL 5.7 or newer is:
ALTER TABLE table_name
RENAME INDEX index_name TO new_index_name;
table_name The name of the table where the index was created. index_name The name of the index that you wish to rename. new_index_name The new name for the index.
Let's look at an example of how to rename an index in MySQL. In older versions of MySQL you need to use the ALTER TABLE statement to first drop the old index and then recreate the new index.
For example (MySQL 5.6 and older):
ALTER TABLE contacts
DROP INDEX contacts_idx
ADD INDEX contacts_new_index (last_name first_name);
In this example we've renamed the index called contacts_idx to contacts_new_index. This was done by dropping the old index and then adding the new index.
Starting in MySQL 5.7 you can use the ALTER TABLE statement with the RENAME INDEX clause to rename the index.
For example (MySQL 5.7 and newer):
ALTER TABLE contacts
RENAME INDEX contacts_idx TO contacts_new_index;
This would also rename the index from contacts_idx to contacts_new_index. If you are unsure which version of MySQL you are running it is safest to use the first syntax to rename an index.
This MySQL tutorial explains how to grant and revoke privileges in MySQL with syntax and examples.
You can GRANT and REVOKE privileges on various database objects in MySQL. You can then view the privileges assigned to a user using the SHOW GRANTS command. We'll look at how to grant and revoke privileges on tables function and procedures in MySQL.
You can grant users various privileges to tables. These permissions can be any combination of SELECT INSERT UPDATE DELETE INDEX CREATE ALTER DROP GRANT OPTION or ALL.
The syntax for granting privileges on a table in MySQL is:
GRANT privileges ON object TO user;
privileges It can be any of the following values:
Privilege | Description |
---|---|
SELECT | Ability to perform SELECT statements on the table. |
INSERT | Ability to perform INSERT statements on the table. |
UPDATE | Ability to perform UPDATE statements on the table. |
DELETE | Ability to perform DELETE statements on the table. |
INDEX | Ability to create an index on an existing table. |
CREATE | Ability to perform CREATE TABLE statements. |
ALTER | Ability to perform ALTER TABLE statements to change the table definition. |
DROP | Ability to perform DROP TABLE statements. |
GRANT OPTION | Allows you to grant the privileges that you possess to other users. |
ALL | Grants all permissions except GRANT OPTION. |
object The name of the database object that you are granting permissions for. In the case of granting privileges on a table this would be the table name. user The name of the user that will be granted these privileges.
Let's look at some examples of how to grant privileges on tables in MySQL.
For example if you wanted to grant SELECT INSERT UPDATE and DELETE privileges on a table called contacts to a user name smithj you would run the following GRANT statement:
GRANT SELECT INSERT UPDATE DELETE ON contacts TO 'smithj'@'localhost';
You can also use the ALL keyword to indicate that you wish to grant all permissions except GRANT OPTION to a user named smithj. For example:
GRANT ALL ON contacts TO 'smithj'@'localhost';
If you wanted to grant only SELECT access on the contacts table to all users you could grant the privileges to *. For example:
GRANT SELECT ON contacts TO '\*'@'localhost';
Once you have granted privileges you may need to revoke some or all of these privileges. To do this you can run a revoke command. You can revoke any combination of SELECT INSERT UPDATE DELETE REFERENCES ALTER or ALL.
The syntax for revoking privileges on a table in MySQL is:
REVOKE privileges ON object FROM user;
privileges It can be any of the following values:
Privilege | Description |
---|---|
SELECT | Ability to perform SELECT statements on the table. |
INSERT | Ability to perform INSERT statements on the table. |
UPDATE | Ability to perform UPDATE statements on the table. |
DELETE | Ability to perform DELETE statements on the table. |
INDEX | Ability to create an index on an existing table. |
CREATE | Ability to perform CREATE TABLE statements. |
ALTER | Ability to perform ALTER TABLE statements to change the table definition. |
DROP | Ability to perform DROP TABLE statements. |
GRANT OPTION | Allows you to grant the privileges that you possess to other users. |
ALL | Grants all permissions except GRANT OPTION. |
object The name of the database object that you are revoking privileges for. In the case of revoking privileges on a table this would be the table name. user The name of the user that will have these privileges revoked.
Let's look at some examples of how to revoke privileges on tables in MySQL.
For example if you wanted to revoke DELETE and UPDATE privileges on a table called contacts from a user named smithj you would run the following REVOKE statement:
REVOKE DELETE UPDATE ON contacts FROM 'smithj'@'localhost';
If you wanted to revoke all permissions (except GRANT OPTION) on a table for a user named smithj you could use the ALL keyword as follows:
REVOKE ALL ON contacts FROM 'smithj'@'localhost';
If you had granted SELECT privileges to * (ie: all users) on the contacts table and you wanted to revoke these privileges you could run the following REVOKE statement:
REVOKE SELECT ON contacts FROM '\*'@'localhost';
When dealing with functions and procedures you can grant users the ability to EXECUTE these functions and procedures in MySQL.
The syntax for granting EXECUTE privileges on a function/procedure in MySQL is:
GRANT EXECUTE ON PROCEDURE | FUNCTION object TO user;
EXECUTE The ability to execute the function or procedure. PROCEDURE It is used when the privilege is being granted on a procedure in MySQL. FUNCTION It is used when the privilege is being granted on a function in MySQL. object The name of the database object that you are granting privileges for. In the case of granting EXECUTE privileges on a function or procedure this would be the function name or the procedure name. user The name of the user that will be granted the EXECUTE privileges.
Let's look at some examples of how to grant EXECUTE privileges on a function in MySQL.
For example if you had a function called CalcIncome and you wanted to grant EXECUTE access to the user named smithj you would run the following GRANT statement:
GRANT EXECUTE ON FUNCTION CalcIncome TO 'smithj'@'localhost';
If you wanted to grant ALL users the ability to EXECUTE this function you would run the following GRANT statement:
GRANT EXECUTE ON FUNCTION CalcIncome TO '\*'@'localhost';
Let's look at some examples of how to grant EXECUTE privileges on a procedure in MySQL.
For example if you had a procedure called MyFirstProc and you wanted to grant EXECUTE access to the user named smithj you would run the following GRANT statement:
GRANT EXECUTE ON PROCEDURE MyFirstProc TO 'smithj'@'localhost';
If you wanted to grant ALL users the ability to EXECUTE this procedure you would run the following GRANT statement:
GRANT EXECUTE ON PROCEDURE MyFirstProc TO '\*'@'localhost';
Once you have granted EXECUTE privileges on a function or procedure you may need to REVOKE these privileges from a user in MySQL. To do this you can execute a REVOKE command.
The syntax for the revoking privileges on a function or procedure in MySQL is:
REVOKE EXECUTE ON PROCEDURE | FUNCTION object FROM user;
EXECUTE The ability to execute the function or procedure is being revoked. PROCEDURE It is used when the privilege is being revoked on a procedure in MySQL. FUNCTION It is used when the privilege is being revoked on a function in MySQL. object The name of the database object that you are revoking privileges for. In the case of revoking EXECUTE privileges on a function or procedure this would be the function name or the procedure name. user The name of the user that will be revoked the EXECUTE privileges.
Let's look at some examples of how to revoke EXECUTE privileges on a function in MySQL.
If you wanted to revoke EXECUTE privileges on a function called CalcIncome from a user named smithj you would run the following REVOKE statement:
REVOKE EXECUTE ON FUNCTION CalcIncome FROM 'smithj'@'localhost';
If you had granted EXECUTE privileges to * (all users) on the function called CalcIncome and you wanted to revoke these EXECUTE privileges you could run the following REVOKE statement:
REVOKE EXECUTE ON FUNCTION CalcIncome FROM '\*'@'localhost';
Let's look at some examples of how to revoke EXECUTE privileges on a procedure in MySQL.
If you wanted to revoke EXECUTE privileges on a procedure called MyFirstProc from a user named smithj you would run the following REVOKE statement:
REVOKE EXECUTE ON PROCEDURE MyFirstProc FROM 'smithj'@'localhost';
If you had granted EXECUTE privileges to * (all users) on the procedure called CalcIncome and you wanted to revoke these EXECUTE privileges you could run the following REVOKE statement:
REVOKE EXECUTE ON PROCEDURE MyFirstProc FROM '\*'@'localhost';
This MySQL tutorial explains how to change a user's password in MySQL with syntax and examples.
The SET PASSWORD statement is used to change a user's password in the MySQL database.
The syntax for changing a password using the SET PASSWORD statement in MySQL is:
SET PASSWORD FOR *user_name* =
{
PASSWORD('*plaintext_password1*')
| OLD_PASSWORD('*plaintext_password2*')
| '*encrypted_password*'
};
FOR user_name Optional. It is the user whose password you wish to change. If user_name is not specified the password will be changed for the current user (see CURRENT_USER function). PASSWORD('plaintext_password1') First method to set password. Uses the PASSWORD function to take the plaintext text string found in plaintext_password1 and generate a hashed password (using hashing techniques MySQL 4.1+). OLD_PASSWORD('plaintext_password2') Second method to set password. Uses the OLD_PASSWORD function to take the plaintext text string found in plaintext_password2 and generate a hashed password (using hashing techniques prior to MySQL 4.1). encrypted_password Third method to set password. A password that is already encrypted using the authentication method for the user account that does not need to be modified any further.
- The FOR user_name parameter must be specified in the format of user_name@host_name such as 'jane'@'localhost'.
Let's look at an example that shows how to use the SET PASSWORD statement in MySQL.
For example if you wanted to update the user named smithj with the password autumn you would run the following SET PASSWORD statement in MySQL:
SET PASSWORD FOR 'smithj'@'localhost' = PASSWORD('autumn');
If you wanted to reset the password using the hashing techniques prior to MySQL 4.1 you would modify the SET PASSWORD statement as follows:
SET PASSWORD FOR 'smithj'@'localhost' = OLD_PASSWORD('autumn');
If the new password was already encrypted you could use the SET PASSWORD statement as follows:
SET PASSWORD FOR 'smithj'@'localhost' = '\*0886644237EED5C45BE221093802B5AB0C06D2D0';
This MySQL tutorial explains how to create and drop functions in MySQL with syntax and examples.
In MySQL a function is a stored program that you can pass parameters into and then return a value.
Just as you can create functions in other languages you can create your own functions in MySQL. Let's take a closer look.
The syntax to create a function in MySQL is:
CREATE FUNCTION function_name (parameter datatype parameter datatype )
RETURNS return_datatype
BEGIN
declaration_section
executable_section
END;
function_name The name to assign to this function in MySQL. parameter One or more parameters passed into the function. When creating a function all parameters are considered to be IN parameters (not OUT or INOUT parameters) where the parameters can be referenced by the function but can not be overwritten by the function. return_datatype The data type of the function's return value. declaration_section The place in the function where you declare local variables. executable_section The place in the function where you enter the code for the function.
Let's look at an example that shows how to create a function in MySQL:
DELIMITER //
CREATE FUNCTION CalcIncome ( starting_value INT )
RETURNS INT
BEGIN
DECLARE income INT;
SET income = 0;
label1: WHILE income <= 3000 DO
SET income = income + starting_value;
END WHILE label1;
RETURN income;
END; //
DELIMITER ;
You could then reference your new function as follows:
SELECT CalcIncome (1000);
Once you have created your function in MySQL you might find that you need to remove it from the database.
The syntax to a drop a function in MySQL is:
DROP FUNCTION IF EXISTS *function_name*;
function_name The name of the function that you wish to drop.
Let's look at an example of how to drop a function in MySQL.
For example:
DROP FUNCTION CalcIncome;
This example would drop the function called CalcIncome.
This MySQL tutorial explains how to create and drop procedures in MySQL with syntax and examples.
In MySQL a procedure is a stored program that you can pass parameters into. It does not return a value like a function does.
Just as you can create procedures in other languages you can create your own procedures in MySQL. Let's take a closer look.
The syntax to create a procedure in MySQL is:
CREATE PROCEDURE procedure_name (parameter datatype parameter datatype )
BEGIN
declaration_section
executable_section
END;
procedure_name The name to assign to this procedure in MySQL. parameter Optional. One or more parameters passed into the procedure. When creating a procedure there are three types of parameters that can be declared:
- IN - The parameter can be referenced by the procedure. The value of the parameter can not be overwritten by the procedure.
- OUT - The parameter can not be referenced by the procedure but the value of the parameter can be overwritten by the procedure.
- IN OUT - The parameter can be referenced by the procedure and the value of the parameter can be overwritten by the procedure.
declaration_section The place in the procedure where you declare local variables. executable_section The place in the procedure where you enter the code for the procedure.
Let's look at an example that shows how to create a procedure in MySQL:
DELIMITER //
CREATE procedure CalcIncome ( OUT ending_value INT )
BEGIN
DECLARE income INT;
SET income = 50;
label1: WHILE income <= 3000 DO
SET income = income \* 2;
END WHILE label1;
SET ending_value = income;
END; //
DELIMITER ;
You could then reference your new procedure as follows:
CALL CalcIncome (@variable_name);
SELECT @variable_name;
Once you have created your procedure in MySQL you might find that you need to remove it from the database.
The syntax to a drop a procedure in MySQL is:
DROP procedure IF EXISTS *procedure_name*;
procedure_name The name of the procedure that you wish to drop.
Let's look at an example of how to drop a procedure in MySQL.
For example:
DROP procedure CalcIncome;
This example would drop the procedure called CalcIncome.
This MySQL tutorial explains how to use literals (string number date time and boolean literals) in MySQL with examples.
In MySQL a literal is the same as a constant. We'll cover several types of literals - string literals number literals date and time literals and boolean literals.
String literals are always surrounded by either single quotes (') or double quotes ("). For example:
Example | Explanation |
---|---|
'techonthenet.com' | String literal with single quotes |
"techonthenet.com" | String literal with double quotes |
'Tech on the Net' | String literal with single quotes |
"Tech on the Net" | String literal with double quotes |
Number literals can be either positive or negative numbers that are exact or floating point values. If you do not specify a sign then a positive number is assumed. Here are some examples of valid number literals:
Example | Explanation |
---|---|
25 | Integer literal with no sign (positive sign is assumed) |
+25 | Integer literal with positive sign |
-25 | Integer literal with negative sign |
25e-04 | Floating point literal |
25.607 | Decimal literal |
Date and time literals can be expressed as either strings or numbers. Here are some examples of valid date and time literals:
Example | Explanation |
---|---|
'2014-04-13' | Date literal formatted as 'YYYY-MM-DD' |
'20140413' | Date literal formatted as 'YYYYMMDD' |
20140413 | Date literal formatted as YYYYMMDD |
'14-04-13' | Date literal formatted as 'YY-MM-DD' |
'140413' | Date literal formatted as 'YYMMDD' |
140413 | Date literal formatted as YYMMDD |
'2014-04-13 11:49:36' | Datetime literal formatted as 'YYYY-MM-DD HH:MM:SS' |
'20140413114936' | Datetime literal formatted as 'YYYYMMDDHHMMSS' |
20140413114936 | Datetime literal formatted as YYYYMMDDHHMMSS |
'14-04-13 11:49:36' | Datetime literal formatted as 'YY-MM-DD HH:MM:SS' |
'140413114936' | Datetime literal formatted as 'YYMMDDHHMMSS' |
140413114936 | Datetime literal formatted as YYMMDDHHMMSS |
'0 11:49:36' | Time literal formatted as 'D HH:MM:SS' where D can be a day value between 0 and 34 |
'11:49:36' | Time literal formatted as 'HH:MM:SS' |
'11:49' | Time literal formatted as 'HH:MM' |
'0 11:49' | Time literal formatted as 'D HH:MM' where D can be a day value between 0 and 34 |
'0 11' | Time literal formatted as 'D HH' where D can be a day value between 0 and 34 |
'36' | Time literal formatted as 'SS' |
114936 | Time literal formatted as HHMMSS |
4936 | Time literal formatted as MMSS |
36 | Time literal formatted as SS |
Boolean literals are values that evaluate to either 1 or 0. Here are some examples of valid boolean literals:
Example | Explanation |
---|---|
1 | Evaluates to 1 |
TRUE | Evaluates to 1 |
true | Evaluates to 1 |
0 | Evaluates to 0 |
FALSE | Evaluates to 0 |
false | Evaluates to 0 |
This MySQL tutorial explains how to declare variables in MySQL with syntax and examples.
In MySQL a variable allows a programmer to store data temporarily during the execution of code.
The syntax to declare a variable in MySQL is:
DECLARE variable_name datatype DEFAULT initial_value
variable_name The name to assign to the variable. datatype The datatype to assign to the variable. DEFAULT initial_value Optional. It is the value initially assigned to the variable when it is declared. If an initial_value is not specified the variable is assigned a value of NULL.
Below is an example of how to declare a variable in MySQL called vSite.
DECLARE vSite VARCHAR(40);
This example would declare a variable called vSite as a VARCHAR(40) data type.
You can then later set or change the value of the vSite variable as follows:
SET vSite = 'TechOnTheNet.com';
This SET statement would set the vSite variable to a value of 'TechOnTheNet.com'.
Below is an example of how to declare a variable in MySQL and give it an initial value. This is different from a constant in that the variable's value can be changed later.
DECLARE vSite VARCHAR(40) DEFAULT 'TechOnTheNet.com';
This would declare a variable called vSite as a VARCHAR(40) data type and assign an initial value of 'TechOnTheNet.com'.
You could later change the value of the vSite variable as follows:
SET vSite = 'CheckYourMath.com';
This SET statement would change the vSite variable from a value of 'TechOnTheNet.com' to a value of 'CheckYourMath.com'.
This MySQL tutorial explains how to create sequences using the AUTO_INCREMENT attribute in MySQL with syntax and examples.
In MySQL you can create a column that contains a sequence of numbers (1 2 3 and so on) by using the AUTO_INCREMENT attribute. The AUTO_INCREMENT attribute is used when you need to create a unique number to act as a primary key in a table.
The syntax to create a sequence (or use the AUTO_INCREMENT attribute) in MySQL is:
CREATE TABLE table_name
(
column1 datatype NOT NULL AUTO_INCREMENT
column2 datatype NULL | NOT NULL
...
);
AUTO_INCREMENT The attribute to use when you want MySQL to assign a sequence of numbers automatically to a field (in essence creating an autonumber field). NULL or NOT NULL Each column should be defined as NULL or NOT NULL. If this parameter is omitted the database assumes NULL as the default.
- You can use the LAST_INSERT_ID function to find last value assigned by the AUTO_INCREMENT field.
Let's look at an example of how to use a sequence or the AUTO_INCREMENT attribute in MySQL.
For example:
CREATE TABLE contacts
( contact_id INT(11) NOT NULL AUTO_INCREMENT
last_name VARCHAR(30) NOT NULL
first_name VARCHAR(25)
birthday DATE
CONSTRAINT contacts_pk PRIMARY KEY (contact_id)
);
This MySQL AUTO_INCREMENT example creates a table called contacts which has 4 columns and one primary key:
- The first column is called contact_id which is created as an INT datatype (maximum 11 digits in length) and can not contain NULL values. It is set as an AUTO_INCREMENT field which means that it is an autonumber field (starting at 1 and incrementing by 1 unless otherwise specified.)
- The second column is called last_name which is a VARCHAR datatype (maximum 30 characters in length) and can not contain NULL values.
- The third column is called first_name which is a VARCHAR datatype (maximum 25 characters in length) and can contain NULL values.
- The fourth column is called birthday which is a DATE datatype and can contain NULL values.
- The primary key is called contacts_pk and is set to the contact_id column.
Now that you've created a table using the AUTO_INCREMENT attribute how can you change the starting value for the AUTO_INCREMENT field if you don't want to start at 1?
You can use the ALTER TABLE statement to change or set the next value assigned by the AUTO_INCREMENT.
In MySQL the syntax to change the starting value for an AUTO_INCREMENT column using the ALTER TABLE statement is:
ALTER TABLE table_name AUTO_INCREMENT = start_value;
table_name The name of the table whose AUTO_INCREMENT value you wish to change. Since a table in MySQL can only contain one AUTO_INCREMENT column you are only required to specify the table name that contains the sequence. You do not need to specify the name of the column that contains the AUTO_INCREMENT value. start_value The next value in the sequence to assign in the AUTO_INCREMENT column.
Let's look at an example of how to change the starting value for the AUTO_INCREMENT column in a table in MySQL.
For example:
ALTER TABLE contacts AUTO_INCREMENT = 50;
This MySQL AUTO_INCREMENT example would change the next value in the AUTO_INCREMENT field (ie: next value in the sequence) to 50 for the contact_id field in the contacts table*.*
Here are some other tutorials to help you learn more about sequences in MySQL:
Reset the Next Value in Sequence
This MySQL tutorial explains how to use comments within your SQL statements in MySQL with syntax and examples.
Did you know that you can place comments within your SQL statements in MySQL? These comments can appear on a single line or span across multiple lines. Let's look at how to do this.
There are three syntaxes that you can use to create a comment within your SQL statement in MySQL.
The syntax for creating a SQL comment in MySQL using #
symbol is:
## *comment goes here*
In MySQL a comment started with #
symbol must be at the end of a line in your SQL statement with a line break after it. This method of commenting can only span a single line within your SQL and must be at the end of the line.
The syntax for creating a SQL comment in MySQL using --
symbol is:
-- *comment goes here*
In MySQL a comment started with --
symbol is similar to a comment starting with #
symbol. When using the --
symbol the comment must be at the end of a line in your SQL statement with a line break after it. This method of commenting can only span a single line within your SQL and must be at the end of the line.
The syntax for creating a SQL comment in MySQL using /*
and */
symbols is:
/\* *comment goes here* \*/
In MySQL a comment that starts with /*
symbol and ends with */
and can be anywhere in your SQL statement. This method of commenting can span several lines within your SQL.
You can create a SQL comment on a single line in your SQL statement in MySQL.
Let's look at a SQL comment example that shows a SQL comment that is on a single line and does not span multiple lines.
SELECT contact_id last_name first_name
/\* Author: TechOnTheNet.com \*/
FROM contacts;
Here is a SQL comment that appears in the middle of the line:
SELECT /\* Author: TechOnTheNet.com \*/ contact_id last_name first_name
FROM contacts;
Here is a SQL comment that appears at the end of the line:
SELECT contact_id last_name first_name /\* Author: TechOnTheNet.com \*/
FROM contacts;
or
SELECT contact_id last_name first_name -- Author: TechOnTheNet.com
FROM contacts;
or
SELECT contact_id last_name first_name ## Author: TechOnTheNet.com
FROM contacts;
In MySQL you can create a SQL comment that spans multiple lines in your SQL statement. For example:
SELECT contact_id last_name first_name
/\*
\* Author: TechOnTheNet.com
\* Purpose: To show a comment that spans multiple lines in your SQL
\* statement in MySQL.
\*/
FROM contacts;
This SQL comment spans across multiple lines in MySQL - in this example it spans across 5 lines.
In MySQL you can also create a SQL comment that spans multiple lines using this syntax:
SELECT contact_id last_name first_name /\* Author: TechOnTheNet.com
Purpose: To show a comment that spans multiple lines in your SQL statement. \*/
FROM contacts;
MySQL will assume that everything after the /*
symbol is a comment until it reaches the */
symbol even if it spans multiple lines within the SQL statement. So in this example the SQL comment will span across 2 lines within the SQL statement.
This MySQL tutorial explores all of the comparison operators used to test for equality and inequality as well as the more advanced operators.
Comparison operators are used in the WHERE clause to determine which records to select. Here is a list of the comparison operators that you can use in MySQL:
Comparison Operator | Description |
---|---|
= | Equal |
<=> | Equal (Safe to compare NULL values) |
<> | Not Equal |
!= | Not Equal |
> | Greater Than |
>= | Greater Than or Equal |
< | Less Than |
<= | Less Than or Equal |
IN ( ) | Matches a value in a list |
NOT | Negates a condition |
BETWEEN | Within a range (inclusive) |
IS NULL | NULL value |
IS NOT NULL | Non-NULL value |
LIKE | Pattern matching with % and _ |
EXISTS | Condition is met if subquery returns at least one row |
Let's review the comparison operators that you can use in MySQL.
In MySQL you can use the =
operator to test for equality in a query. The =
operator can only test equality with values that are not NULL.
For example:
SELECT \*
FROM contacts
WHERE last_name = 'Johnson';
In this example the SELECT statement above would return all rows from the contacts table where the last_name is equal to Johnson.
Because the =
operator only compares non-NULL values it is not safe to use with NULL values. To overcome this limitation MySQL added the <=>
operator to allow you to test for equality with both NULL and non-NULL values.
To better explain the difference between the =
operator and the <=>
operator we will include some examples with both queries and data.
Assuming that we have a table called contacts in MySQL that is populated with the following data:
contact_id | last_name | website1 | website2 |
---|---|---|---|
1 | Johnson | techonthenet.com | |
2 | Anderson | ||
3 | Smith | TBD | TDB |
4 | Jackson | checkyourmath.com | digminecraft.com |
We could use the =
operator in the following query:
SELECT \*
FROM contacts
WHERE website1 = website2;
Because we used the =
operator we would get the following results:
contact_id | last_name | website1 | website2 |
---|---|---|---|
3 | Smith | TBD | TDB |
In this example the SELECT statement above would return all rows from the contacts table where the website1 is equal to website2. It does not return the second record where website1 and website2 are both NULL values.
Now let's see what happens when we rewrite our query using the <=>
operator that is safe to use with NULL values:
SELECT \*
FROM contacts
WHERE website1 <=>website2;
Because we used the <=>
operator we would get the following results:
contact_id | last_name | website1 | website2 |
---|---|---|---|
2 | Anderson | ||
3 | Smith | TBD | TDB |
Now our query returns all rows from the contacts table where website1 is equal to website2 including those records where website1 and website2 are NULL values.
In MySQL you can use the <>
or !=
operators to test for inequality in a query.
For example we could test for inequality using the <>
operator as follows:
SELECT \*
FROM contacts
WHERE last_name <> 'Johnson';
In this example the SELECT statement would return all rows from the contacts table where the last_name is not equal to Johnson.
Or you could also write this query using the !=
operator as follows:
SELECT \*
FROM contacts
WHERE last_name != 'Johnson';
Both of these queries would return the same results.
You can use the >
operator in MySQL to test for an expression greater than.
SELECT \*
FROM contacts
WHERE contact_id > 50;
In this example the SELECT statement would return all rows from the contacts table where the contact_id is greater than 50. A contact_id equal to 50 would not be included in the result set.
In MySQL you can use the >=
operator to test for an expression greater than or equal to.
SELECT \*
FROM contacts
WHERE contact_id >= 50;
In this example the SELECT statement would return all rows from the contacts table where the contact_id is greater than or equal to 50. In this case contact_id equal to 50 would be included in the result set.
You can use the <
operator in MySQL to test for an expression less than.
SELECT \*
FROM inventory
WHERE product_id < 300;
In this example the SELECT statement would return all rows from the inventory table where the product_id is less than 300. A product_id equal to 300 would not be included in the result set.
In MySQL you can use the <=
operator to test for an expression less than or equal to.
SELECT \*
FROM inventory
WHERE product_id <= 300;
In this example the SELECT statement would return all rows from the inventory table where the product_id is less than or equal to 300. In this case product_id equal to 300 would be included in the result set.
We've written specific tutorials to discuss each of the more advanced comparison operators. These topics will be covered later or you can jump to one of these tutorials now.
This MySQL tutorial explains how to use the MySQL SELECT statement with syntax and examples.
The MySQL SELECT statement is used to retrieve records from one or more tables in MySQL.
In its simplest form the syntax for the SELECT statement in MySQL is:
SELECT expressions
FROM tables
WHERE conditions ;
However the full syntax for the SELECT statement in MySQL is:
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
expressions
FROM tables
WHERE conditions
GROUP BY expressions
HAVING condition
ORDER BY expression ASC | DESC
LIMIT offset_value number_rows | LIMIT number_rows OFFSET offset_value
PROCEDURE procedure_name
INTO OUTFILE 'file_name' options
| DUMPFILE 'file_name'
| @variable1 @variable2 ... @variable_n
FOR UPDATE | LOCK IN SHARE MODE ;
ALL Optional. Returns all matching rows DISTINCT Optional. Removes duplicates from the result set. Learn more about DISTINCT clause. DISTINCTROW Optional. Synonym for DISTINCT. Removes duplicates from the result set. HIGH_PRIORITY Optional. It tells MySQL to run the SELECT before any UPDATE statements that are waiting for the same resource. It may be used with MyISAM MEMORY and MERGE tables that use table-level locking. STRAIGHT_JOIN Optional. It tells MySQL to join the tables in the order that they are listed in the FROM clause. SQL_SMALL_RESULT Optional. Uses fast temporary tables to store results (used with DISTINCT and GROUP BY). SQL_BIG_RESULT Optional. Prefers sorting rather than using a temporary table to store results (used with DISTINCT and GROUP BY). SQL_BUFFER_RESULT Optional. Uses temporary tables to store results (can not be used with subqueries). SQL_CACHE Optional. Stores the results in the query cache. SQL_NO_CACHE Optional. Does not store the results in the query cache. SQL_CALC_FOUND_ROWS Optional. Calculates how many records are in the result set (not taking into account the LIMIT modifier) which can then be retrieved using the FOUND_ROWS function. expressions The columns or calculations that you wish to retrieve. Use * if you wish to select all columns. tables The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause. WHERE conditions Optional. The conditions that must be met for the records to be selected. GROUP BY expressions Optional. It collects data across multiple records and groups the results by one or more columns. Learn more about the GROUP BY clause. HAVING condition Optional. It is used in combination with the GROUP BY to restrict the groups of returned rows to only those whose the condition is TRUE. Learn more about the HAVING clause. ORDER BY expression Optional. It is used to sort the records in your result set. Learn more about the ORDER BY clause. LIMIT Optional. If LIMIT is provided it controls the maximum number of records to retrieve. At most the number of records specified by number_rows will be returned in the result set. The first row returned by LIMIT will be determined by offset_value. PROCEDURE Optional. If provided procedure_name is the name of the procedure that should process the data in the result set. INTO Optional. If provided it allows you to write the result set to either a file or variable.
Value | Explanation |
---|---|
INTO OUTFILE 'filename' options | Writes the result set to a file called filename on the server host. For options you can specify: |
FIELDS ESCAPED BY 'character' FIELDS TERMINATED BY 'character' OPTIONALLY ENCLOSED BY 'character' LINES TERMINATED BY 'character'
where character is the character to display as the ESCAPE ENCLOSED or TERMINATED character. For example:
SELECT supplier_id supplier_name FROM suppliers INTO OUTFILE 'results.txt' FIELDS TERMINATED BY ' ' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n'; | | INTO DUMPFILE 'filename' | Writes one row of the result set to a file called filename on the server host. With this method there is no column termination no line termination or escape processing. | | INTO @variable1 @variable2 ... @variable_n | Writes the result set to one or more variables as specified by @variable1 @variable2 ... @variable_n |
FOR UPDATE Optional. Records affected by the query are write-locked until the transaction has completed. LOCK IN SHARE MODE Optional. Records affected by the query can be used by other transactions but can not be updated or deleted by those other transactions.
Let's look at how to use a MySQL SELECT query to select all fields from a table.
SELECT \*
FROM order_details
WHERE quantity >= 10
ORDER BY quantity DESC;
In this MySQL SELECT statement example we've used * to signify that we wish to select all fields from the order_details table where the quantity is greater than or equal to 10. The result set is sorted by quantity in descending order.
You can also use the MySQL SELECT statement to select individual fields from the table as opposed to all fields from the table.
For example:
SELECT order_id quantity unit_price
FROM order_details
WHERE quantity < 500
ORDER BY quantity ASC unit_price DESC;
This MySQL SELECT example would return only the order_id quantity and unit_price fields from the order_details table where the quantity is less than 500. The results are sorted by quantity in ascending order and then unit_price in descending order.
You can also use the MySQL SELECT statement to retrieve fields from multiple tables.
SELECT order_details.order_id customers.customer_name
FROM customers
INNER JOIN order_details
ON customers.customer_id = order_details.customer_id
ORDER BY order_id;
This MySQL SELECT example joins two tables together to gives us a result set that displays the order_id and customer_name fields where the customer_id value matches in both the customers and order_details table. The results are sorted by order_id in ascending order.
You can also use the MySQL SELECT statement to write the result set to a file.
For example:
SELECT order_id quantity unit_price
FROM order_details
WHERE quantity < 500
ORDER BY quantity
INTO OUTFILE 'results.txt'
FIELDS TERMINATED BY ' ' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n';
This MySQL SELECT example would return only the order_id quantity and unit_price fields from the order_details table where the quantity is less than 500. The results would be sorted by quantity in ascending order and written to a file called results.txt.
This MySQL tutorial explains how to use the SELECT LIMIT statement in MySQL with syntax and examples.
The MySQL SELECT LIMIT statement is used to retrieve records from one or more tables in MySQL and limit the number of records returned based on a limit value.
The syntax for the SELECT LIMIT statement in MySQL is:
SELECT expressions
FROM tables
WHERE conditions
ORDER BY expression ASC | DESC
LIMIT row_count;
expressions The columns or calculations that you wish to retrieve. tables The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause. WHERE conditions Optional. The conditions that must be met for the records to be selected. ORDER BY expression Optional. It is used in the SELECT LIMIT statement so that you can order the results and target those records that you wish to return. LIMIT row_count Specifies a limited number of rows in the result set to be returned based on row_count. For example LIMIT 10 would return the first 10 rows matching the SELECT criteria. This is where sort order matters so be sure to use an ORDER BY clause appropriately.
Let's look at how to use a SELECT statement with a LIMIT clause in MySQL.
For example:
SELECT contact_id last_name first_name
FROM contacts
WHERE website = 'TechOnTheNet.com'
ORDER BY contact_id DESC
LIMIT 5;
This MySQL SELECT LIMIT example would select the first 5 records from the contacts table where the website is 'TechOnTheNet.com'. Note that the results are sorted by contact_id in descending order so this means that the 5 largest contact_id values will be returned by the SELECT LIMIT statement.
If there are other records in the contacts table that have a website value of 'TechOnTheNet.com' they will not be returned by the SELECT LIMIT statement in MySQL.
If we wanted to select the 5 smallest contact_id values instead of the largest we could change the sort order as follows:
SELECT contact_id last_name first_name
FROM contacts
WHERE website = 'TechOnTheNet.com'
ORDER BY contact_id ASC
LIMIT 5;
Now the results would be sorted by contact_id in ascending order so the first 5 smallest contact_id records that have a website of 'TechOnTheNet.com' would be returned by this SELECT LIMIT statement. No other records would be returned by this query.
This MySQL tutorial explains how to use the MySQL INSERT statement with syntax and examples.
The MySQL INSERT statement is used to insert a single record or multiple records into a table in MySQL.
In its simplest form the syntax for the INSERT statement when inserting a single record using the VALUES keyword in MySQL is:
INSERT INTO table
(column1 column2 ... )
VALUES
(expression1 expression2 ... )
(expression1 expression2 ... )
...;
However the full syntax for the INSERT statement when inserting a single record using the VALUES keyword is:
INSERT LOW_PRIORITY | DELAYED | HIGH_PRIORITY IGNORE
INTO table
(column1 column2 ... )
VALUES
(expression1 expression2 ... )
(expression1 expression2 ... )
ON DUPLICATE KEY UPDATE
dup_column1 = dup_expression1
dup_column2 = dup_expression2
... ;
Or...
In its simplest form the syntax for the INSERT statement when inserting multiple records using a sub-select in MySQL is:
INSERT INTO table
(column1 column2 ... )
SELECT expression1 expression2 ...
FROM source_table
WHERE conditions ;
However the full syntax for the INSERT statement when inserting multiple records using a sub-select is:
INSERT LOW_PRIORITY | HIGH_PRIORITY IGNORE
INTO table
(column1 column2 ... )
SELECT expression1 expression2 ...
FROM source_table
WHERE conditions
ON DUPLICATE KEY UPDATE
dup_column1 = dup_expression1
dup_column2 = dup_expression2
... ;
LOW_PRIORITY Optional. The insert will be delayed until there are no processes reading from the table. DELAYED Optional. The inserted rows are put in a buffer until the table is available and the next SQL statement can be issued by the process. HIGH_PRIORITY Optional. The insert will be given a higher priority overriding the database's "insert" priorities. IGNORE Optional. If specified all errors encountered during the insert are ignored and treated instead as warnings. table The table to insert the records into. column1 column2 The columns in the table to insert values. expression1 expression2 The values to assign to the columns in the table. So column1 would be assigned the value of expression1 column2 would be assigned the value of expression2 and so on. source_table The source table when inserting data from another table. WHERE conditions Optional. The conditions that must be met for the records to be inserted. ON DUPLICATE KEY UPDATE Optional. If specified and a row is inserted that would violate a primary key or unique index an update will be performed instead of an insert. dup_column1 would be assigned the value of dup_expression1 dup_column2 would be assigned the value of dup_expression2 and so on.
- When inserting records into a table using the MySQL INSERT statement you must provide a value for every NOT NULL column.
- You can omit a column from the MySQL INSERT statement if the column allows NULL values.
The simplest way to create a MySQL INSERT query to list the values using the VALUES keyword.
For example:
INSERT INTO suppliers
(supplier_id supplier_name)
VALUES
(1000 'Dell');
This MySQL INSERT statement would result in one record being inserted into the suppliers table. This new record would have a supplier_id of 1000 and a supplier_name of 'Dell'.
You can also create more complicated MySQL INSERT statements using sub-selects.
For example:
INSERT INTO suppliers
(supplier_id supplier_name)
SELECT account_no name
FROM customers
WHERE customer_id < 5000;
By placing a SELECT statement within the INSERT statement you can perform multiples inserts quickly.
With this type of insert you may wish to check for the number of rows being inserted. You can determine the number of rows that will be inserted by calling the mysql_info function or by running the following MySQL SELECT statement before performing the insert.
SELECT count(\*)
FROM customers
WHERE customer_id < 5000;
This MySQL tutorial explains how to use the MySQL UPDATE statement with syntax and examples.
The MySQL UPDATE statement is used to update existing records in a table in a MySQL database. There are 3 syntaxes for the UPDATE statement depending on the type of update that you wish to perform.
In its simplest form the syntax for the UPDATE statement when updating one table in MySQL is:
UPDATE table
SET column1 = expression1
column2 = expression2
...
WHERE conditions ;
However the full syntax for the MySQL UPDATE statement when updating one table is:
UPDATE LOW_PRIORITY IGNORE
table
SET column1 = expression1
column2 = expression2
...
WHERE conditions
ORDER BY expression ASC | DESC
LIMIT number_rows ;
OR
The syntax for the UPDATE statement when updating one table with data from another table in MySQL is:
UPDATE table1
SET column1 = (SELECT expression1
FROM table2
WHERE conditions)
WHERE conditions ;
OR
The syntax for the MySQL UPDATE statement when updating multiple tables is:
UPDATE table1 table2 ...
SET column1 = expression1
column2 = expression2
...
WHERE table1.column = table2.column
AND conditions;
LOW_PRIORITY Optional. If LOW_PRIORITY is provided the update will be delayed until there are no processes reading from the table. LOW_PRIORITY may be used with MyISAM MEMORY and MERGE tables that use table-level locking. IGNORE Optional. If IGNORE is provided all errors encountered during the update are ignored. If an update on a row would result in a violation of a primary key or unique index the update on that row is not performed. column1 column2 The columns that you wish to update. expression1 expression2 The new values to assign to the column1 column2. So column1 would be assigned the value of expression1 column2 would be assigned the value of expression2 and so on. WHERE conditions Optional. The conditions that must be met for the update to execute. ORDER BY expression Optional. It may be used in combination with LIMIT to sort the records appropriately when limiting the number of records to be updated. LIMIT number_rows Optional. If LIMIT is provided it controls the maximum number of records to update in the table. At most the number of records specified by number_rows will be update in the table.
Let's look at a very simple MySQL UPDATE query example.
UPDATE customers
SET last_name = 'Anderson'
WHERE customer_id = 5000;
This MySQL UPDATE example would update the last_name to 'Anderson' in the customers table where the customer_id is 5000.
Let's look at a MySQL UPDATE example where you might want to update more than one column with a single UPDATE statement.
UPDATE customers
SET state = 'California'
customer_rep = 32
WHERE customer_id > 100;
When you wish to update multiple columns you can do this by separating the column/value pairs with commas.
This MySQL UPDATE statement example would update the state to 'California' and the customer_rep to 32 where the customer_id is greater than 100.
Let's look at an UPDATE example that shows how to update a table with data from another table in MySQL.
UPDATE customers
SET city = (SELECT city
FROM suppliers
WHERE suppliers.supplier_name = customers.customer_name)
WHERE customer_id > 2000;
This UPDATE example would update only the customers table for all records where the customer_id is greater than 2000. When the supplier_name from the suppliers table matches the customer_name from the customers table the city from the suppliers table would be copied to the city field in the customers table.
Let's look at a MySQL UPDATE example where you might want to perform an update that involves more than one table in a single UPDATE statement.
UPDATE customers suppliers
SET customers.city = suppliers.city
WHERE customers.customer_id = suppliers.supplier_id;
This MySQL UPDATE statement example would update the city field in the customers table to the city from the suppliers table where the customer_id matches the supplier_id.
This MySQL tutorial explains how to use the MySQL DELETE statement with syntax and examples.
The MySQL DELETE statement is used to delete a single record or multiple records from a table in MySQL.
In its simplest form the syntax for the DELETE statement in MySQL is:
DELETE FROM table
WHERE conditions ;
However the full syntax for the DELETE statement in MySQL is:
DELETE LOW_PRIORITY QUICK IGNORE FROM table
WHERE conditions
ORDER BY expression ASC | DESC
LIMIT number_rows ;
LOW_PRIORITY Optional. If LOW_PRIORITY is provided the delete will be delayed until there are no processes reading from the table. LOW_PRIORITY may be used with MyISAM MEMORY and MERGE tables that use table-level locking. QUICK Optional. If QUICK is provided ndex leaves are not merged during the delete making the deletion faster for MyISAM tables. IGNORE Optional. If IGNORE is provided all errors encountered during the delete are ignored. IGNORE was introduced in MySQL 4.1.1. table The table that you wish to delete records from. WHERE conditions Optional. The conditions that must be met for the records to be deleted. If no conditions are provided then all records from the table will be deleted. ORDER BY expression Optional. It may be used in combination with LIMIT to sort the records appropriately when limiting the number of records to be deleted. LIMIT Optional. If LIMIT is provided it controls the maximum number of records to delete from the table. At most the number of records specified by number_rows will be deleted from the table.
- You do not need to list fields in the MySQL DELETE statement since you are deleting the entire row from the table.
Let's look at a simple MySQL DELETE query example where we just have one condition in the DELETE statement.
For example:
DELETE FROM contacts
WHERE last_name = 'Johnson';
This MySQL DELETE example would delete all records from the contacts table where the last_name is Johnson.
You may wish to check for the number of rows that will be deleted. You can determine the number of rows that will be deleted by calling the mysql_info function or by running the following MySQL SELECT statement before performing the delete.
SELECT count(\*)
FROM contacts
WHERE last_name = 'Johnson';
Let's look at a MySQL DELETE example where we just have two conditions in the DELETE statement.
For example:
DELETE FROM contacts
WHERE last_name = 'Johnson'
AND contact_id < 1000;
This MySQL DELETE example would delete all records from the contacts table where the last_name is 'Johnson' and the customer_id is less than 1000.
You may wish to check for the number of rows that will be deleted. You can determine the number of rows that will be deleted by calling the mysql_info function or by running the following MySQL SELECT statement before performing the delete.
SELECT count(\*)
FROM contacts
WHERE last_name = 'Johnson'
AND contact_id < 1000;
Let's look at a MySQL DELETE example where we use the LIMIT modifier to control the number of records deleted.
For example:
DELETE FROM contacts
WHERE last_name = 'Johnson'
ORDER BY contact_id DESC
LIMIT 1;
This MySQL DELETE example would delete one record from the contacts table (as specified by LIMIT 1) where the last_name is 'Johnson'. The DELETE is sorted in descending order by contact_id so only the record with the largest contact_id whose last_name is 'Johnson' would be deleted from table. All other records in the contacts table with the last_name of 'Johnson' would remain in the table.
If you wished to instead delete the smallest contact_id whose last_name is 'Johnson' you could rewrite the DELETE statement as follows:
DELETE FROM contacts
WHERE last_name = 'Johnson'
ORDER BY contact_id ASC
LIMIT 1;
Or you could delete the last record in the contacts table with the following DELETE statement (assuming that the contact_id is a sequential number):
DELETE FROM contacts
ORDER BY contact_id DESC
LIMIT 1;
You can also perform more complicated deletes.
You may wish to delete records in one table based on values in another table. Since you can't list more than one table in the MySQL FROM clause when you are performing a delete you can use the MySQL EXISTS clause.
For example:
DELETE FROM suppliers
WHERE EXISTS
( SELECT \*
FROM customers
WHERE customers.customer_id = suppliers.supplier_id
AND customer_id > 500 );
This MySQL DELETE example would delete all records in the suppliers table where there is a record in the customers table whose customer_id is greater than 500 and the customer_id matches the supplier_id.
You may wish to check for the number of rows that will be deleted. You can determine the number of rows that will be deleted by calling the mysql_info function or by running the following MySQL SELECT statement before performing the delete.
SELECT COUNT(\*) FROM suppliers
WHERE EXISTS
( SELECT \*
FROM customers
WHERE customers.customer_id = suppliers.supplier_id
AND customer_id > 500 );
This MySQL tutorial explains how to use the DELETE LIMIT statement in MySQL with syntax and examples.
The MySQL DELETE LIMIT statement is used to delete records from a table in MySQL and limit the number of records deleted based on a limit value.
The syntax for the DELETE LIMIT statement in MySQL is:
DELETE FROM table
WHERE conditions
ORDER BY expression ASC | DESC
LIMIT row_count;
table The table that you wish to delete records from. WHERE conditions Optional. The conditions that must be met for the records to be deleted. ORDER BY expression Optional. It is used in the DELETE LIMIT statement so that you can order the results and target those records that you wish to delete. LIMIT row_count It specifies a limited number of rows in the result set to delete based on row_count. For example LIMIT 10 would delete the first 10 rows matching the delete criteria. This is where sort order matters so be sure to use an ORDER BY clause appropriately.
- You do not need to list fields in the MySQL DELETE LIMIT statement since you are deleting the entire row from the table.
Let's look at how to use a DELETE statement with a LIMIT clause in MySQL.
For example:
DELETE FROM contacts
WHERE website = 'TechOnTheNet.com'
ORDER BY contact_id DESC
LIMIT 2;
This DELETE LIMIT example would delete the first 2 records from the contacts table where the website is 'TechOnTheNet.com'. Note that the results are sorted by contact_id in descending order so this means that the 2 largest contact_id values will be deleted by the DELETE LIMIT statement.
If there are other records in the contacts table that have a website value of 'TechOnTheNet.com' they will not be deleted by the DELETE LIMIT statement in MySQL.
If we wanted to delete the smallest contact_id values instead of the largest two we could change the sort order as follows:
DELETE FROM contacts
WHERE website = 'TechOnTheNet.com'
ORDER BY contact_id ASC
LIMIT 2;
Now the results would be sorted by contact_id in ascending order so the first two smallest contact_id records that have a website of 'TechOnTheNet.com' would be deleted by this DELETE LIMIT statement. No other records would be affected.
This MySQL tutorial explains how to use the MySQL TRUNCATE TABLE statement with syntax and examples.
The TRUNCATE TABLE statement is used to remove all records from a table in MySQL. It performs the same function as a DELETE statement without a WHERE clause.
Warning: If you truncate a table the TRUNCATE TABLE statement can not be rolled back.
The syntax for the TRUNCATE TABLE statement in MySQL is:
TRUNCATE TABLE database_name. table_name;
database_name Optional. If specified it is the name of the database. table_name The table that you wish to truncate.
- When you truncate a table the AUTO_INCREMENT counters on the table will be reset.
- MySQL truncates the table by dropping and creating the table. Thus the DELETE triggers for the table do not fire during the truncation.
- Starting in MySQL 5.5 you can not truncate an InnoDB table that is referenced by a foreign key in another table.
- Starting in MySQL 5.6 you can not truncate a NDB table that is referenced by a foreign key in another table.
In MySQL truncating a table is a fast way to clear out records from a table if you don't need to worry about rolling back. In most cases MySQL handles the process of table truncation a bit differently than other databases such as Oracle or SQL Server.
Let's look at an example of how to use the TRUNCATE TABLE statement in MySQL.
For example:
TRUNCATE TABLE customers;
This example would truncate the table called customers and remove all records from that table.
It would be equivalent to the following DELETE statement in MySQL:
DELETE FROM customers;
Both of these statements would result in all data from the customers table being deleted. The main difference between the two is that you can roll back the DELETE statement if you choose but you can't roll back the TRUNCATE TABLE statement.
Let's look at one more example where we prefix the table name with the database name.
For example:
TRUNCATE TABLE totn.products;
This example would truncate the table called products in the database called totn.
This MySQL tutorial explains how to use the MySQL UNION operator with syntax and examples.
The MySQL UNION operator is used to combine the result sets of 2 or more SELECT statements. It removes duplicate rows between the various SELECT statements.
Each SELECT statement within the UNION operator must have the same number of fields in the result sets with similar data types.
The syntax for the UNION operator in MySQL is:
SELECT expression1 expression2 ... expression_n
FROM tables
WHERE conditions
UNION DISTINCT
SELECT expression1 expression2 ... expression_n
FROM tables
WHERE conditions ;
expression1 expression2 ... expression_n The columns or calculations that you wish to retrieve. tables The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause. WHERE conditions Optional. The conditions that must be met for the records to be selected. DISTINCT Optional. Removes duplicates from the result set but the inclusion of the DISTINCT modifier has no impact on the result set of the UNION operator because by default the UNION operator already removes duplicates.
- There must be same number of expressions in both SELECT statements.
- Since the UNION operator by default removes all duplicate rows from the result set providing the UNION DISTINCT modifier has no effect on the results.
- The column names from the first SELECT statement in the UNION operator are used as the column names for the result set.
The following is an example of the MySQL UNION operator that returns one field from multiple SELECT statements (and both fields have the same data type):
SELECT supplier_id
FROM suppliers
UNION
SELECT supplier_id
FROM order_details;
In this MySQL UNION operator example if a supplier_id appeared in both the suppliers and order_details table it would appear once in your result set. The MySQL UNION operator removes duplicates. If you do not wish to remove duplicates try using the MySQL UNION ALL operator.
The MySQL UNION operator can use the ORDER BY clause to order the results of the query.
For example:
SELECT supplier_id supplier_name
FROM suppliers
WHERE supplier_id <= 500
UNION
SELECT company_id company_name
FROM companies
WHERE company_name = 'Apple'
ORDER BY 2;
In this MySQL UNION operator since the column names are different between the two SELECT statements it is more advantageous to reference the columns in the ORDER BY clause by their position in the result set. In this example we've sorted the results by supplier_name / company_name in ascending order as denoted by the ORDER BY 2
.
The supplier_name / company_name fields are in position #2 in the result set.
This MySQL tutorial explains how to use the MySQL UNION ALL operator with syntax and examples.
The MySQL UNION ALL operator is used to combine the result sets of 2 or more SELECT statements. It returns all rows from the query and it does not remove duplicate rows between the various SELECT statements.
Each SELECT statement within the MySQL UNION ALL operator must have the same number of fields in the result sets with similar data types.
The syntax for the UNION ALL operator in MySQL is:
SELECT expression1 expression2 ... expression_n
FROM tables
WHERE conditions
UNION ALL
SELECT expression1 expression2 ... expression_n
FROM tables
WHERE conditions ;
expression1 expression2 ... expression_n The columns or calculations that you wish to retrieve. tables The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause. WHERE conditions Optional. The conditions that must be met for the records to be selected.
- There must be same number of expressions in both SELECT statements.
- The column names from the first SELECT statement are used as the column names for the result set.
The following is an example of the MySQL UNION ALL operator that returns one field from multiple SELECT statements (and both fields have the same data type):
SELECT supplier_id
FROM suppliers
UNION ALL
SELECT supplier_id
FROM orders;
This MySQL UNION ALL operator would return a supplier_id multiple times in your result set if the supplier_id appeared in both the suppliers and orders table. The MySQL UNION ALL operator does not remove duplicates. If you wish to remove duplicates try using the MySQL UNION operator.
The MySQL UNION ALL operator can use the ORDER BY clause to order the results of the operator.
For example:
SELECT supplier_id supplier_name
FROM suppliers
WHERE state = 'California'
UNION ALL
SELECT company_id company_name
FROM companies
WHERE company_id > 1000
ORDER BY 2;
In this MySQL UNION ALL operator since the column names are different between the two SELECT statements it is more advantageous to reference the columns in the ORDER BY clause by their position in the result set. In this example we've sorted the results by supplier_name / company_name in ascending order as denoted by the ORDER BY 2
.
The supplier_name / company_name fields are in position #2 in the result set.
This MySQL tutorial explains how to use the INTERSECT operator with syntax and examples.
Although there is no INTERSECT operator in MySQL you can easily simulate this type of query using either the IN clause or the EXISTS clause depending on the complexity of the INTERSECT query.
First let's explain what an INTERSECT query is. An INTERSECT query returns the intersection of 2 or more datasets. If a record exists in both data sets it will be included in the INTERSECT results. However if a record exists in one data set and not in the other it will be omitted from the INTERSECT results.
Explanation: The INTERSECT query will return the records in the blue shaded area. These are the records that exist in both Dataset1 and Dataset2.
The syntax for the INTERSECT operator in MySQL is:
SELECT expression1 expression2 ... expression_n
FROM tables
WHERE conditions
INTERSECT
SELECT expression1 expression2 ... expression_n
FROM tables
WHERE conditions ;
expression1 expression2 ... expression_n The columns or calculations that you wish to retrieve. tables The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause. WHERE conditions Optional. The conditions that must be met for the records to be selected.
- There must be same number of expressions in both SELECT statements and have similar data types.
First let's explore how to simulate an INTERSECT query in MySQL that has one field with the same data type.
If the database supported the INTERSECT operator (which MySQL does not) this is how you would have use the INTERSECT operator to return the common category_id values between the products and inventory tables.
SELECT category_id
FROM products
INTERSECT
SELECT category_id
FROM inventory;
Since you can't use the INTERSECT operator in MySQL you will use the IN operator to simulate the INTERSECT query as follows:
SELECT products.category_id
FROM products
WHERE products.category_id IN (SELECT inventory.category_id FROM inventory);
In this simple example you can use the IN operator to return all category_id values that exist in both the products and inventory tables.
Now let's complicate our example further by adding WHERE conditions to the INTERSECT query.
For example this is how the INTERSECT would look with WHERE conditions:
SELECT category_id
FROM products
WHERE category_id < 100
INTERSECT
SELECT category_id
FROM inventory
WHERE quantity > 0;
This is how you would simulate the INTERSECT query using the IN operator and include the WHERE conditions:
SELECT products.category_id
FROM products
WHERE products.category_id < 100
AND products.category_id IN
(SELECT inventory.category_id
FROM inventory
WHERE inventory.quantity > 0);
In this example the WHERE clauses have been added that filter both the products table as well as the results from the inventory table.
Next let's look at how to simulate an INTERSECT query in MySQL that returns more than one column.
First this is how you would use the INTERSECT operator to return multiple expressions.
SELECT contact_id last_name first_name
FROM contacts
WHERE contact_id < 100
INTERSECT
SELECT customer_id last_name first_name
FROM customers
WHERE last_name <> 'Johnson';
Again since you can't use the INTERSECT operator in MySQL you can use the EXISTS clause in more complex situations to simulate the INTERSECT query as follows:
SELECT contacts.contact_id contacts.last_name contacts.first_name
FROM contacts
WHERE contacts.contact_id < 100
AND EXISTS (SELECT \*
FROM customers
WHERE customers.last_name <> 'Johnson'
AND customers.customer_id = contacts.contact_id
AND customers.last_name = contacts.last_name
AND customers.first_name = contacts.first_name);
In this more complex example you can use the EXISTS clause to return multiple expressions that exist in both the contacts table where the contact_id is less than 100 as well as the customers table where the last_name is not equal to Johnson.
Because you are doing an INTERSECT you need to join the intersect fields as follows:
AND customers.customer_id = contacts.contact_id
AND customers.last_name = contacts.last_name
AND customers.first_name = contacts.first_name
This join is performed to ensure that the customer_id last_name and first_name fields from the customers table are intersected with the contact_id last_name and first_name fields from the contacts table.
This MySQL tutorial explains how to use subqueries in MySQL with syntax and examples.
In MySQL a subquery is a query within a query. You can create subqueries within your SQL statements. These subqueries can reside in the WHERE clause the FROM clause or the SELECT clause.
- In MySQL a subquery is also called an INNER QUERY or INNER SELECT.
- In MySQL the main query that contains the subquery is also called the OUTER QUERY or OUTER SELECT.
Most often the subquery will be found in the WHERE clause. These subqueries are also called nested subqueries.
For example:
SELECT c.contact_id c.last_name
FROM contacts c
WHERE c.site_name IN
(SELECT a.site_name
FROM address_book a
WHERE a.address_book_id < 50);
The subquery portion of the SELECT statement above is:
(SELECT a.site_name
FROM address_book a
WHERE a.address_book_id < 50);
This subquery allows you to find all site_name values from the address_book table that have an address_book_id less than 50. The subquery is then used to filter the results from the main query using the IN condition.
This subquery could have alternatively been written as an INNER join as follows:
SELECT c.contact_id c.last_name
FROM contacts c
INNER JOIN address_book a
ON c.site_name = a.site_name
WHERE a.address_book_id < 50;
This INNER JOIN would run more efficiently than the original subquery. It is important to note though that not all subqueries can be rewritten using joins.
A subquery can also be found in the FROM clause. These are called inline views.
For example:
SELECT contacts.last_name subquery1.total_size
FROM contacts
(SELECT site_name SUM(file_size) AS total_size
FROM pages
GROUP BY site_name) subquery1
WHERE subquery1.site_name = contacts.site_name;
In this example we've created a subquery in the FROM clause as follows:
(SELECT site_name SUM(file_size) AS total_size
FROM pages
GROUP BY site_name) subquery1
This subquery has been aliased with the name subquery1. This will be the name used to reference this subquery or any of its fields.
A subquery can also be found in the SELECT clause. These are generally used when you wish to retrieve a calculation using an aggregate function such as the SUM COUNT MIN MAX or AVG function but you do not want the aggregate function to apply to the main query.
For example:
SELECT p1.site_name
(SELECT MAX(file_size)
FROM pages p2
WHERE p1.site_id = p2.site_id) subquery2
FROM pages p1;
In this example we've created a subquery in the SELECT clause as follows:
(SELECT MAX(file_size)
FROM pages p2
WHERE p1.site_id = p2.site_id) subquery2
The subquery has been aliased with the name subquery2. This will be the name used to reference this subquery or any of its fields.
The trick to placing a subquery in the SELECT clause is that the subquery must return a single value. This is why an aggregate function such as the SUM COUNT MIN MAX or AVG function is commonly used in the subquery.
This MySQL tutorial explains how to use MySQL JOINS (inner and outer) with syntax visual illustrations and examples.
MySQL JOINS are used to retrieve data from multiple tables. A MySQL JOIN is performed whenever two or more tables are joined in a SQL statement.
There are different types of MySQL joins:
- MySQL INNER JOIN (or sometimes called simple join)
- MySQL LEFT OUTER JOIN (or sometimes called LEFT JOIN)
- MySQL RIGHT OUTER JOIN (or sometimes called RIGHT JOIN)
So let's discuss MySQL JOIN syntax look at visual illustrations of MySQL JOINS and explore MySQL JOIN examples.
Chances are you've already written a statement that uses a MySQL INNER JOIN. It is the most common type of join. MySQL INNER JOINS return all rows from multiple tables where the join condition is met.
The syntax for the INNER JOIN in MySQL is:
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;
In this visual diagram the MySQL INNER JOIN returns the shaded area:
The MySQL INNER JOIN would return the records where table1 and table2 intersect.
Here is an example of a MySQL INNER JOIN:
SELECT suppliers.supplier_id suppliers.supplier_name orders.order_date
FROM suppliers
INNER JOIN orders
ON suppliers.supplier_id = orders.supplier_id;
This MySQL INNER JOIN example would return all rows from the suppliers and orders tables where there is a matching supplier_id value in both the suppliers and orders tables.
Let's look at some data to explain how the INNER JOINS work:
We have a table called suppliers with two fields (supplier_id and supplier_name). It contains the following data:
supplier_id | supplier_name |
---|---|
10000 | IBM |
10001 | Hewlett Packard |
10002 | Microsoft |
10003 | NVIDIA |
We have another table called orders with three fields (order_id supplier_id and order_date). It contains the following data:
order_id | supplier_id | order_date |
---|---|---|
500125 | 10000 | 2013/05/12 |
500126 | 10001 | 2013/05/13 |
500127 | 10004 | 2013/05/14 |
If we run the MySQL SELECT statement (that contains an INNER JOIN) below:
SELECT suppliers.supplier_id suppliers.supplier_name orders.order_date
FROM suppliers
INNER JOIN orders
ON suppliers.supplier_id = orders.supplier_id;
Our result set would look like this:
supplier_id | name | order_date |
---|---|---|
10000 | IBM | 2013/05/12 |
10001 | Hewlett Packard | 2013/05/13 |
The rows for Microsoft and NVIDIA from the supplier table would be omitted since the supplier_id's 10002 and 10003 do not exist in both tables. The row for 500127 (order_id) from the orders table would be omitted since the supplier_id 10004 does not exist in the suppliers table.
As a final note it is worth mentioning that the MySQL INNER JOIN example above could be rewritten using the older implicit syntax as follows (but we still recommend using the INNER JOIN keyword syntax):
SELECT suppliers.supplier_id suppliers.supplier_name orders.order_date
FROM suppliers orders
WHERE suppliers.supplier_id = orders.supplier_id;
Another type of join is called a MySQL LEFT OUTER JOIN. This type of join returns all rows from the LEFT-hand table specified in the ON condition and only those rows from the other table where the joined fields are equal (join condition is met).
The syntax for the LEFT OUTER JOIN in MySQL is:
SELECT columns
FROM table1
LEFT OUTER JOIN table2
ON table1.column = table2.column;
In some databases the LEFT OUTER JOIN keywords are replaced with LEFT JOIN.
In this visual diagram the MySQL LEFT OUTER JOIN returns the shaded area:
The MySQL LEFT OUTER JOIN would return the all records from table1 and only those records from table2 that intersect with table1.
Here is an example of a MySQL LEFT OUTER JOIN:
SELECT suppliers.supplier_id suppliers.supplier_name orders.order_date
FROM suppliers
LEFT JOIN orders
ON suppliers.supplier_id = orders.supplier_id;
This LEFT OUTER JOIN example would return all rows from the suppliers table and only those rows from the orders table where the joined fields are equal.
If a supplier_id value in the suppliers table does not exist in the orders table all fields in the orders table will display as <null*>* in the result set.
Let's look at some data to explain how LEFT OUTER JOINS work:
We have a table called suppliers with two fields (supplier_id and supplier_name). It contains the following data:
supplier_id | supplier_name |
---|---|
10000 | IBM |
10001 | Hewlett Packard |
10002 | Microsoft |
10003 | NVIDIA |
We have a second table called orders with three fields (order_id supplier_id and order_date). It contains the following data:
order_id | supplier_id | order_date |
---|---|---|
500125 | 10000 | 2013/05/12 |
500126 | 10001 | 2013/05/13 |
If we run the SELECT statement (that contains a LEFT OUTER JOIN) below:
SELECT suppliers.supplier_id suppliers.supplier_name orders.order_date
FROM suppliers
LEFT JOIN orders
ON suppliers.supplier_id = orders.supplier_id;
Our result set would look like this:
supplier_id | supplier_name | order_date |
---|---|---|
10000 | IBM | 2013/05/12 |
10001 | Hewlett Packard | 2013/05/13 |
10002 | Microsoft | |
10003 | NVIDIA |
The rows for Microsoft and NVIDIA would be included because a LEFT OUTER JOIN was used. However you will notice that the order_date field for those records contains a value.
Another type of join is called a MySQL RIGHT OUTER JOIN. This type of join returns all rows from the RIGHT-hand table specified in the ON condition and only those rows from the other table where the joined fields are equal (join condition is met).
The syntax for the RIGHT OUTER JOIN in MySQL is:
SELECT columns
FROM table1
RIGHT OUTER JOIN table2
ON table1.column = table2.column;
In some databases the RIGHT OUTER JOIN keywords are replaced with RIGHT JOIN.
In this visual diagram the MySQL RIGHT OUTER JOIN returns the shaded area:
The MySQL RIGHT OUTER JOIN would return the all records from table2 and only those records from table1 that intersect with table2.
Here is an example of a MySQL RIGHT OUTER JOIN:
SELECT orders.order_id orders.order_date suppliers.supplier_name
FROM suppliers
RIGHT JOIN orders
ON suppliers.supplier_id = orders.supplier_id;
This RIGHT OUTER JOIN example would return all rows from the orders table and only those rows from the suppliers table where the joined fields are equal.
If a supplier_id value in the orders table does not exist in the suppliers table all fields in the suppliers table will display as <null*>* in the result set.
Let's look at some data to explain how RIGHT OUTER JOINS work:
We have a table called suppliers with two fields (supplier_id and supplier_name). It contains the following data:
supplier_id | supplier_name |
---|---|
10000 | Apple |
10001 |
We have a second table called orders with three fields (order_id supplier_id and order_date). It contains the following data:
order_id | supplier_id | order_date |
---|---|---|
500125 | 10000 | 2013/08/12 |
500126 | 10001 | 2013/08/13 |
500127 | 10002 | 2013/08/14 |
If we run the SELECT statement (that contains a RIGHT OUTER JOIN) below:
SELECT orders.order_id orders.order_date suppliers.supplier_name
FROM suppliers
RIGHT JOIN orders
ON suppliers.supplier_id = orders.supplier_id;
Our result set would look like this:
order_id | order_date | supplier_name |
---|---|---|
500125 | 2013/08/12 | Apple |
500126 | 2013/08/13 | |
500127 | 2013/08/14 |
The row for 500127 (order_id) would be included because a RIGHT OUTER JOIN was used. However you will notice that the supplier_name field for that record contains a value.
This MySQL tutorial explains how to use MySQL ALIASES (temporary names for columns or tables) with syntax and examples.
MySQL ALIASES can be used to create a temporary name for columns or tables.
- COLUMN ALIASES are used to make column headings in your result set easier to read.
- TABLE ALIASES are used to shorten your SQL to make it easier to read or when you are performing a self join (ie: listing the same table more than once in the FROM clause).
The syntax to ALIAS A COLUMN in MySQL is:
column_name AS alias_name
OR
The syntax to ALIAS A TABLE in MySQL is:
table_name AS alias_name
column_name The original name of the column that you wish to alias. table_name The original name of the table that you wish to alias. AS Optional. Most programmers will specify the AS keyword when aliasing a column name but not when aliasing a table name. Whether you specify the AS keyword or not has no impact on the alias in MySQL. It is a personal choice in MySQL unlike other databases. (Our examples will use AS when aliasing a column name but omit AS when aliasing a table name.) alias_name The temporary name to assign to the column or table.
- If the alias_name contains spaces you must enclose the alias_name in quotes.
- It is acceptable to use spaces when you are aliasing a column name. However it is not generally good practice to use spaces when you are aliasing a table name.
- The alias_name is only valid within the scope of the SQL statement.
Generally aliases are used to make the column headings in your result set easier to read. For example when using the MAX function you might alias the result of the MAX function in MySQL.
For example:
SELECT department MAX(salary) AS highest
FROM employees
GROUP BY department;
In this example we've aliased the MAX(salary) field as highest. As a result highest will display as the heading for the second column when the result set is returned. Because our alias_name did not include any spaces we are not required to enclose the alias_name in quotes.
However it would have been perfectly acceptable to write this example using quotes as follows:
SELECT department MAX(salary) AS "highest"
FROM employees
GROUP BY department;
Next let's look at an example where we are required to enclose the alias_name in quotes.
For example:
SELECT department MAX(salary) AS "highest salary"
FROM employees
GROUP BY department;
In this example we've aliased the MAX(salary) field as "highest salary". Since there are spaces in this alias_name "highest salary" must be enclosed in quotes.
When you create an alias on a table it is either because you plan to list the same table name more than once in the FROM clause (ie: self join) or you want to shorten the table name to make the SQL statement shorter and easier to read.
Let's look at an example of how to alias a table name in MySQL.
For example:
SELECT p.product_id p.product_name suppliers.supplier_name
FROM products p
INNER JOIN suppliers
ON p.supplier_id = suppliers.supplier_id
ORDER BY p.product_name ASC suppliers.supplier_name DESC;
In this example we've created an alias for the products table called p. Now within this SQL statement we can refer to the products table as p.
When creating table aliases it is not necessary to create aliases for all of the tables listed in the FROM clause. You can choose to create aliases on any or all of the tables.
For example we could modify our example above and create an alias for the suppliers table as well.
SELECT p.product_id p.product_name s.supplier_name
FROM products p
INNER JOIN suppliers s
ON p.supplier_id = s.supplier_id
ORDER BY p.product_name ASC s.supplier_name DESC;
Now we have an alias for suppliers table called s as well as the alias for the products table called p.
This MySQL tutorial explains how to use the MySQL DISTINCT clause with syntax and examples.
The MySQL DISTINCT clause is used to remove duplicates from the result set. The DISTINCT clause can only be used with SELECT statements.
The syntax for the DISTINCT clause in MySQL is:
SELECT DISTINCT expressions
FROM tables
WHERE conditions ;
expressions The columns or calculations that you wish to retrieve. tables The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause. WHERE conditions Optional. The conditions that must be met for the records to be selected.
- When only one expression is provided in the DISTINCT clause the query will return the unique values for that expression.
- When more than one expression is provided in the DISTINCT clause the query will retrieve unique combinations for the expressions listed.
- In MySQL the DISTINCT clause doesn't ignore NULL values. So when using the DISTINCT clause in your SQL statement your result set will include NULL as a distinct value.
Let's look at the simplest MySQL DISTINCT clause example. We can use the MySQL DISTINCT clause to return a single field that removes the duplicates from the result set.
For example:
SELECT DISTINCT state
FROM customers;
This MySQL DISTINCT example would return all unique state values from the customers table.
Let's look at how you might use the MySQL DISTINCT clause to remove duplicates from more than one field in your SELECT statement.
For example:
SELECT DISTINCT city state
FROM customers;
This MySQL DISTINCT clause example would return each unique city and state combination from the customers table. In this case the DISTINCT applies to each field listed after the DISTINCT keyword and therefore returns distinct combinations.
This MySQL tutorial explains how to use the MySQL FROM clause with syntax and examples.
The MySQL FROM clause is used to list the tables and any joins required for the query in MySQL.
The syntax for the FROM Clause in MySQL is:
FROM table1
{ INNER JOIN
| LEFT OUTER JOIN
| RIGHT OUTER JOIN } table2
ON table1.column1 = table2.column1
table1 and table2
The tables used in the MySQL statement. The two tables are joined based on table1.column1 = table2.column1
.
- When using the FROM clause in a MySQL statement there must be at least one table listed in the FROM clause.
- If there are two or more tables listed in the MySQL FROM clause these tables are generally joined using INNER or OUTER joins as opposed to the older syntax in the WHERE clause.
It is difficult to explain the syntax for the MySQL FROM clause so let's look at some examples.
We'll start by looking at how to use the FROM clause with only a single table.
For example:
SELECT \*
FROM order_details
WHERE quantity >= 10
ORDER BY quantity DESC;
In this MySQL FROM clause example we've used the FROM clause to list the table called order_details. There are no joins performed since we are only using one table.
Let's look at how to use the FROM clause with two tables and an INNER JOIN.
For example:
SELECT order_details.order_id customers.customer_name
FROM customers
INNER JOIN order_details
ON customers.customer_id = order_details.customer_id
ORDER BY order_id;
This MySQL FROM clause example uses the FROM clause to list two tables - customers and order_details. And we are using the FROM clause to specify an INNER JOIN between the customers and order_details tables based on the customer_id column in both tables.
Let's look at how to use the FROM clause when we join two tables together using an OUTER JOIN. In this case we will look at the LEFT OUTER JOIN.
For example:
SELECT products.product_id inventory.qty_on_hand
FROM products
LEFT OUTER JOIN inventory
ON products.product_id = inventory.product_id
WHERE products.product_name = 'Database Software';
This MySQL FROM clause example uses the FROM clause to list two tables - products and inventory. And we are using the FROM clause to specify a LEFT OUTER JOIN between the products and inventory tables based on the product_id columns in both tables.
This MySQL tutorial explains how to use the MySQL WHERE clause with syntax and examples.
The MySQL WHERE clause is used to filter the results from a SELECT INSERT UPDATE or DELETE statement.
The syntax for the WHERE Clause in MySQL is:
WHERE conditions;
conditions The conditions that must be met for records to be selected.
It is difficult to explain the syntax for the MySQL WHERE clause so let's look at some examples.
SELECT \*
FROM contacts
WHERE last_name = 'Johnson';
In this MySQL WHERE clause example we've used the WHERE clause to filter our results from the contacts table. The SELECT statement above would return all rows from the contacts table where the last_name is Johnson. Because the * is used in the SELECT all fields from the contacts table would appear in the result set.
SELECT \*
FROM suppliers
WHERE state = 'Florida'
AND supplier_id > 1000;
This MySQL WHERE clause example uses the WHERE clause to define multiple conditions. In this case this SELECT statement uses the AND Condition to return all suppliers that are located in the state of Florida and whose supplier_id is greater than 1000.
SELECT supplier_id
FROM suppliers
WHERE supplier_name = 'Apple'
OR supplier_name = 'Microsoft';
This MySQL WHERE clause example uses the WHERE clause to define multiple conditions but instead of using the AND Condition it uses the OR Condition. In this case this SELECT statement would return all supplier_id values where the supplier_name is Apple or Microsoft.
SELECT \*
FROM suppliers
WHERE (state = 'Florida' AND supplier_name = 'IBM')
OR (supplier_id > 5000);
This MySQL WHERE clause example uses the WHERE clause to define multiple conditions but it combines the AND Condition and the OR Condition. This example would return all suppliers that reside in the state of Florida and whose supplier_name is IBM as well as all suppliers whose supplier_id is greater than 5000.
The parentheses determine the order that the AND and OR conditions are evaluated. Just like you learned in the order of operations in Math class!
SELECT suppliers.suppler_name orders.order_id
FROM suppliers orders
WHERE suppliers.supplier_id = orders.supplier_id
AND suppliers.state = 'California';
This MySQL WHERE clause example uses the WHERE clause to join multiple tables together in a single SELECT statement. This SELECT statement would return all supplier_name and order_id values where there is a matching record in the suppliers and orders tables based on supplier_id and where the supplier's state is California.
Learn more about MySQL joins.
This MySQL tutorial explains how to use the MySQL ORDER BY clause with syntax and examples.
The MySQL ORDER BY clause is used to sort the records in your result set.
The syntax for the ORDER BY clause in MySQL is:
SELECT expressions
FROM tables
WHERE conditions
ORDER BY expression ASC | DESC ;
expressions The columns or calculations that you wish to retrieve. tables The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause. WHERE conditions Optional. The conditions that must be met for the records to be selected. ASC Optional. It sorts the result set in ascending order by expression (default if no modifier is provider). DESC Optional. It sorts the result set in descending order by expression.
- If the ASC or DESC modifier is not provided in the ORDER BY clause the results will be sorted by expression in ascending order. This is equivalent to
ORDER BY *expression* ASC
. - The ORDER BY clause can be used in a SELECT statement SELECT LIMIT statement and DELETE LIMIT statement in MySQL.
The MySQL ORDER BY clause can be used without specifying the ASC or DESC modifier. When this attribute is omitted from the ORDER BY clause the sort order is defaulted to ASC or ascending order.
For example:
SELECT city
FROM customers
WHERE customer_name = 'Apple'
ORDER BY city;
This MySQL ORDER BY example would return all records sorted by the city field in ascending order and would be equivalent to the following ORDER BY clause:
SELECT city
FROM customers
WHERE customer_name = 'Apple'
ORDER BY city ASC;
Most programmers omit the ASC attribute if sorting in ascending order.
When sorting your result set in descending order you use the DESC attribute in your ORDER BY clause as follows:
SELECT last_name first_name city
FROM contacts
WHERE last_name = 'Johnson'
ORDER BY city DESC;
This MySQL ORDER BY example would return all records sorted by the city field in descending order.
You can also use the MySQL ORDER BY clause to sort by relative position in the result set where the first field in the result set is 1. The next field is 2 and so on.
For example:
SELECT last_name first_name city
FROM contacts
WHERE last_name = 'Johnson'
ORDER BY 3 DESC;
This MySQL ORDER BY would return all records sorted by the city field in descending order since the city field is in position #3 in the result set and would be equivalent to the following ORDER BY clause:
SELECT last_name first_name city
FROM contacts
WHERE last_name = 'Johnson'
ORDER BY city DESC;
When sorting your result set using the MySQL ORDER BY clause you can use the ASC and DESC attributes in a single SELECT statement.
For example:
SELECT supplier_city supplier_state
FROM suppliers
WHERE supplier_name = 'Microsoft'
ORDER BY supplier_city DESC supplier_state ASC;
This MySQL ORDER BY would return all records sorted by the supplier_city field in descending order with a secondary sort by supplier_state in ascending order.
This MySQL tutorial explains how to use the MySQL GROUP BY clause with syntax and examples.
The MySQL GROUP BY clause is used in a SELECT statement to collect data across multiple records and group the results by one or more columns.
The syntax for the GROUP BY clause in MySQL is:
SELECT expression1 expression2 ... expression_n
aggregate_function (expression)
FROM tables
WHERE conditions
GROUP BY expression1 expression2 ... expression_n;
expression1 expression2 ... expression_n The expressions that are not encapsulated within an aggregate function and must be included in the GROUP BY clause. aggregate_function A function such as SUM COUNT MIN MAX or AVG functions. tables The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause. WHERE conditions Optional. The conditions that must be met for the records to be selected.
Let's look at a MySQL GROUP BY query example that uses the SUM function.
This MySQL GROUP BY example uses the SUM function to return the name of the product and the total quantity (for the product).
SELECT product SUM(quantity) AS "Total quantity"
FROM order_details
GROUP BY product;
Because you have listed one column (the product field) in your SELECT statement that is not encapsulated in the SUM function you must use the GROUP BY Clause. The product field must therefore be listed in the GROUP BY clause.
Let's look at how we could use the GROUP BY clause with the COUNT function in MySQL.
This GROUP BY example uses the COUNT function to return the product and the number of orders (for that product) that are in the produce category.
SELECT product COUNT(\*) AS "Number of orders"
FROM order_details
WHERE category = 'produce'
GROUP BY product;
Let's next look at how we could use the GROUP BY clause with the MIN function in MySQL.
This GROUP BY example uses the MIN function to return the name of each department and the minimum salary in the department.
SELECT department MIN(salary) AS "Lowest salary"
FROM employees
GROUP BY department;
Finally let's look at how we could use the GROUP BY clause with the MAX function in MySQL.
This GROUP BY example uses the MAX function to return the name of each department and the maximum salary in the department.
SELECT department MAX(salary) AS "Highest salary"
FROM employees
GROUP BY department;
This MySQL tutorial explains how to use the MySQL HAVING clause with syntax and examples.
The MySQL HAVING clause is used in combination with the GROUP BY clause to restrict the groups of returned rows to only those whose the condition is TRUE.
The syntax for the HAVING Clause in MySQL is:
SELECT expression1 expression2 ... expression_n
aggregate_function (expression)
FROM tables
WHERE conditions
GROUP BY expression1 expression2 ... expression_n
HAVING condition;
aggregate_function A function such as SUM COUNT MIN MAX or AVG functions. expression1 expression2 ... expression_n The expressions that are not encapsulated within an aggregate function and must be included in the GROUP BY clause. WHERE conditions Optional. These are the conditions for the records to be selected. HAVING condition This is a further condition applied only to the aggregated results to restrict the groups of returned rows. Only those groups whose condition evaluates to TRUE will be included in the result set.
Let's look at a MySQL HAVING clause example that uses the SUM function.
You could also use the SUM function to return the name of the product and the total quantity (for that product). The MySQL HAVING clause will filter the results so that only products with a total quantity greater than 10 will be returned.
SELECT product SUM(quantity) AS "Total quantity"
FROM order_details
GROUP BY product
HAVING SUM(quantity) > 10;
Let's look at how we could use the HAVING clause with the COUNT function in MySQL.
You could use the COUNT function to return the name of the product and the number of orders (for that product) that are in the 'produce' category. The MySQL HAVING clause will filter the results so that only products with more than 20 orders will be returned.
SELECT product COUNT(\*) AS "Number of orders"
FROM order_details
WHERE category = 'produce'
GROUP BY product
HAVING COUNT(\*) > 20;
Let's next look at how we could use the HAVING clause with the MIN function in MySQL.
You could also use the MIN function to return the name of each department and the minimum salary in the department. The MySQL HAVING clause will return only those departments where the minimum salary is less than $50 000.
SELECT department MIN(salary) AS "Lowest salary"
FROM employees
GROUP BY department
HAVING MIN(salary) < 50000;
Finally let's look at how we could use the HAVING clause with the MAX function in MySQL. For example you could also use the MAX function to return the name of each department and the maximum salary in the department. The MySQL HAVING clause will return only those departments whose maximum salary is greater than $25 000.
SELECT department MAX(salary) AS "Highest salary"
FROM employees
GROUP BY department
HAVING MAX(salary) > 25000;
This MySQL tutorial explains how to use the MySQL COUNT function with syntax and examples.
The MySQL COUNT function returns the count of an expression.
The syntax for the COUNT function in MySQL is:
SELECT COUNT(aggregate_expression)
FROM tables
WHERE conditions ;
OR the syntax for the COUNT function when grouping the results by one or more columns is:
SELECT expression1 expression2 ... expression_n
COUNT(aggregate_expression)
FROM tables
WHERE conditions
GROUP BY expression1 expression2 ... expression_n;
expression1 expression2 ... expression_n Expressions that are not encapsulated within the COUNT function and must be included in the GROUP BY clause at the end of the SQL statement. aggregate_expression This is the column or expression whose non-null values will be counted. tables The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause. WHERE conditions Optional. These are conditions that must be met for the records to be selected.
Not everyone realizes this but the COUNT function will only include the records in the count where the value of expression in COUNT(expression) is NOT NULL. When expression contains a NULL value it is not included in the COUNT calculations.
Let's look at a COUNT function example that demonstrates how NULL values are evaluated by the COUNT function.
For example if you have the following table called suppliers:
supplier_id | supplier_name | state |
---|---|---|
1 | IBM | CA |
2 | Microsoft | |
3 | NVIDIA |
And if you ran the following SELECT statement that uses the COUNT function:
SELECT COUNT(supplier_id)
FROM suppliers;
*Result:* 3
This COUNT example will return 3 since all supplier_id values in the query's result set are NOT NULL.
However if you ran the next SELECT statement that uses the COUNT function:
SELECT COUNT(state)
FROM suppliers;
*Result:* 1
This COUNT example will only return 1 since only one state value in the query's result set is NOT NULL. That would be the first row where the state = 'CA'. It is the only row that is included in the COUNT function calculation.
The COUNT function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL COUNT function examples and explore how to use the COUNT function in MySQL.
For example you might wish to know how many employees have a salary above $75 000 / year.
SELECT COUNT(\*) AS "Number of employees"
FROM employees
WHERE salary > 75000;
In this COUNT function example we've aliased the COUNT(*) expression as "Number of employees". As a result "Number of employees" will display as the field name when the result set is returned.
You can use the DISTINCT clause within the COUNT function. For example the SQL statement below returns the number of unique departments where at least one employee makes over $55 000 / year.
SELECT COUNT(DISTINCT department) AS "Unique departments"
FROM employees
WHERE salary > 55000;
Again the COUNT(DISTINCT department) field is aliased as "Unique departments". This is the field name that will display in the result set.
In some cases you will be required to use the GROUP BY clause with the COUNT function.
For example you could also use the COUNT function to return the name of the department and the number of employees (in the associated department) that are in the state of 'CA'.
SELECT department COUNT(\*) AS "Number of employees"
FROM employees
WHERE state = 'CA'
GROUP BY department;
Because you have listed one column in your SELECT statement that is not encapsulated in the COUNT function you must use a GROUP BY clause. The department field must therefore be listed in the GROUP BY section.
This MySQL tutorial explains how to use the MySQL SUM function with syntax and examples.
The MySQL SUM function returns the summed value of an expression.
The syntax for the SUM function in MySQL is:
SELECT SUM(aggregate_expression)
FROM tables
WHERE conditions ;
OR the syntax for the SUM function when grouping the results by one or more columns is:
SELECT expression1 expression2 ... expression_n
SUM(aggregate_expression)
FROM tables
WHERE conditions
GROUP BY expression1 expression2 ... expression_n;
expression1 expression2 ... expression_n Expressions that are not encapsulated within the SUM function and must be included in the GROUP BY clause at the end of the SQL statement. aggregate_expression This is the column or expression that will be summed. tables The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause. WHERE conditions Optional. These are conditions that must be met for the records to be selected.
The SUM function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL SUM function examples and explore how to use the SUM function in MySQL.
For example you might wish to know how the combined total salary of all employees whose salary is above $50 000 / year.
SELECT SUM(salary) AS "Total Salary"
FROM employees
WHERE salary > 50000;
In this SUM function example we've aliased the SUM(salary) expression as "Total Salary". As a result "Total Salary" will display as the field name when the result set is returned.
You can use the DISTINCT clause within the SUM function. For example the SQL statement below returns the combined total salary of unique salary values where the salary is above $50 000 / year.
SELECT SUM(DISTINCT salary) AS "Total Salary"
FROM employees
WHERE salary > 50000;
If there were two salaries of $82 000/year only one of these values would be used in the SUM function.
The expression contained within the SUM function does not need to be a single field. You could also use a formula. For example you might want to calculate the total commission.
SELECT SUM(sales \* 0.05) AS "Total Commission"
FROM orders;
In some cases you will be required to use the GROUP BY clause with the SUM function.
For example you could also use the SUM function to return the name of the department and the total sales (in the associated department).
SELECT department SUM(sales) AS "Total sales"
FROM order_details
GROUP BY department;
Because you have listed one column in your SELECT statement that is not encapsulated in the SUM function you must use a GROUP BY clause. The department field must therefore be listed in the GROUP BY section.
This MySQL tutorial explains how to use the MySQL MIN function with syntax and examples.
The MySQL MIN function returns the minimum value of an expression.
The syntax for the MIN function in MySQL is:
SELECT MIN(aggregate_expression)
FROM tables
WHERE conditions ;
OR the syntax for the MIN function when grouping the results by one or more columns is:
SELECT expression1 expression2 ... expression_n
MIN(aggregate_expression)
FROM tables
WHERE conditions
GROUP BY expression1 expression2 ... expression_n;
expression1 expression2 ... expression_n Expressions that are not encapsulated within the MIN function and must be included in the GROUP BY clause at the end of the SQL statement. aggregate_expression This is the column or expression from which the minimum value will be returned. tables The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause. WHERE conditions Optional. These are conditions that must be met for the records to be selected.
The MIN function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL MIN function examples and explore how to use the MIN function in MySQL.
For example you might wish to know how the minimum salary of all employees.
SELECT MIN(salary) AS "Lowest Salary"
FROM employees;
In this MIN function example we've aliased the MIN(salary) expression as "Lowest Salary". As a result "Lowest Salary" will display as the field name when the result set is returned.
In some cases you will be required to use the GROUP BY clause with the MIN function.
For example you could also use the MIN function to return the name of the department and the minimum salary in the department.
SELECT department MIN(salary) AS "Lowest salary"
FROM employees
GROUP BY department;
Because you have listed one column in your SELECT statement that is not encapsulated in the MIN function you must use a GROUP BY clause. The department field must therefore be listed in the GROUP BY section.
This MySQL tutorial explains how to use the MySQL MAX function with syntax and examples.
The MySQL MAX function returns the maximum value of an expression.
The syntax for the MAX function in MySQL is:
SELECT MAX(aggregate_expression)
FROM tables
WHERE conditions ;
OR the syntax for the MAX function when grouping the results by one or more columns is:
SELECT expression1 expression2 ... expression_n
MAX(aggregate_expression)
FROM tables
WHERE conditions
GROUP BY expression1 expression2 ... expression_n;
expression1 expression2 ... expression_n Expressions that are not encapsulated within the MAX function and must be included in the GROUP BY clause at the end of the SQL statement. aggregate_expression This is the column or expression from which the maximum value will be returned. tables The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause. WHERE conditions Optional. These are conditions that must be met for the records to be selected.
The MAX function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL MAX function examples and explore how to use the MAX function in MySQL.
For example you might wish to know how the maximum salary of all employees.
SELECT MAX(salary) AS "Highest Salary"
FROM employees;
In this MAX function example we've aliased the MAX(salary) expression as "Highest Salary". As a result "Highest Salary" will display as the field name when the result set is returned.
In some cases you will be required to use the GROUP BY clause with the MAX function.
For example you could also use the MAX function to return the name of the department and the maximum salary in the department.
SELECT department MAX(salary) AS "Highest salary"
FROM employees
GROUP BY department;
Because you have listed one column in your SELECT statement that is not encapsulated in the MAX function you must use a GROUP BY clause. The department field must therefore be listed in the GROUP BY section.
This MySQL tutorial explains how to use the MySQL AVG function with syntax and examples.
The MySQL AVG function returns the average value of an expression.
The syntax for the AVG function in MySQL is:
SELECT AVG(aggregate_expression)
FROM tables
WHERE conditions ;
OR the syntax for the AVG function when grouping the results by one or more columns is:
SELECT expression1 expression2 ... expression_n
AVG(aggregate_expression)
FROM tables
WHERE conditions
GROUP BY expression1 expression2 ... expression_n;
expression1 expression2 ... expression_n Expressions that are not encapsulated within the AVG function and must be included in the GROUP BY clause at the end of the SQL statement. aggregate_expression This is the column or expression that will be averaged. tables The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause. WHERE conditions Optional. These are conditions that must be met for the records to be selected.
The AVG function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL AVG function examples and explore how to use the AVG function in MySQL.
For example you might wish to know how the average salary of all employees whose salary is above $25 000 / year.
SELECT AVG(salary) AS "Avg Salary"
FROM employees
WHERE salary > 25000;
In this AVG function example we've aliased the AVG(salary) expression as "Avg Salary". As a result "Avg Salary" will display as the field name when the result set is returned.
You can use the DISTINCT clause within the AVG function. For example the SQL statement below returns the average salary of unique salary values where the salary is above $25 000 / year.
SELECT AVG(DISTINCT salary) AS "Avg Salary"
FROM employees
WHERE salary > 25000;
If there were two salaries of $30 000/year only one of these values would be used in the AVG function.
The expression contained within the AVG function does not need to be a single field. You could also use a formula. For example you might want the average commission.
SELECT AVG(sales \* 0.10) AS "Average Commission"
FROM orders;
You could also use the AVG function to return the name of the department and the average sales (in the associated department). For example
SELECT department AVG(sales) AS "Avg sales"
FROM order_details
GROUP BY department;
Because you have listed one column in your SELECT statement that is not encapsulated in the AVG function you must use a GROUP BY clause. The department field must therefore be listed in the GROUP BY section.
This MySQL tutorial explains how to use the MySQL AND condition with syntax and examples.
The MySQL AND Condition (also called the AND Operator) is used to test two or more conditions in a SELECT INSERT UPDATE or DELETE statement.
The syntax for the AND Condition in MySQL is:
WHERE condition1
AND condition2
...
AND condition_n;
condition1 condition2 ... condition_n All of the conditions that must be met for the records to be selected.
- The MySQL AND condition allows you to test 2 or more conditions.
- The MySQL AND condition requires that all of the conditions (ie: condition1 condition2 condition_n) must be met for the record to be included in the result set.
Let's look at some examples that show how to use the AND condition in MySQL.
The first MySQL AND condition query involves a SELECT statement with 2 conditions.
For example:
SELECT \*
FROM contacts
WHERE state = 'California'
AND contact_id > 3000;
This MySQL AND example would return all contacts that reside in the state of California and have a customer_id greater than 3000. Because the * is used in the SELECT statement all fields from the contacts table would appear in the result set.
Our next MySQL AND example shows how the AND condition can be used to join multiple tables in a SELECT statement.
For example:
SELECT orders.order_id suppliers.supplier_name
FROM suppliers orders
WHERE suppliers.supplier_id = orders.supplier_id
AND suppliers.supplier_name = 'Dell';
Though the above SQL works just fine you would more traditionally write this SQL as follows using a proper INNER JOIN.
For example:
SELECT orders.order_id suppliers.supplier_name
FROM suppliers
INNER JOIN orders
ON suppliers.supplier_id = orders.supplier_id
WHERE suppliers.supplier_name = 'Dell';
This MySQL AND condition example would return all rows where the supplier_name is Dell. And the suppliers and orders tables are joined on supplier_id. You will notice that all of the fields are prefixed with the table names (ie: orders.order_id). This is required to eliminate any ambiguity as to which field is being referenced; as the same field name can exist in both the suppliers and the orders tables.
In this case the result set would only display the order_id and supplier_name fields (as listed in the first part of the SELECT statement.).
This next MySQL AND example demonstrates how the AND condition can be used in the INSERT statement.
For example:
INSERT INTO suppliers
(supplier_id supplier_name)
SELECT customer_id customer_name
FROM customers
WHERE customer_name = 'Oracle'
AND customer_id < 2500;
This MySQL AND condition example would insert into the suppliers table all customer_id and customer_name records from the customers table whose customer_name is Oracle and have a customer_id less than 2500.
This MySQL AND condition example shows how the AND condition can be used in the UPDATE statement.
For example:
UPDATE suppliers
SET supplier_name = 'Cisco'
WHERE supplier_name = 'Sun Microsystems'
AND offices = 10;
This MySQL AND condition example would update all supplier_name values in the suppliers table to Cisco where the supplier_name was Sun Microsystems and had 10 offices.
Finally this last MySQL AND example demonstrates how the AND condition can be used in the DELETE statement.
For example:
DELETE FROM suppliers
WHERE supplier_name = 'Gateway'
AND product = 'computers';
This MySQL AND condition example would delete all records from the suppliers table whose supplier_name was Gateway and product was computers.
Learn more about joining tables in MySQL.
This MySQL tutorial explains how to use the MySQL OR condition with syntax and examples.
The MySQL OR Condition is used to test two or more conditions where records are returned when any one of the conditions are met. It can be used in a SELECT INSERT UPDATE or DELETE statement.
The syntax for the OR Condition in MySQL is:
WHERE condition1
OR condition2
...
OR condition_n;
condition1 condition2 ... condition_n Any of the conditions that must be met for the records to be selected.
- The MySQL OR condition allows you to test 2 or more conditions.
- The MySQL OR condition requires that any of the conditions (ie: condition1 condition2 condition_n) must be met for the record to be included in the result set.
The first MySQL OR condition example that we'll take a look at involves a SELECT statement with 2 conditions:
SELECT \*
FROM contacts
WHERE state = 'California'
OR contact_id < 1000;
This MySQL OR condition example would return all customers that reside in either the state of California or have a contact_id less than 1000. Because the * is used in the SELECT statement all fields from the contacts table would appear in the result set.
The next MySQL OR example looks at a SELECT statement with 3 conditions. If any of these conditions is met the record will be included in the result set.
SELECT supplier_id supplier_name
FROM suppliers
WHERE supplier_name = 'Microsoft'
OR state = 'Florida'
OR offices > 10;
This MySQL OR condition example would return all supplier_id and supplier_name values where the supplier_name is either Microsoft the state is Florida or offices is greater than 10.
The MySQL OR condition can be used in the INSERT statement.
For example:
INSERT INTO suppliers
(supplier_id supplier_name)
SELECT customer_id customer_name
FROM customers
WHERE state = 'Florida'
OR state = 'California';
This MySQL OR example would insert into the suppliers table all customer_id and customer_name records from the customers table that reside in the state of Florida or California.
The MySQL OR condition can be used in the UPDATE statement.
For example:
UPDATE suppliers
SET supplier_name = 'Apple'
WHERE supplier_name = 'RIM'
OR available_products > 25;
This MySQL OR condition example would update all supplier_name values in the suppliers table to Apple where the supplier_name was RIM or its available_products was greater than 25.
The MySQL OR condition can be used in the DELETE statement.
For example:
DELETE FROM customers
WHERE last_name = 'Johnson'
OR first_name = 'Joe';
This MySQL OR condition example would delete all customers from the customers table whose last_name was Johnson or first_name was Joe.
This MySQL tutorial explains how to use the AND condition and the OR condition together in a MySQL query with syntax and examples.
The MySQL AND condition and OR condition can be combined in a SELECT INSERT UPDATE or DELETE statement.
When combining these conditions it is important to use parentheses so that the database knows what order to evaluate each condition. (Just like when you were learning the order of operations in Math class!)
The syntax for the AND condition and OR condition together in MySQL is:
WHERE condition1
AND condition2
...
OR condition_n;
condition1 condition2 ... condition_n The conditions that are evaluated to determine if the records will be selected.
- The MySQL AND & OR conditions allow you to test multiple conditions.
- Don't forget the order of operation parentheses!
Let's look at an example that combines the AND and OR conditions in a SELECT statement.
For example:
SELECT \*
FROM customers
WHERE (state = 'California' AND last_name = 'Johnson')
OR (customer_id > 4500);
This AND & OR example would return all suppliers that reside in the state of California whose last_name is Johnson and all suppliers whose customer_id is greater than 4500. The parentheses determine the order that the AND and OR conditions are evaluated. Just like you learned in the order of operations in Math class!
The next example takes a look at a more complex statement.
For example:
SELECT customer_id last_name first_name
FROM customers
WHERE (last_name = 'Johnson')
OR (last_name = 'Anderson' AND state = 'California')
OR (last_name = 'Smith' AND status = 'Active' AND state = 'Florida');
This AND & OR example would return all customer_id last_name and first_name values from the customers table whose the last_name is Johnson OR whose last_name is Anderson and the state is California OR whose last_name is Smith the status is Active and the state is Florida.
This next AND & OR example demonstrates how the AND condition and OR condition can be combined in the INSERT statement.
For example:
INSERT INTO suppliers
(supplier_id supplier_name)
SELECT customer_id customer_name
FROM customers
WHERE (customer_name = 'Apple' OR customer_name = 'Samsung')
AND customer_id >= 100;
This MySQL AND and OR example would insert into the suppliers table all customer_id and customer_name records from the customers table whose customer_name is either Apple or Samsung and where the customer_id is greater than or equal to 100.
This AND & OR example shows how the AND and OR conditions can be used in the UPDATE statement.
For example:
UPDATE contacts
SET last_name = 'Johnson'
WHERE last_name = 'Anderson'
AND (state = 'Florida' OR state = 'California');
This MySQL AND & OR condition example would update all last_name values in the contacts table to Johnson where the last_name was Anderson and resides in either the state of Florida or 'California'.
Finally this last AND & OR example demonstrates how the AND and OR conditions can be used in the DELETE statement.
For example:
DELETE FROM contacts
WHERE state = 'California'
AND (last_name = 'Smith' OR last_name = 'Anderson');
This MySQL AND and OR condition example would delete all records from the contacts table whose state is California and last_name was either Smith or Anderson.
This MySQL tutorial explains how to use the MySQL LIKE condition to perform pattern matching with syntax and examples.
The MySQL LIKE condition allows wildcards to be used in the WHERE clause of a SELECT INSERT UPDATE or DELETE statement. This allows you to perform pattern matching.
The syntax for the LIKE Condition in MySQL is:
expression LIKE pattern ESCAPE 'escape_character'
expression A character expression such as a column or field. pattern A character expression that contains pattern matching. The patterns that you can choose from are:
Wildcard | Explanation |
---|---|
% | Allows you to match any string of any length (including zero length) |
_ | Allows you to match on a single character |
escape_character Optional. It allows you to test for literal instances of a wildcard character such as % or _. If you do not provide the escape_character MySQL assumes that "" is the escape_character.
The first MySQL LIKE example that we will look at involves using the % wildcard (percent sign wildcard).
Let's explain how the % wildcard works in the MySQL LIKE condition. We want to find all of the customers whose last_name begins with 'Sm'.
SELECT customer_name
FROM customers
WHERE last_name LIKE 'Sm%';
You can also using the % wildcard multiple times within the same string. For example
SELECT customer_name
FROM customers
WHERE last_name LIKE '%it%';
In this MySQL LIKE condition example we are looking for all customers whose last_name contains the characters 'it'.
Next let's explain how the _ wildcard (underscore wildcard) works in the MySQL LIKE condition. Remember that _ wildcard is looking for only one character.
For example:
SELECT supplier_name
FROM suppliers
WHERE supplier_name LIKE 'Sm_th';
This MySQL LIKE condition example would return all suppliers whose supplier_name is 5 characters long where the first two characters are 'Sm' and the last two characters are 'th'. For example it could return suppliers whose supplier_name is 'Smith' 'Smyth' 'Smath' 'Smeth' etc.
Here is another example:
SELECT \*
FROM suppliers
WHERE account_number LIKE '12345_';
You might find that you are looking for an account number but you only have 5 of the 6 digits. The example above would retrieve potentially 10 records back (where the missing value could equal anything from 0 to 9). For example it could return suppliers whose account numbers are:
123450 123451 123452 123453 123454 123455 123456 123457 123458 123459
Next let's look at how you would use the NOT Operator with wildcards.
Let's use the % wilcard with the NOT Operator. You could also use the MySQL LIKE condition to find suppliers whose name does not start with 'G'.
For example:
SELECT supplier_name
FROM suppliers
WHERE supplier_name NOT LIKE 'G%';
By placing the NOT Operator in front of the MySQL LIKE condition you are able to retrieve all suppliers whose supplier_name does not start with 'G'.
It is important to understand how to "Escape Characters" when pattern matching. These examples deal specifically with escaping characters in MySQL.
Let's say you wanted to search for a % or a _ character in the MySQL LIKE condition. You can do this using an Escape character.
Please note that you can only define an escape character as a single character (length of 1).
For example:
SELECT \*
FROM suppliers
WHERE supplier_name LIKE 'G\%';
Since we didn't specify an escape character MySQL assumes that the "" is the escape character. MySQL then assumes that the escape character is "" which results in MySQL treating the % character as a literal instead of a wildcard. This statement would then return all suppliers whose supplier_name is G%.
We can override the default escape character in MySQL by providing the ESCAPE modifier as follows:
SELECT \*
FROM suppliers
WHERE supplier_name LIKE 'G!%' ESCAPE '!';
This MySQL LIKE condition example identifies the ! character as an escape character. The ! escape character would result in MySQL treating the % character as a literal. As a result this statement will also return all suppliers whose supplier_name is G%.
Here is another more complicated example using escape characters in the MySQL LIKE condition.
SELECT \*
FROM suppliers
WHERE supplier_name LIKE 'H%\%';
This MySQL LIKE condition example returns all suppliers whose name starts with H and ends in %. For example it would return a value such as 'Hello%'. Since we did not specify an escape character in the LIKE condition MySQL assumes that the escape character is "" which results in MySQL treating the second % character as a literal instead of a wildcard.
We could modify this LIKE condition by specfying an escape character as follows:
SELECT \*
FROM suppliers
WHERE supplier_name LIKE 'H%!%' ESCAPE '!';
This MySQL LIKE condition example returns all suppliers whose name starts with H and ends in the literal %. For example it would return a value such as 'Hello%'.
You can also use the escape character with the _ character in the MySQL LIKE condition.
For example:
SELECT \*
FROM suppliers
WHERE supplier_name LIKE 'H%\_';
Again since no ESCAPE modifier is provided MySQL uses "" as the escape character resulting in the _ character to be treated as a literal instead of a wildcard. This example would then return all suppliers whose supplier_name starts with H and ends in . For example it would return a value such as 'Hello'.
This MySQL tutorial explains how to use the MySQL IN condition with syntax and examples.
The MySQL IN condition is used to help reduce the need to use multiple OR conditions in a SELECT INSERT UPDATE or DELETE statement.
The syntax for the IN condition in MySQL is:
expression IN (value1 value2 .... value_n);
OR
expression IN (subquery);
expression The value to test. value1 value2 ... or value_n These are the values to test against expression. If any of these values matches expression then the IN condition will evaluate to true. This is a quick method to test if any one of the values matches expression. subquery This is a SELECT statement whose result set will be tested against expression. If any of these values matches expression then the IN condition will evaluate to true.
- The MySQL IN condition will return the records where expression is value1 value2... or value_n.
- The MySQL IN condition is also called the MySQL IN operator.
Let's look at a MySQL IN condition example using character values.
The following is a MySQL SELECT statement that uses the IN condition to compare character values:
SELECT \*
FROM contacts
WHERE last_name IN ('Johnson' 'Anderson' 'Smith');
This MySQL IN condition example would return all rows from the contacts table where the last_name is either Johnson Anderson or Smith. Because the * is used in the SELECT all fields from the contacts table would appear in the result set.
The above IN example is equivalent to the following SELECT statement:
SELECT \*
FROM contacts
WHERE last_name = 'Johnson'
OR last_name = 'Anderson'
OR last_name = 'Smith';
As you can see using the MySQL IN condition makes the statement easier to read and more efficient.
Next let's look at a MySQL IN condition example using numeric values.
For example:
SELECT \*
FROM suppliers
WHERE supplier_id IN (200 201 203 300);
This MySQL IN condition example would return all suppliers where the supplier_id is either 200 201 203 or 300.
The above IN example is equivalent to the following SELECT statement:
SELECT \*
FROM suppliers
WHERE supplier_id = 200
OR supplier_id = 201
OR supplier_id = 203
OR supplier_id = 300;
Finally let's look at an IN condition example using the NOT operator.
For example:
SELECT \*
FROM contacts
WHERE last_name NOT IN ('Johnson' 'Anderson' 'Smith');
This MySQL IN condition example would return all rows from the contacts table where the last_name is not Johnson Anderson or Smith. Sometimes it is more efficient to list the values that you do not want as opposed to the values that you do want.
This MySQL tutorial explains how to use the MySQL NOT condition with syntax and examples.
The MySQL NOT Condition (also called the NOT Operator) is used to negate a condition in a SELECT INSERT UPDATE or DELETE statement.
The syntax for the NOT Condition in MySQL is:
NOT condition
condition The condition to negate.
- The MySQL NOT condition requires that the opposite of the condition must be met for the record to be included in the result set.
The MySQL NOT condition can be combined with the IN Condition.
For example:
SELECT \*
FROM contacts
WHERE first_name NOT IN ('Joseph' 'Andrew' 'Brad');
This MySQL NOT example would return all rows from the contacts table where the first_name is not Joseph Andrew or Brad. Sometimes it is more efficient to list the values that you do not want as opposed to the values that you do want.
The MySQL NOT condition can also be combined with the IS NULL Condition.
For example
SELECT \*
FROM contacts
WHERE first_name IS NOT NULL;
This MySQL NOT example would return all records from the contacts table where the first_name does not contain a NULL value.
The MySQL NOT condition can also be combined with the LIKE Condition.
For example:
SELECT supplier_id supplier_name
FROM suppliers
WHERE supplier_name NOT LIKE 'P%';
By placing the MySQL NOT Operator in front of the LIKE condition you are able to retrieve all suppliers whose supplier_name does not start with 'P'.
The MySQL NOT condition can also be combined with the BETWEEN Condition. Here is an example of how you would combine the NOT Operator with the BETWEEN Condition.
For example:
SELECT \*
FROM orders
WHERE order_id NOT BETWEEN 300 AND 399;
This MySQL NOT example would return all rows where the order_id was NOT between 300 and 399 inclusive. It would be equivalent to the following SELECT statement:
SELECT \*
FROM orders
WHERE order_id < 300
OR order_id > 399;
The MySQL NOT condition can also be combined with the EXISTS Condition.
For example
SELECT \*
FROM suppliers
WHERE NOT EXISTS (SELECT \*
FROM orders
WHERE suppliers.supplier_id = orders.supplier_id);
This MySQL NOT example would return all records from the suppliers table where there are no records in the orders table for the given supplier_id.
This MySQL tutorial explains how to use the MySQL IS NULL condition with syntax and examples.
The MySQL IS NULL Condition is used to test for a NULL value in a SELECT INSERT UPDATE or DELETE statement.
The syntax for the IS NULL Condition in MySQL is:
expression IS NULL
expression The value to test if it is a NULL value.
- If expression is a NULL value the condition evaluates to TRUE.
- If expression is not a NULL value the condition evaluates to FALSE.
Let's look at an example of how to use MySQL IS NULL in a SELECT statement:
SELECT \*
FROM contacts
WHERE last_name IS NULL;
This MySQL IS NULL example will return all records from the contacts table where the last_name contains a NULL value.
Next let's look at an example of how to use MySQL IS NULL in an INSERT statement:
INSERT INTO contacts
(contact_id contact_name)
SELECT account_no supplier_name
FROM suppliers
WHERE category IS NULL;
This MySQL IS NULL example will insert records into the contacts table where the category contains a NULL value.
Next let's look at an example of how to use MySQL IS NULL in an UPDATE statement:
UPDATE contacts
SET last_name = 'TBD'
WHERE last_name IS NULL;
This MySQL IS NULL example will update records in the contacts table where the last_name contains a NULL value.
Next let's look at an example of how to use MySQL IS NULL in a DELETE statement:
DELETE FROM contacts
WHERE last_name IS NULL;
This MySQL IS NULL example will delete all records from the contacts table where the last_name contains a NULL value.
This MySQL tutorial explains how to use the MySQL IS NOT NULL condition with syntax and examples.
The MySQL IS NOT NULL condition is used to test for a NOT NULL value in a SELECT INSERT UPDATE or DELETE statement.
The syntax for the IS NOT NULL Condition in MySQL is:
expression IS NOT NULL
expression The value to test if it is a not NULL value.
- If expression is NOT a NULL value the condition evaluates to TRUE.
- If expression is a NULL value the condition evaluates to FALSE.
Here is an example of how to use the MySQL IS NOT NULL condition in a SELECT statement:
SELECT \*
FROM contacts
WHERE last_name IS NOT NULL;
This MySQL IS NOT NULL example will return all records from the contacts table where the last_name does not contain a null value.
Here is an example of how to use the MySQL IS NOT NULL condition in an INSERT statement:
INSERT INTO contacts
(contact_id contact_name)
SELECT account_no supplier_name
FROM suppliers
WHERE category IS NOT NULL;
This MySQL IS NOT NULL example will insert records into the contacts table where the category does not contain a null value.
Here is an example of how to use the MySQL IS NOT NULL condition in an UPDATE statement:
UPDATE contacts
SET status = 'completed'
WHERE last_name IS NOT NULL;
This MySQL IS NOT NULL example will update records in the contacts table where the last_name does not contain a null value.
Here is an example of how to use the MySQL IS NOT NULL condition in a DELETE statement:
DELETE FROM contacts
WHERE last_name IS NOT NULL;
This MySQL IS NOT NULL example will delete all records from the contacts table where the last_name does not contain a null value.
This MySQL tutorial explains how to use the MySQL BETWEEN condition with syntax and examples.
The MySQL BETWEEN Condition is used to retrieve values within a range in a SELECT INSERT UPDATE or DELETE statement.
The syntax for the BETWEEN Condition in MySQL is:
expression BETWEEN value1 AND value2;
expression A column or calculation. value1 and value2 These values create an inclusive range that expression is compared to.
- The MySQL BETWEEN Condition will return the records where expression is within the range of value1 and value2 (inclusive).
- When using the MySQL BETWEEN Condition with dates be sure to use the CAST function to explicitly convert the values to dates.
Let's look at some MySQL BETWEEN condition examples using numeric values. The following numeric example uses the BETWEEN condition to retrieve values within a numeric range.
For example:
SELECT \*
FROM contacts
WHERE contact_id BETWEEN 100 AND 200;
This MySQL BETWEEN example would return all rows from the contacts table where the contact_id is between 100 and 200 (inclusive). It is equivalent to the following SELECT statement:
SELECT \*
FROM contacts
WHERE contact_id >= 100
AND contact_id <= 200;
Next let's look at how you would use the MySQL BETWEEN condition with Dates. When using the BETWEEN condition in MySQL with dates be sure to use the CAST function to explicitly convert the values to dates.
The following date example uses the BETWEEN condition to retrieve values within a date range. Note that the order_date field is of type DATE and not of type DATETIME. (This is why we don't have to CAST the order_date field to a DATE type in the examples below.)
For example:
SELECT \*
FROM order_details
WHERE order_date BETWEEN CAST('2014-02-01' AS DATE) AND CAST('2014-02-28' AS DATE);
This MySQL BETWEEN condition example would return all records from the order_details table where the order_date is between Feb 1 2014 and Feb 28 2014 (inclusive). It would be equivalent to the following SELECT statement:
SELECT \*
FROM order_details
WHERE order_date >= CAST('2014-02-01' AS DATE)
AND order_date <= CAST('2014-02-28' AS DATE);
The MySQL BETWEEN condition can also be combined with the NOT operator. Here is an example of how you would combine the BETWEEN condition with the NOT Operator.
For example:
SELECT \*
FROM suppliers
WHERE supplier_id NOT BETWEEN 2000 AND 2999;
This MySQL BETWEEN example would return all rows from the suppliers table where the supplier_id was NOT between 2000 and 2999 inclusive. It would be equivalent to the following SELECT statement:
SELECT \*
FROM suppliers
WHERE supplier_id < 2000
OR supplier_id > 2999;
This MySQL tutorial explains how to use the MySQL EXISTS condition with syntax and examples.
The MySQL EXISTS condition is used in combination with a subquery and is considered "to be met" if the subquery returns at least one row. It can be used in a SELECT INSERT UPDATE or DELETE statement.
The syntax for the EXISTS condition in MySQL is:
WHERE EXISTS ( subquery );
subquery A SELECT statement that usually starts with SELECT * rather than a list of expressions or column names. MySQL ignores the list of expressions in the subquery anyways.
- SQL statements that use the EXISTS Condition in MySQL are very inefficient since the sub-query is RE-RUN for EVERY row in the outer query's table. There are more efficient ways to write most queries that do not use the EXISTS Condition.
Let's look at a simple example.
The following is a SELECT statement that uses the MySQL EXISTS condition:
SELECT \*
FROM customers
WHERE EXISTS (SELECT \*
FROM order_details
WHERE customers.customer_id = order_details.customer_id);
This MySQL EXISTS condition example will return all records from the customers table where there is at least one record in the order_details table with the matching customer_id.
The MySQL EXISTS condition can also be combined with the NOT operator.
For example
SELECT \*
FROM customers
WHERE NOT EXISTS (SELECT \*
FROM order_details
WHERE customers.customer_id = order_details.customer_id);
This MySQL EXISTS example will return all records from the customers table where there are no records in the order_details table for the given customer_id.
The following is an example of an INSERT statement that uses the MySQL EXISTS condition:
INSERT INTO contacts
(contact_id contact_name)
SELECT supplier_id supplier_name
FROM suppliers
WHERE EXISTS (SELECT \*
FROM orders
WHERE suppliers.supplier_id = orders.supplier_id);
The following is an example of an UPDATE statement that uses the MySQL EXISTS condition:
UPDATE suppliers
SET supplier_name = (SELECT customers.customer_name
FROM customers
WHERE customers.customer_id = suppliers.supplier_id)
WHERE EXISTS (SELECT \*
FROM customers
WHERE customers.customer_id = suppliers.supplier_id);
The following is an example of a DELETE statement that uses the MySQL EXISTS condition:
DELETE FROM suppliers
WHERE EXISTS (SELECT \*
FROM orders
WHERE suppliers.supplier_id = orders.supplier_id);
This MySQL tutorial explains how to use the MySQL CREATE TABLE statement with syntax and examples.
The MySQL CREATE TABLE statement allows you to create and define a table.
In its simplest form the syntax for the CREATE TABLE statement in MySQL is:
CREATE TABLE table_name
(
column1 datatype NULL | NOT NULL
column2 datatype NULL | NOT NULL
...
);
However the full syntax for the MySQL CREATE TABLE statement is:
CREATE TEMPORARY TABLE IF NOT EXISTS table_name
(
column1 datatype NULL | NOT NULL
DEFAULT default_value
AUTO_INCREMENT
UNIQUE KEY | PRIMARY KEY
COMMENT 'string'
column2 datatype NULL | NOT NULL
DEFAULT default_value
AUTO_INCREMENT
UNIQUE KEY | PRIMARY KEY
COMMENT 'string'
...
| CONSTRAINT constraint_name PRIMARY KEY USING BTREE | HASH (index_col_name ...)
| INDEX | KEY index_name USING BTREE | HASH (index_col_name ...)
| CONSTRAINT constraint_name UNIQUE INDEX | KEY
index_name USING BTREE | HASH (index_col_name ...)
| {FULLTEXT | SPATIAL} INDEX | KEY index_name (index_col_name ...)
| CONSTRAINT constraint_name
FOREIGN KEY index_name (index_col_name ...)
REFERENCES another_table_name (index_col_name ...)
MATCH FULL | MATCH PARTIAL | MATCH SIMPLE
ON DELETE { RESTRICT | CASCADE | SET NULL | NO ACTION }
ON UPDATE { RESTRICT | CASCADE | SET NULL | NO ACTION }
| CHECK (expression)
{ENGINE | TYPE} = engine_name
| AUTO_INCREMENT = value
| AVG_ROW_LENGTH = value
| DEFAULT CHARACTER SET = charset_name
| CHECKSUM = {0 | 1}
| DEFAULT COLLATE = collation_name
| COMMENT = 'string'
| DATA DIRECTORY = 'absolute path'
| DELAY_KEY_WRITE = { 0 | 1 }
| INDEX DIRECTORY = 'absolute path'
| INSERT_METHOD = { NO | FIRST | LAST }
| MAX_ROWS = value
| MIN_ROWS = value
| PACK_KEYS = {0 | 1 | DEFAULT}
| PASSWORD = 'string'
| RAID_TYPE = { 1 | STRIPED | RAIDO }
RAID_CHUNKS = value
RAID_CHUNKSIZE = value
| ROW_FORMAT = {DEFAULT | DYNAMIC | FIXED | COMPRESSED}
| UNION = (table1 ... )
);
TEMPORARY Optional. It specifies that the table is a temporary table. IF NOT EXISTS Optional. If specified the CREATE TABLE statement will not raise an error if the tables already exists. table_name The name of the table that you wish to create. column1 column2 The columns that you wish to create in the table. datatype The data type for the column and can be one of the following:
Value |
---|
CHAR (length) CHARACTER SET charset_name COLLATE collation_name |
VARCHAR (length) CHARACTER SET charset_name COLLATE collation_name |
BINARY (length) |
VARBINARY (length) |
DATE |
TIME |
TIMESTAMP |
DATETIME |
YEAR |
TINYINT (length) UNSIGNED ZEROFILL |
SMALLINT (length) UNSIGNED ZEROFILL |
MEDIUMINT (length) UNSIGNED ZEROFILL |
INT (length) UNSIGNED ZEROFILL |
INTEGER (length) UNSIGNED ZEROFILL |
BIGINT (length) UNSIGNED ZEROFILL |
REAL (length decimals) UNSIGNED ZEROFILL |
DOUBLE (length decimals) UNSIGNED ZEROFILL |
FLOAT (length decimals) UNSIGNED ZEROFILL |
DECIMAL (length decimals ) UNSIGNED ZEROFILL |
NUMERIC (length decimals ) UNSIGNED ZEROFILL |
TINYBLOB |
BLOB |
MEDIUMBLOB |
LONGBLOB |
TINYTEXT BINARY CHARACTER SET charset_name COLLATE collation_name |
TEXT BINARY CHARACTER SET charset_name COLLATE collation_name |
MEDIUMTEXT BINARY CHARACTER SET charset_name COLLATE collation_name |
LONGTEXT BINARY CHARACTER SET charset_name COLLATE collation_name |
ENUM(value1 value2 ...) CHARACTER SET charset_name COLLATE collation_name |
NULL or NOT NULL Each column should be defined as NULL or NOT NULL. If this parameter is omitted the database assumes NULL as the default. DEFAULT default_value Optional. It is the value to assign to the column if left blank or NULL. AUTO_INCREMENT Optional. It sets the column to be an autonumber field. constraint_name Optional. The name of the constraint if you define a primary key unique constraint or foreign key. index_col_name
Optional. It is the following syntax:
column_name (length) ASC | DESC
- There can only be one column in a table that is set as AUTO_INCREMENT and this column must be the primary key.
Let's look at a MySQL CREATE TABLE example.
CREATE TABLE contacts
( contact_id INT(11) NOT NULL AUTO_INCREMENT
last_name VARCHAR(30) NOT NULL
first_name VARCHAR(25)
birthday DATE
CONSTRAINT contacts_pk PRIMARY KEY (contact_id)
);
This MySQL CREATE TABLE example creates a table called contacts which has 4 columns and one primary key:
- The first column is called contact_id which is created as an INT datatype (maximum 11 digits in length) and can not contain NULL values. It is set as an AUTO_INCREMENT field which means that it is an autonumber field (starting at 1 and incrementing by 1 unless otherwise specified.)
- The second column is called last_name which is a VARCHAR datatype (maximum 30 characters in length) and can not contain NULL values.
- The third column is called first_name which is a VARCHAR datatype (maximum 25 characters in length) and can contain NULL values.
- The fourth column is called birthday which is a DATE datatype and can contain NULL values.
- The primary key is called contacts_pk and is set to the contact_id column.
Next let's create a table that has a DEFAULT VALUE.
CREATE TABLE suppliers
( supplier_id INT(11) NOT NULL AUTO_INCREMENT
supplier_name VARCHAR(50) NOT NULL
account_rep VARCHAR(30) NOT NULL DEFAULT 'TBD'
CONSTRAINT suppliers_pk PRIMARY KEY (supplier_id)
);
This MySQL CREATE TABLE example creates a table called suppliers which has 3 columns and one primary key:
- The first column is called supplier_id which is created as an INT datatype (maximum 11 digits in length) and can not contain NULL values. It is set as an AUTO_INCREMENT field.
- The second column is called supplier_name which is a VARCHAR datatype (maximum 50 characters in length) and can not contain NULL values.
- The third column is called account_rep which is a VARCHAR datatype (maximum 30 characters in length) and can not contain NULL values. If no value is provided for this column the DEFAULT VALUE will be 'TBD'.
- The primary key is called suppliers_pk and is set to the supplier_id column.
This MySQL tutorial explains how to use the MySQL CREATE TABLE AS statement with syntax and examples.
The MySQL CREATE TABLE AS statement is used to create a table from an existing table by copying the existing table's columns.
It is important to note that when creating a table in this way the new table will be populated with the records from the existing table (based on the SELECT Statement).
The syntax for the CREATE TABLE AS statement in MySQL is:
CREATE TABLE IF NOT EXISTS new_table AS
SELECT expressions
FROM existing_tables
WHERE conditions ;
IF NOT EXISTS Optional. If specified the CREATE TABLE AS statement will not raise an error if the table already exists. new_table The name of the table that you wish to create. AS Optional. Whether you specify the AS keyword or not has no impact on the creation of the table. expressions The columns from the existing_tables that you would like created in the new_table. The column definitions from those columns listed will be transferred to the new_table that you create. existing_tables The existing tables from which to copy the column definitions and the associated records (as per the WHERE clause). WHERE conditions Optional. The conditions that must be met for the records to be copied to the new_table.
- The column definitions from the existing_tables will be copied to the new_table.
- The new_table will be populated with records based on the conditions in the WHERE clause.
Let's look at a MySQL CREATE TABLE AS example that shows how to create a table by copying all columns from another table.
CREATE TABLE local_companies AS
SELECT \*
FROM companies
WHERE state = 'Florida';
This example would create a new table called local_companies that included all columns from the companies table.
If there were records in the companies table then the new local_companies table would be populated with the records returned by the SELECT statement.
Next let's look at a CREATE TABLE AS example that shows how to create a table by copying selected columns from multiple tables.
For example:
CREATE TABLE suppliers AS
SELECT companies.company_id AS "supplier_id"
companies.address companies.state categories.category_type
FROM companies categories
WHERE companies.company_id = categories.category_id
AND companies.state = 'Florida';
This example would create a new table called suppliers based on column definitions from both the companies and categories tables. Notice in this example that we have aliased the company_id field as supplier_id since we want the field in the new suppliers table to be called supplier_id and not company_id.
This MySQL tutorial explains how to use the MySQL ALTER TABLE statement to add a column modify a column drop a column rename a column or rename a table (with syntax and examples).
The MySQL ALTER TABLE statement is used to add modify or drop/delete columns in a table. The MySQL ALTER TABLE statement is also used to rename a table.
The syntax to add a column in a table in MySQL (using the ALTER TABLE statement) is:
ALTER TABLE table_name
ADD new_column_name column_definition
FIRST | AFTER column_name ;
table_name The name of the table to modify. new_column_name The name of the new column to add to the table. column_definition The datatype and definition of the column (NULL or NOT NULL etc). FIRST | AFTER column_name Optional. It tells MySQL where in the table to create the column. If this parameter is not specified the new column will be added to the end of the table.
Let's look at an example that shows how to add a column in a MySQL table using the ALTER TABLE statement.
For example:
ALTER TABLE contacts
ADD last_name varchar(40) NOT NULL
AFTER contact_id;
This MySQL ALTER TABLE example will add a column called last_name to the contacts table. It will be created as a NOT NULL column and will appear after the contact_id field in the table.
The syntax to add multiple columns in a table in MySQL (using the ALTER TABLE statement) is:
ALTER TABLE table_name
ADD new_column_name column_definition
FIRST | AFTER column_name
ADD new_column_name column_definition
FIRST | AFTER column_name
...
;
table_name The name of the table to modify. new_column_name The name of the new column to add to the table. column_definition The datatype and definition of the column (NULL or NOT NULL etc). FIRST | AFTER column_name Optional. It tells MySQL where in the table to create the column. If this parameter is not specified the new column will be added to the end of the table.
Let's look at an example that shows how to add multiple columns in a MySQL table using the ALTER TABLE statement.
For example:
ALTER TABLE contacts
ADD last_name varchar(40) NOT NULL
AFTER contact_id
ADD first_name varchar(35) NULL
AFTER last_name;
This ALTER TABLE example will add two columns to the contacts table - last_name and first_name.
The last_name field will be created as a varchar(40) NOT NULL column and will appear after the contact_id column in the table. The first_name column will be created as a varchar(35) NULL column and will appear after the last_name column in the table.
The syntax to modify a column in a table in MySQL (using the ALTER TABLE statement) is:
ALTER TABLE table_name
MODIFY column_name column_definition
FIRST | AFTER column_name ;
table_name The name of the table to modify. column_name The name of the column to modify in the table. column_definition The modified datatype and definition of the column (NULL or NOT NULL etc). FIRST | AFTER column_name Optional. It tells MySQL where in the table to position the column if you wish to change its position.
Let's look at an example that shows how to modify a column in a MySQL table using the ALTER TABLE statement.
For example:
ALTER TABLE contacts
MODIFY last_name varchar(50) NULL;
This ALTER TABLE example will modify the column called last_name to be a data type of varchar(50) and force the column to allow NULL values.
The syntax to modify multiple columns in a table in MySQL (using the ALTER TABLE statement) is:
ALTER TABLE table_name
MODIFY column_name column_definition
FIRST | AFTER column_name
MODIFY column_name column_definition
FIRST | AFTER column_name
...
;
table_name The name of the table to modify. column_name The name of the column to modify in the table. column_definition The modified datatype and definition of the column (NULL or NOT NULL etc). FIRST | AFTER column_name Optional. It tells MySQL where in the table to position the column if you wish to change its position.
Let's look at an example that shows how to modify multiple columns in a MySQL table using the ALTER TABLE statement.
For example:
ALTER TABLE contacts
MODIFY last_name varchar(55) NULL
AFTER contact_type
MODIFY first_name varchar(30) NOT NULL;
This ALTER TABLE example will modify two columns to the contacts table - last_name and first_name.
The last_name field will be changed to a varchar(55) NULL column and will appear after the contact_type column in the table. The first_name column will be modified to a varchar(30) NOT NULL column (and will not change position in the contacts table definition as there is no FIRST | AFTER specified).
The syntax to drop a column in a table in MySQL (using the ALTER TABLE statement) is:
ALTER TABLE table_name
DROP COLUMN column_name;
table_name The name of the table to modify. column_name The name of the column to delete from the table.
Let's look at an example that shows how to drop a column in a MySQL table using the ALTER TABLE statement.
For example:
ALTER TABLE contacts
DROP COLUMN contact_type;
This ALTER TABLE example will drop the column called contact_type from the table called contacts.
The syntax to rename a column in a table in MySQL (using the ALTER TABLE statement) is:
ALTER TABLE table_name
CHANGE COLUMN old_name new_name
column_definition
FIRST | AFTER column_name
table_name The name of the table to modify. old_name The column to rename. new_name The new name for the column. column_definition The datatype and definition of the column (NULL or NOT NULL etc). You must specify the column definition when renaming the column even if it does not change. FIRST | AFTER column_name Optional. It tells MySQL where in the table to position the column if you wish to change its position.
Let's look at an example that shows how to rename a column in a MySQL table using the ALTER TABLE statement.
For example:
ALTER TABLE contacts
CHANGE COLUMN contact_type ctype
varchar(20) NOT NULL;
This MySQL ALTER TABLE example will rename the column called contact_type to ctype. The column will be defined as a varchar(20) NOT NULL column.
The syntax to rename a table in MySQL is:
ALTER TABLE table_name
RENAME TO new_table_name;
table_name The table to rename. new_table_name The new table name to use.
Let's look at an example that shows how to rename a table in MySQL using the ALTER TABLE statement.
For example:
ALTER TABLE contacts
RENAME TO people;
This ALTER TABLE example will rename the contacts table to people.
This MySQL tutorial explains how to use the MySQL DROP TABLE statement with syntax and examples.
The MySQL DROP TABLE statement allows you to remove or delete a table from the MySQL database.
In its simplest form the syntax for the DROP TABLE statement in MySQL is:
DROP TABLE table_name;
However the full syntax for the MySQL DROP TABLE statement is:
DROP TEMPORARY TABLE IF EXISTS
table_name1 table_name2 ...
RESTRICT | CASCADE ;
TEMPORARY Optional. It specifies that only temporary tables should be dropped by the DROP TABLE statement. table_name The name of the table to remove from the database. table_name1 table_name2 The tables to remove from the database if removing more than one table in the DROP TABLE statement. IF EXISTS Optional. If specified the DROP TABLE statement will not raise an error if one of the tables does not exist. RESTRICT Optional. It has no impact or effect on the DROP TABLE statement but is included in the syntax to make porting the tables to different databases easier. CASCADE Optional. It has no impact or effect on the DROP TABLE statement but is included in the syntax to make porting the tables to different databases easier.
- If you use the MySQL DROP TABLE statement to drop one or more tables that do not exist the database will raise an error (unless you specify the IF EXISTS parameter in the DROP TABLE statement).
Let's look at an example that shows how to drop a table using the MySQL DROP TABLE statement.
First let's look at a simple DROP TABLE example that shows how to use the DROP TABLE statement to drop one table in MySQL.
For example:
DROP TABLE customers;
This DROP TABLE example would delete the table called customers.
Let's look at an example where we want to drop more than one table using the DROP TABLE statement:
For example:
DROP TABLE customers suppliers;
This DROP TABLE statement example would delete two tables - customers and suppliers. If we were worried that one of the tables doesn't exist and we don't want to raise an error we could modify our DROP TABLE statement as follows:
DROP TABLE IF EXISTS customers suppliers;
This example would delete the customers and suppliers tables and would not raise an error if one of the tables didn't exist.
Finally let's look at an example that shows how to use the DROP TABLE statement to drop a temporary table.
DROP TEMPORARY TABLE IF EXISTS customers;
This DROP TABLE example will only delete the temporary table called customers. If there was also a permanent table called customers this DROP TABLE statement would not delete it because TEMPORARY is specified.
This MySQL tutorial explains how to create update and drop VIEWS in MySQL with syntax and examples.
In MySQL a VIEW is not a physical table but rather it is in essence a virtual table created by a query joining one or more tables.
The syntax for the CREATE VIEW statement in MySQL is:
CREATE OR REPLACE VIEW view_name AS
SELECT columns
FROM tables
WHERE conditions ;
OR REPLACE Optional. If you do not specify this clause and the VIEW already exists the CREATE VIEW statement will return an error. view_name The name of the VIEW that you wish to create in MySQL. WHERE conditions Optional. The conditions that must be met for the records to be included in the VIEW.
Here is an example of how to use the CREATE VIEW statement to create a view in MySQL:
CREATE VIEW hardware_suppliers AS
SELECT supplier_id supplier_name
FROM suppliers
WHERE category_type = 'Hardware';
This CREATE VIEW example would create a virtual table based on the result set of the SELECT statement. You can now query the MySQL VIEW as follows:
SELECT \*
FROM hardware_suppliers;
You can modify the definition of a VIEW in MySQL without dropping it by using the ALTER VIEW statement.
The syntax for the ALTER VIEW statement in MySQL is:
ALTER VIEW view_name AS
SELECT columns
FROM table
WHERE conditions;
Here is an example of how you would use the ALTER VIEW statement in MySQL:
ALTER VIEW hardware_suppliers AS
SELECT supplier_id supplier_name address city
FROM suppliers
WHERE category_type = 'Hardware';
This ALTER VIEW example in MySQL would update the definition of the VIEW called hardware_suppliers without dropping it. In this example we are adding the address and city columns to the VIEW.
Once a VIEW has been created in MySQL you can drop it with the DROP VIEW statement.
The syntax for the DROP VIEW statement in MySQL is:
DROP VIEW IF EXISTS view_name;
view_name The name of the view that you wish to drop. IF EXISTS Optional. If you do not specify this clause and the VIEW does not exist the DROP VIEW statement will return an error.
Here is an example of how to use the DROP VIEW statement in MySQL:
DROP VIEW hardware_suppliers;
This DROP VIEW example would drop/delete the MySQL VIEW called hardware_suppliers.
This MySQL tutorial explains how to use the MySQL ASCII function with syntax and examples.
The MySQL ASCII function returns the numeric value of the left-most character of a string.
The syntax for the ASCII function in MySQL is:
ASCII( single_character )
single_character The specified character to retrieve the NUMBER code for. If more than one character is entered the ASCII function will return the value for the first character and ignore all of the characters after the first.
The ASCII function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL ASCII function examples and explore how to use the ASCII function in MySQL.
For example:
mysql> SELECT ASCII('t');
*Result:* 116
mysql> SELECT ASCII('techonthenet.com');
*Result:* 116
mysql> SELECT ASCII('T');
*Result:* 84
mysql> SELECT ASCII('T2');
*Result:* 84
View a listing of the ASCII values.
This MySQL tutorial explains how to use the MySQL CHAR_LENGTH function with syntax and examples.
The MySQL CHAR_LENGTH function returns the length of the specified string (measured in characters).
The syntax for the CHAR_LENGTH function in MySQL is:
CHAR_LENGTH( string )
string The string to return the length for.
- When using the CHAR_LENGTH function a multi-byte character is counted as a single character.
- The CHARACTER_LENGTH function is a synonym for the CHAR_LENGTH function.
- See also the LENGTH function.
The CHAR_LENGTH function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL CHAR_LENGTH function examples and explore how to use the CHAR_LENGTH function in MySQL.
For example:
mysql> SELECT CHAR_LENGTH(NULL);
*Result:* NULL
mysql> SELECT CHAR_LENGTH('');
*Result:* 0
mysql> SELECT CHAR_LENGTH(' ');
*Result:* 1
mysql> SELECT CHAR_LENGTH('Tech on the Net');
*Result:* 15
mysql> SELECT CHAR_LENGTH('techonthenet.com');
*Result:* 16
This MySQL tutorial explains how to use the MySQL CHARACTER_LENGTH function with syntax and examples.
The MySQL CHARACTER_LENGTH function returns the length of the specified string (measured in characters).
The syntax for the CHARACTER_LENGTH function in MySQL is:
CHARACTER_LENGTH( string )
string The string to return the length for.
- When using the CHARACTER_LENGTH function a multi-byte character is counted as a single character.
- The CHARACTER_LENGTH function is a synonym for the CHAR_LENGTH function.
- See also the LENGTH function.
The CHARACTER_LENGTH function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL CHARACTER_LENGTH function examples and explore how to use the CHARACTER_LENGTH function in MySQL.
For example:
mysql> SELECT CHARACTER_LENGTH(NULL);
*Result:* NULL
mysql> SELECT CHARACTER_LENGTH('');
*Result:* 0
mysql> SELECT CHARACTER_LENGTH(' ');
*Result:* 1
mysql> SELECT CHARACTER_LENGTH('Tech on the Net');
*Result:* 15
mysql> SELECT CHARACTER_LENGTH('techonthenet.com');
*Result:* 16
This MySQL tutorial explains how to use the MySQL CONCAT function with syntax and examples.
The MySQL CONCAT function allows you to concatenate two or more expressions together.
The syntax for the CONCAT function in MySQL is:
CONCAT( expression1 expression2 ... expression_n )
expression1 expression2 ... expression_n The expressions to concatenate together.
- If expression is a numeric value it will be converted by the CONCAT function to a binary string.
- If all expressions are nonbinary strings the CONCAT function will return a nonbinary string.
- If any of the expressions is a binary string the CONCAT function will return a binary string.
- If any of the expressions is a NULL the CONCAT function will return a NULL value.
- See also the CONCAT_WS function.
The CONCAT function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL CONCAT function examples and explore how to use the CONCAT function in MySQL.
For example:
mysql> SELECT CONCAT('tech' 'on' 'the' 'net' '.com');
*Result:* 'techonthenet.com'
mysql> SELECT CONCAT('The answer is ' 24);
*Result:* 'The answer is 24'
mysql> SELECT CONCAT('The answer is ' 10+10);
*Result:* 'The answer is 20'
mysql> SELECT CONCAT('techonthenet.com' NULL);
*Result:* NULL
You can also concatenate expressions together in MySQL by placing the strings next to each other.
For example:
mysql> SELECT 'tech' 'on' 'the' 'net' '.com';
*Result:* 'techonthenet.com'
mysql> SELECT 'The answer is ' '24';
*Result:* 'The answer is 24'
mysql> SELECT 'The answer is ' '10+10';
*Result:* 'The answer is 10+10'
Using the above method of concatenation each of the expressions must be a string.
This MySQL tutorial explains how to use the MySQL CONCAT_WS function with syntax and examples.
The MySQL CONCAT_WS function allows you to concatenate two or more expressions together and adds a separator between each of the concatenated expressions.
The syntax for the CONCAT_WS function in MySQL is:
CONCAT_WS( separator expression1 expression2 ... expression_n )
separator The separator that is added between each of the concatenated expressions. expression1 expression2 ... expression_n The expressions to concatenate together.
- The CONCAT_WS function skips expressions (ie: expression1 expression2 ... expression_n) that contain a NULL value.
- If separator is a NULL the CONCAT_WS function will return a NULL value.
- See also the CONCAT function.
The CONCAT_WS function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL CONCAT_WS function examples and explore how to use the CONCAT_WS function in MySQL.
For example:
mysql> SELECT CONCAT_WS('_' 'tech' 'on' 'the' 'net');
*Result:* 'tech_on_the_net'
mysql> SELECT CONCAT_WS(' ' 1 2 3 4);
*Result:* '1 2 3 4'
mysql> SELECT CONCAT_WS(' ' 1 2 3 4);
*Result:* '1 2 3 4'
mysql> SELECT CONCAT_WS('ABC' 'x' 'y' 'z');
*Result:* 'xABCyABCz'
mysql> SELECT CONCAT_WS('ABC' 'x' 'y' NULL 'z');
*Result:* 'xABCyABCz'
mysql> SELECT CONCAT_WS(NULL 'x' 'y' 'z');
*Result:* NULL
This MySQL tutorial explains how to use the MySQL FIELD function with syntax and examples.
The MySQL FIELD function returns the position of a value in a list of values (val1 val2 val3 ...).
The syntax for the FIELD function in MySQL is:
FIELD( value val1 val2 val3 ... )
value The value to find in the list. val1 val2 val3 ... The list of values that is to be searched.
- If value is not found in the list of values (val1 val2 val3 ...) the FIELD function will return 0.
- If value is NULL the FIELD function will return 0.
- If all arguments in the FIELD function are string values the find is performed as string values.
- If all arguments in the FIELD function are numeric values the find is performed as numeric values.
The FIELD function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL FIELD function examples and explore how to use the FIELD function in MySQL.
For example:
mysql> SELECT FIELD('b' 'a' 'b' 'c' 'd' 'e' 'f');
*Result:* 2
mysql> SELECT FIELD('B' 'a' 'b' 'c' 'd' 'e' 'f');
*Result:* 2
mysql> SELECT FIELD(15 10 20 15 40);
*Result:* 3
mysql> SELECT FIELD('c' 'a' 'b');
*Result:* 0
mysql> SELECT FIELD('g' '');
*Result:* 0
mysql> SELECT FIELD(null 'a' 'b' 'c');
*Result:* 0
mysql> SELECT FIELD('a' null);
*Result:* 0
This MySQL tutorial explains how to use the MySQL FIND_IN_SET function with syntax and examples.
The MySQL FIND_IN_SET function returns the position of a string in a comma-delimited string list.
The syntax for the FIND_IN_SET function in MySQL is:
FIND_IN_SET( string string_list )
string The string to find. string_list The list of string values separated by commas that is to be searched.
- If string is not found in string_list the FIND_IN_SET function will return 0.
- If string is NULL the FIND_IN_SET function will return NULL.
- If string_list is an empty string the FIND_IN_SET function will return 0.
- If string_list is NULL the FIND_IN_SET function will return NULL.
The FIND_IN_SET function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL FIND_IN_SET function examples and explore how to use the FIND_IN_SET function in MySQL.
For example:
mysql> SELECT FIND_IN_SET('b' 'a b c d e f');
*Result:* 2
mysql> SELECT FIND_IN_SET('B' 'a b c d e f');
*Result:* 2
mysql> SELECT FIND_IN_SET('f' 'a b c d e f');
*Result:* 6
mysql> SELECT FIND_IN_SET(2 '1 2 3');
*Result:* 2
mysql> SELECT FIND_IN_SET('g' 'a b c d e f');
*Result:* 0
mysql> SELECT FIND_IN_SET('g' '');
*Result:* 0
mysql> SELECT FIND_IN_SET(null 'a b c');
*Result:* NULL
mysql> SELECT FIND_IN_SET('a' null);
*Result:* NULL
This MySQL tutorial explains how to use the MySQL FORMAT function with syntax and examples.
The MySQL FORMAT function formats a number as a format of '## ###.##' rounding it to a certain number of decimal places and then it returns the result as a string.
The syntax for the FORMAT function in MySQL is:
FORMAT( number decimal_places )
number The number to format. decimal_places The number of decimal places to round the number.
- If decimal_places is 0 then the FORMAT function returns a string with no decimal places.
The FORMAT function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL FORMAT function examples and explore how to use the FORMAT function in MySQL.
For example:
mysql> SELECT FORMAT(12345.6789 2);
*Result:* '12 345.68'
mysql> SELECT FORMAT(12345.6789 1);
*Result:* '12 345.7'
mysql> SELECT FORMAT(12345.6789 0);
*Result:* '12 346'
This MySQL tutorial explains how to use the MySQL INSERT function with syntax and examples.
The MySQL INSERT function inserts a substring into a string at a specified position for a certain number of characters.
The syntax for the INSERT function in MySQL is:
INSERT( string position number substring )
string The string to modify. position The position in string to insert substring. number The number of characters to replace in string. substring The substring to insert into string.
- The first position in string is 1.
- If position is not within the length of string the INSERT function will return string.
- If number is not within the length of the rest of the string the INSERT function will replace string starting from position until the end of string.
The INSERT function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL INSERT function examples and explore how to use the INSERT function in MySQL.
For example:
mysql> SELECT INSERT('techonthenet.com' 1 12 'checkyourmath');
*Result:* 'checkyourmath.com'
mysql> SELECT INSERT('Tech on the Net' 13 3 'Internet');
*Result:* 'Tech on the Internet'
mysql> SELECT INSERT('abcgh' 4 2 'def');
*Result:* 'abcdef'
mysql> SELECT INSERT('techonthenet.com' 99 12 'checkyourmath');
*Result:* 'techonthenet.com'
This MySQL tutorial explains how to use the MySQL INSTR function with syntax and examples.
The MySQL INSTR function returns the location of a substring in a string.
The syntax for the INSTR function in MySQL is:
INSTR( string substring )
string The string to search. substring The substring to search for in string.
- The first position in string is 1.
- When finding the location of a substring in a string the INSTR function does not perform case-sensitive search.
- If substring is not found in string then the INSTR function will return 0.
The INSTR function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL INSTR function examples and explore how to use the INSTR function in MySQL.
For example:
mysql> SELECT INSTR('Tech on the net' 'T');
*Result:* 1
mysql> SELECT INSTR('Tech on the net' 't');
*Result:* 1
mysql> SELECT INSTR('Tech on the net' 'e');
*Result:* 2
mysql> SELECT INSTR('techonthenet.com' 'h');
*Result:* 4
mysql> SELECT INSTR('techonthenet.com' 'NET');
*Result:* 10
mysql> SELECT INSTR('techonthenet.com' 'Z');
*Result:* 0
This MySQL tutorial explains how to use the MySQL LCASE function with syntax and examples.
The MySQL LCASE function converts all characters in the specified string to lowercase. If there are characters in the string that are not letters they are unaffected by this function.
The LCASE function is a synonym for the LOWER function.
The syntax for the LCASE function in MySQL is:
LCASE( string )
string The string to convert to lowercase.
- The LCASE function will convert the characters using the current character mapping set which is latin1 by default.
- The LCASE function is a synonym for the LOWER function.
The LCASE function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL LCASE function examples and explore how to use the LCASE function in MySQL.
For example:
mysql> SELECT LCASE('Tech on the Net');
*Result:* 'tech on the net'
mysql> SELECT LCASE('TECHONTHENET.COM 123 ');
*Result:* 'techonthenet.com 123 '
This MySQL tutorial explains how to use the MySQL LEFT function with syntax and examples.
The MySQL LEFT function allows you to extract a substring from a string starting from the left-most character.
The syntax for the LEFT function in MySQL is:
LEFT( string number_of_characters )
string The string that you wish to extract from. number_of_characters The number of characters that you wish to extract from string starting from the left-most character.
- If number_of_characters exceeds the length of string the LEFT function will return string.
The LEFT function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL LEFT function examples and explore how to use the LEFT function in MySQL.
For example:
mysql> SELECT LEFT('Tech on the net' 1);
*Result:* 'T'
mysql> SELECT LEFT('techonthenet.com' 4);
*Result:* 'tech'
mysql> SELECT LEFT('techonthenet.com' 12);
*Result:* 'techonthenet'
mysql> SELECT LEFT('techonthenet.com' 100);
*Result:* 'techonthenet.com'
This MySQL tutorial explains how to use the MySQL LENGTH function with syntax and examples.
The MySQL LENGTH function returns the length of the specified string (measured in bytes).
The syntax for the LENGTH function in MySQL is:
LENGTH( string )
string The string to return the length for.
- When using the LENGTH function a multi-byte character is counted as more than one byte.
- See also the CHAR_LENGTH function.
The LENGTH function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL LENGTH function examples and explore how to use the LENGTH function in MySQL.
For example:
mysql> SELECT LENGTH(NULL);
*Result:* NULL
mysql> SELECT LENGTH('');
*Result:* 0
mysql> SELECT LENGTH(' ');
*Result:* 1
mysql> SELECT LENGTH('Tech on the Net');
*Result:* 15
mysql> SELECT LENGTH('techonthenet.com');
*Result:* 16
This MySQL tutorial explains how to use the MySQL LOCATE function with syntax and examples.
The MySQL LOCATE function returns the location of the first appearance of a substring in a string.
The syntax for the LOCATE function in MySQL is:
LOCATE( substring string start_position )
substring The substring to search for in string. string The string to search. start_position Optional. The position in string where the search will start. If omitted it defaults to 1. The first position in the string is 1.
- The first position in string is 1.
- If substring is not found in string then the LOCATE function will return 0.
- When searching for the location of a substring in a string the LOCATE function does not perform a case-sensitive search.
- The POSITION function is a synonym for the LOCATE function.
The LOCATE function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL LOCATE function examples and explore how to use the LOCATE function in MySQL.
For example:
mysql> SELECT LOCATE('T' 'techonthenet.com');
*Result:* 1
mysql> SELECT LOCATE('t' 'techonthenet.com');
*Result:* 1
mysql> SELECT LOCATE('t' 'techonthenet.com' 2);
*Result:* 7
mysql> SELECT LOCATE('e' 'techonthenet.com');
*Result:* 2
mysql> SELECT LOCATE('e' 'techonthenet.com' 3);
*Result:* 9
mysql> SELECT LOCATE('the' 'techonthenet.com' 1);
*Result:* 7
mysql> SELECT LOCATE('Z' 'techonthenet.com');
*Result:* 0
This MySQL tutorial explains how to use the MySQL LOWER function with syntax and examples.
The MySQL LOWER function converts all characters in the specified string to lowercase. If there are characters in the string that are not letters they are unaffected by this function.
The syntax for the LOWER function in MySQL is:
LOWER( string )
string The string to convert to lowercase.
- The LOWER function will convert the characters using the current character mapping set which is latin1 by default.
- The LCASE function is a synonym for the LOWER function.
The LOWER function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL LOWER function examples and explore how to use the LOWER function in MySQL.
For example:
mysql> SELECT LOWER('Tech on the Net');
*Result:* 'tech on the net'
mysql> SELECT LOWER('TECHONTHENET.COM 123 ');
*Result:* 'techonthenet.com 123 '
This MySQL tutorial explains how to use the MySQL LPAD function with syntax and examples.
The MySQL LPAD function returns a string that is left-padded with a specified string to a certain length.
The syntax for the LPAD function in MySQL is:
LPAD( string length pad_string )
string The string to left-pad. length The length of the result after string has been left-padded. pad_string The specified string to left-pad to string.
- If string is longer than length the LPAD function will remove characters from string to shorten it to length characters.
- See also the RPAD function.
The LPAD function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL LPAD function examples and explore how to use the LPAD function in MySQL.
For example:
mysql> SELECT LPAD('techonthenet.com' 18 'A');
*Result:* 'AAtechonthenet.com'
mysql> SELECT LPAD('techonthenet.com' 19 'A');
*Result:* 'AAAtechonthenet.com'
mysql> SELECT LPAD('abc' 6 ' ');
*Result:* ' abc'
mysql> SELECT LPAD('abc' 9 'XYZ');
*Result:* 'XYZXYZabc'
mysql> SELECT LPAD('abc' 10 'XYZ');
*Result:* 'XYZXYZXabc'
This MySQL tutorial explains how to use the MySQL LTRIM function with syntax and examples.
The MySQL LTRIM function removes all space characters from the left-hand side of a string.
The syntax for the LTRIM function in MySQL is:
LTRIM( string )
string The string to trim the space characters from the left-hand side.
The LTRIM function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL LTRIM function examples and explore how to use the LTRIM function in MySQL.
For example:
mysql> SELECT LTRIM(' Tech on the net');
*Result:* 'Tech on the net'
mysql> SELECT LTRIM(' Tech on the net ');
*Result:* 'Tech on the net '
mysql> SELECT LTRIM(' techonthenet.com');
*Result:* 'techonthenet.com'
This MySQL tutorial explains how to use the MySQL MID function with syntax and examples.
The MySQL MID function allows you to extract a substring from a string.
The syntax for the MID function in MySQL is:
MID( string start_position length )
string The source string used to extract from. start_position The position to begin extraction. The first position in the string is always 1. length The number of characters to extract.
- The first position in string is 1.
- If start_position is a positive number then the MID function starts from the beginning of the string.
- If start_position is a negative number then the MID function starts from the end of the string and counts backwards.
- The MID function and the SUBSTR function are synonyms of the SUBSTRING function.
The MID function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL MID function examples and explore how to use the MID function in MySQL.
For example:
mysql> SELECT MID('techonthenet.com' 5 2);
*Result:* 'on'
mysql> SELECT MID('techonthenet.com' 1 4);
*Result:* 'tech'
mysql> SELECT MID('techonthenet.com' -3 3);
*Result:* 'com'
mysql> SELECT MID('techonthenet.com' -7 3);
*Result:* 'net'
This MySQL tutorial explains how to use the MySQL POSITION function with syntax and examples.
The MySQL POSITION function returns the location of a substring in a string.
The syntax for the POSITION function in MySQL is:
POSITION( substring IN string )
substring The substring to search for in string. string The string to search.
- The first position in string is 1.
- If substring is not found in string then the POSITION function will return 0.
- When searching for the location of a substring in a string the POSITION function does not perform a case-sensitive search.
- The POSITION function is a synonym for the LOCATE function.
The POSITION function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL POSITION function examples and explore how to use the POSITION function in MySQL.
For example:
mysql> SELECT POSITION('T' IN 'Tech on the net');
*Result:* 1
mysql> SELECT POSITION('t' IN 'Tech on the net');
*Result:* 1
mysql> SELECT POSITION('e' IN 'Tech on the net');
*Result:* 2
mysql> SELECT POSITION('h' IN 'techonthenet.com');
*Result:* 4
mysql> SELECT POSITION('on' IN 'techonthenet.com');
*Result:* 5
mysql> SELECT POSITION('Z' IN 'techonthenet.com');
*Result:* 0
This MySQL tutorial explains how to use the MySQL REPEAT function with syntax and examples.
The MySQL REPEAT function repeats a string a specified number of times.
The syntax for the REPEAT function in MySQL is:
REPEAT( string number )
string The string to repeat. number The number of times to repeat the string.
- If number is less than 1 the REPEAT function will return an empty string.
The REPEAT function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL REPEAT function examples and explore how to use the REPEAT function in MySQL.
For example:
mysql> SELECT REPEAT('A' 2);
*Result:* 'AA'
mysql> SELECT REPEAT('a' 5);
*Result:* 'aaaaa'
mysql> SELECT REPEAT('abc' 2);
*Result:* 'abcabc'
mysql> SELECT REPEAT(' ' 6);
*Result:* ' '
mysql> SELECT REPEAT(3 2);
*Result:* '33'
mysql> SELECT REPEAT('abc' 0);
*Result:* ''
This MySQL tutorial explains how to use the MySQL REPLACE function with syntax and examples.
The MySQL REPLACE function replaces all occurrences of a specified string.
The syntax for the REPLACE function in MySQL is:
REPLACE( string from_substring to_substring )
string The source string. from_substring The substring to find. All occurrences of from_substring found within string are replaced with to_substring. to_substring The replacement substring. All occurrences of from_substring found within string are replaced with to_substring.
- The REPLACE function performs a case-sensitive replacement.
The REPLACE function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL REPLACE function examples and explore how to use the REPLACE function in MySQL.
For example:
mysql> SELECT REPLACE('techonthenet.com' 'techonthenet' 'checkyourmath');
*Result:* 'checkyourmath.com'
mysql> SELECT REPLACE('TechOnTheNet.com' 'techonthenet' 'checkyourmath');
*Result:* 'TechOnTheNet.com'
mysql> SELECT REPLACE('abc abc' 'a' 'B');
*Result:* 'Bbc Bbc'
mysql> SELECT REPLACE('abc abc' 'A' 'B');
*Result:* 'abc abc'
mysql> SELECT REPLACE('123 123' 2 5);
*Result:* '153 153'
This MySQL tutorial explains how to use the MySQL REVERSE function with syntax and examples.
The MySQL REVERSE function returns a string with the characters in reverse order.
The syntax for the REVERSE function in MySQL is:
REVERSE( string )
string The source string whose characters are to be reversed.
- The REVERSE function is safe to use with multi-bytes.
The REVERSE function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL REVERSE function examples and explore how to use the REVERSE function in MySQL.
For example:
mysql> SELECT REVERSE('techonthenet.com');
*Result:* 'moc.tenehtnohcet'
mysql> SELECT REVERSE('abcde');
*Result:* 'edcba'
mysql> SELECT REVERSE('123');
*Result:* '321'
mysql> SELECT REVERSE(123);
*Result:* '321'
This MySQL tutorial explains how to use the MySQL RIGHT function with syntax and examples.
The MySQL RIGHT function allows you to extract a substring from a string starting from the right-most character.
The syntax for the RIGHT function in MySQL is:
RIGHT( string number_of_characters )
string The string that you wish to extract from. number_of_characters The number of characters that you wish to extract from string starting from the right-most character.
- If number_of_characters exceeds the length of string the RIGHT function will return string.
The RIGHT function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL RIGHT function examples and explore how to use the RIGHT function in MySQL.
For example:
mysql> SELECT RIGHT('Tech on the net' 1);
*Result:* 't'
mysql> SELECT RIGHT('techonthenet.com' 4);
*Result:* '.com'
mysql> SELECT RIGHT('techonthenet.com' 12);
*Result:* 'onthenet.com'
mysql> SELECT RIGHT('techonthenet.com' 100);
*Result:* 'techonthenet.com'
This MySQL tutorial explains how to use the MySQL RPAD function with syntax and examples.
The MySQL RPAD function returns a string that is right-padded with a specified string to a certain length.
The syntax for the RPAD function in MySQL is:
RPAD( string length pad_string )
string The string to right-pad. length The length of the result after string has been right-padded. pad_string The specified string to right-pad to string.
- If string is longer than length the RPAD function will remove characters from string to shorten it to length characters.
- See also the LPAD function.
The RPAD function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL RPAD function examples and explore how to use the RPAD function in MySQL.
For example:
mysql> SELECT RPAD('techonthenet.com' 18 'A');
*Result:* 'techonthenet.comAA'
mysql> SELECT RPAD('techonthenet.com' 19 'A');
*Result:* 'techonthenet.comAAA'
mysql> SELECT RPAD('abc' 6 ' ');
*Result:* 'abc '
mysql> SELECT RPAD('abc' 9 'XYZ');
*Result:* 'abcXYZXYZ'
mysql> SELECT RPAD('abc' 10 'XYZ');
*Result:* 'abcXYZXYZX'
This MySQL tutorial explains how to use the MySQL RTRIM function with syntax and examples.
The MySQL RTRIM function removes all space characters from the right-hand side of a string.
The syntax for the RTRIM function in MySQL is:
RTRIM( string )
string The string to trim the space characters from the right-hand side.
The RTRIM function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL RTRIM function examples and explore how to use the RTRIM function in MySQL.
For example:
mysql> SELECT RTRIM('Tech on the net ');
*Result:* 'Tech on the net'
mysql> SELECT RTRIM(' Tech on the net ');
*Result:* ' Tech on the net'
mysql> SELECT RTRIM('techonthenet.com ');
*Result:* 'techonthenet.com'
This MySQL tutorial explains how to use the MySQL SPACE function with syntax and examples.
The MySQL SPACE function returns a string with a specified number of spaces.
The syntax for the SPACE function in MySQL is:
SPACE( number )
number The number of spaces to be returned.
The SPACE function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL SPACE function examples and explore how to use the SPACE function in MySQL.
For example:
mysql> SELECT SPACE(3);
*Result:* ' '
mysql> SELECT SPACE(7);
*Result:* ' '
This MySQL tutorial explains how to use the MySQL STRCMP function with syntax and examples.
The MySQL STRCMP function tests whether two strings are the same using the current character set.
The syntax for the STRCMP function in MySQL is:
STRCMP( string1 string2 )
string1 and string2 The two strings to be compared to each other.
- If string1 and string2 are the same the STRCMP function will return 0.
- If string1 is smaller than string2 the STRCMP function will return -1.
- If string1 is larger than string2 the STRCMP function will return 1.
The STRCMP function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL STRCMP function examples and explore how to use the STRCMP function in MySQL.
For example:
mysql> SELECT STRCMP('techonthenet.com' 'techonthenet.com');
*Result:* 0
mysql> SELECT STRCMP('checkyourmath.com' 'techonthenet.com');
*Result:* -1
mysql> SELECT STRCMP('techonthenet.com' 'checkyourmath.com');
*Result:* 1
This MySQL tutorial explains how to use the MySQL SUBSTR function with syntax and examples.
The MySQL SUBSTR function allows you to extract a substring from a string.
The syntax for the SUBSTR function in MySQL is:
SUBSTR( string start_position length )
OR
SUBSTR( string FROM start_position FOR length )
string The source string. start_position The position for extraction. The first position in the string is always 1. length Optional. It is the number of characters to extract. If this parameter is omitted the SUBSTR function will return the entire string.
- The first position in string is 1.
- If start_position is a positive number then the SUBSTR function starts from the beginning of the string.
- If start_position is a negative number then the SUBSTR function starts from the end of the string and counts backwards. Negative values for start_position was introduced in MySQL 4.1.
- The SUBSTR function and the MID function are synonyms of the SUBSTRING function.
The SUBSTR function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1.1
Let's look at some MySQL SUBSTR function examples and explore how to use the SUBSTR function in MySQL.
For example:
mysql> SELECT SUBSTR('Techonthenet.com' 5);
*Result:* 'onthenet.com'
mysql> SELECT SUBSTR('Techonthenet.com' FROM 5);
*Result:* 'onthenet.com'
mysql> SELECT SUBSTR('Techonthenet.com' 1 4);
*Result:* 'Tech'
mysql> SELECT SUBSTR('Techonthenet.com' FROM 1 FOR 4);
*Result:* 'Tech'
mysql> SELECT SUBSTR('Techonthenet.com' -3 3);
*Result:* 'com'
mysql> SELECT SUBSTR('Techonthenet.com' FROM -3 FOR 3);
*Result:* 'com'
This MySQL tutorial explains how to use the MySQL SUBSTRING function with syntax and examples.
The MySQL SUBSTRING function allows you to extract a substring from a string.
The syntax for the SUBSTRING function in MySQL is:
SUBSTRING( string start_position length )
OR
SUBSTRING( string FROM start_position FOR length )
string The source string. start_position The position for extraction. The first position in the string is always 1. length Optional. It is the number of characters to extract. If this parameter is omitted the SUBSTRING function will return the entire remaining string.
- The first position in string is 1.
- If start_position is a positive number then the SUBSTRING function starts from the beginning of the string.
- If start_position is a negative number then the SUBSTRING function starts from the end of the string and counts backwards. Negative values for start_position was introduced in MySQL 4.1.
- The SUBSTR function and the MID function are synonyms of the SUBSTRING function.
The SUBSTRING function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL SUBSTRING function examples and explore how to use the SUBSTRING function in MySQL.
For example:
mysql> SELECT SUBSTRING('Techonthenet.com' 5);
*Result:* 'onthenet.com'
mysql> SELECT SUBSTRING('Techonthenet.com' FROM 5);
*Result:* 'onthenet.com'
mysql> SELECT SUBSTRING('Techonthenet.com' 1 4);
*Result:* 'Tech'
mysql> SELECT SUBSTRING('Techonthenet.com' FROM 1 FOR 4);
*Result:* 'Tech'
mysql> SELECT SUBSTRING('Techonthenet.com' -3 3);
*Result:* 'com'
mysql> SELECT SUBSTRING('Techonthenet.com' FROM -3 FOR 3);
*Result:* 'com'
This MySQL tutorial explains how to use the MySQL SUBSTRING_INDEX function with syntax and examples.
The MySQL SUBSTRING_INDEX function returns the substring of string before number of occurrences of delimiter.
The syntax for the SUBSTRING_INDEX function in MySQL is:
SUBSTRING_INDEX( string delimiter number )
string The source string. delimiter The delimiter to search for in string. number The number of times to search for delimiter.
- If number is a positive value everything from the left of the targeted delimiter is returned by the SUBSTRING_INDEX function.
- If number is a negative value everything from the right of the targeted delimiter is returned by the SUBSTRING_INDEX function.
- See also SUBSTRING function.
The SUBSTRING_INDEX function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL SUBSTRING_INDEX function examples and explore how to use the SUBSTRING_INDEX function in MySQL.
For example:
mysql> SELECT SUBSTRING_INDEX('www.techonthenet.com' '.' 1);
*Result:* 'www'
mysql> SELECT SUBSTRING_INDEX('www.techonthenet.com' '.' 2);
*Result:* 'www.techonthenet'
mysql> SELECT SUBSTRING_INDEX('www.techonthenet.com' '.' -1);
*Result:* 'com'
mysql> SELECT SUBSTRING_INDEX('www.techonthenet.com' '.' -2);
*Result:* 'techonthenet.com'
This MySQL tutorial explains how to use the MySQL TRIM function with syntax and examples.
The MySQL TRIM function removes all specified characters either from the beginning or the end of a string.
The syntax for the TRIM function in MySQL is:
TRIM( LEADING | TRAILING | BOTH trim_character FROM string )
LEADING Optional. Removes the trim_character from the front of string. TRAILING Optional. Removes the trim_character from the end of string. BOTH Optional. Removes the trim_character from the front and end of string. trim_character Optional. The character that will be removed from string. If this parameter is omitted it will remove space characters from string. string The string to trim.
- If you do not specify a value for the first parameter (LEADING TRAILING BOTH) the TRIM function will default to BOTH and remove trim_character from both the front and end of string.
- If you do not specify a trim_character the TRIM function will default the character to be removed as a space character.
The TRIM function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL TRIM function examples and explore how to use the TRIM function in MySQL.
For example:
mysql> SELECT TRIM(LEADING ' ' FROM ' techonthenet.com ');
*Result:* 'techonthenet.com '
mysql> SELECT TRIM(TRAILING ' ' FROM ' techonthenet.com ');
*Result:* ' techonthenet.com'
mysql> SELECT TRIM(BOTH ' ' FROM ' techonthenet.com ');
*Result:* 'techonthenet.com'
mysql> SELECT TRIM(' ' FROM ' techonthenet.com ');
*Result:* 'techonthenet.com'
mysql> SELECT TRIM(' techonthenet.com ');
*Result:* 'techonthenet.com'
mysql> SELECT TRIM(LEADING '0' FROM '000123');
*Result:* '123'
mysql> SELECT TRIM(TRAILING '1' FROM 'Tech1');
*Result:* 'Tech'
mysql> SELECT TRIM(BOTH '123' FROM '123Tech123');
*Result:* 'Tech'
This MySQL tutorial explains how to use the MySQL UCASE function with syntax and examples.
The MySQL UCASE function converts all characters in the specified string to uppercase. If there are characters in the string that are not letters they are unaffected by this function.
The syntax for the UCASE function in MySQL is:
UCASE( string )
string The string to convert to uppercase.
- The UCASE function will convert the characters using the current character mapping set which is latin1 by default.
- The UCASE function is a synonym for the UPPER function.
The UCASE function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL UCASE function examples and explore how to use the UCASE function in MySQL.
For example:
mysql> SELECT UCASE('Tech on the Net');
*Result:* 'TECH ON THE NET'
mysql> SELECT UCASE('Techonthenet.com 123 ');
*Result:* 'TECHONTHENET.COM 123 '
This MySQL tutorial explains how to use the MySQL UPPER function with syntax and examples.
The MySQL UPPER function converts all characters in the specified string to uppercase. If there are characters in the string that are not letters they are unaffected by this function.
The syntax for the UPPER function in MySQL is:
UPPER( string )
string The string to convert to uppercase.
- The UPPER function will convert the characters using the current character mapping set which is latin1 by default.
- The UCASE function is a synonym for the UPPER function.
The UPPER function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL UPPER function examples and explore how to use the UPPER function in MySQL.
For example:
mysql> SELECT UPPER('Tech on the Net');
*Result:* 'TECH ON THE NET'
mysql> SELECT UPPER('Techonthenet.com 123 ');
*Result:* 'TECHONTHENET.COM 123 '
This MySQL tutorial explains how to use the MySQL ABS function with syntax and examples.
The MySQL ABS function returns the absolute value of a number.
The syntax for the ABS function in MySQL is:
ABS( number )
number The number to convert to an absolute value.
The ABS function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL ABS function examples and explore how to use the ABS function in MySQL.
For example:
mysql> SELECT ABS(-23);
*Result:* 23
mysql> SELECT ABS(-23.6);
*Result:* 23.6
mysql> SELECT ABS(-23.65);
*Result:* 23.65
mysql> SELECT ABS(23.65);
*Result:* 23.65
mysql> SELECT ABS(30 \* -1);
*Result:* 30
This MySQL tutorial explains how to use the MySQL ACOS function with syntax and examples.
The MySQL ACOS function returns the arc cosine of a number.
The syntax for the ACOS function in MySQL is:
ACOS( number )
number The number used to calculate the arc cosine.
- The ACOS function will return NULL if number is not within the range of -1 to 1.
The ACOS function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL ACOS function examples and explore how to use the ACOS function in MySQL.
For example:
mysql> SELECT ACOS(0.75);
*Result:* 0.7227342478134157
mysql> SELECT ACOS(0.2);
*Result:* 1.369438406004566
mysql> SELECT ACOS(-0.9);
*Result:* 2.6905658417935308
mysql> SELECT ACOS(2);
*Result:* NULL
This MySQL tutorial explains how to use the MySQL ASIN function with syntax and examples.
The MySQL ASIN function returns the arc sine of a number.
The syntax for the ASIN function in MySQL is:
ASIN( number )
number The number used to calculate the arc sine.
- The ASIN function will return NULL if number is not within the range of -1 to 1.
The ASIN function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL ASIN function examples and explore how to use the ASIN function in MySQL.
For example:
mysql> SELECT ASIN(0.75);
*Result:* 0.848062078981481
mysql> SELECT ASIN(0.2);
*Result:* 0.2013579207903308
mysql> SELECT ASIN(-0.9);
*Result:* -1.1197695149986342
mysql> SELECT ASIN(2);
*Result:* NULL
This MySQL tutorial explains how to use the MySQL ATAN function with syntax and examples.
The MySQL ATAN function returns the arc tangent of a number or returns the arc tangent of n and m.
The syntax for the ATAN function in MySQL is:
ATAN( number )
OR
ATAN( n m )
number The number used to calculate the arc tangent. n m Values used to calculate the arc tangent of two values.
- When using the second syntax for the ATAN function the signs of n and m are used to determine the quadrant for the result.
The ATAN function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL ATAN function examples and explore how to use the ATAN function in MySQL.
For example:
mysql> SELECT ATAN(0.75);
*Result:* 0.6435011087932844
mysql> SELECT ATAN(-2);
*Result:* -1.1071487177940904
mysql> SELECT ATAN(-0.9 2);
*Result:* -0.4228539261329407
mysql> SELECT ATAN(PI() 2);
*Result:* 1.0038848218538872
This MySQL tutorial explains how to use the MySQL ATAN2 function with syntax and examples.
The MySQL ATAN2 function returns the arc tangent of n and m.
The syntax for the ATAN2 function in MySQL is:
ATAN2( n m )
n m Values used to calculate the arc tangent of two values.
- The signs of n and m are used to determine the quadrant for the result from the ATAN2 function.
The ATAN2 function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL ATAN2 function examples and explore how to use the ATAN2 function in MySQL.
For example:
mysql> SELECT ATAN2(0.75 1);
*Result:* 0.6435011087932844
mysql> SELECT ATAN2(-0.9 2);
*Result:* -0.4228539261329407
mysql> SELECT ATAN2(PI() 2);
*Result:* 1.0038848218538872
This MySQL tutorial explains how to use the MySQL AVG function with syntax and examples.
The MySQL AVG function returns the average value of an expression.
The syntax for the AVG function in MySQL is:
SELECT AVG(aggregate_expression)
FROM tables
WHERE conditions ;
OR the syntax for the AVG function when grouping the results by one or more columns is:
SELECT expression1 expression2 ... expression_n
AVG(aggregate_expression)
FROM tables
WHERE conditions
GROUP BY expression1 expression2 ... expression_n;
expression1 expression2 ... expression_n Expressions that are not encapsulated within the AVG function and must be included in the GROUP BY clause at the end of the SQL statement. aggregate_expression This is the column or expression that will be averaged. tables The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause. WHERE conditions Optional. These are conditions that must be met for the records to be selected.
The AVG function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL AVG function examples and explore how to use the AVG function in MySQL.
For example you might wish to know how the average salary of all employees whose salary is above $25 000 / year.
SELECT AVG(salary) AS "Avg Salary"
FROM employees
WHERE salary > 25000;
In this AVG function example we've aliased the AVG(salary) expression as "Avg Salary". As a result "Avg Salary" will display as the field name when the result set is returned.
You can use the DISTINCT clause within the AVG function. For example the SQL statement below returns the average salary of unique salary values where the salary is above $25 000 / year.
SELECT AVG(DISTINCT salary) AS "Avg Salary"
FROM employees
WHERE salary > 25000;
If there were two salaries of $30 000/year only one of these values would be used in the AVG function.
The expression contained within the AVG function does not need to be a single field. You could also use a formula. For example you might want the average commission.
SELECT AVG(sales \* 0.10) AS "Average Commission"
FROM orders;
You could also use the AVG function to return the name of the department and the average sales (in the associated department). For example
SELECT department AVG(sales) AS "Avg sales"
FROM order_details
GROUP BY department;
Because you have listed one column in your SELECT statement that is not encapsulated in the AVG function you must use a GROUP BY clause. The department field must therefore be listed in the GROUP BY section.
This MySQL tutorial explains how to use the MySQL CEIL function with syntax and examples.
The MySQL CEIL function returns the smallest integer value that is greater than or equal to a number.
The syntax for the CEIL function in MySQL is:
CEIL( number )
number The value used to find the smallest integer value.
- The CEIL function is a synonym for the CEILING function.
- See also the FLOOR ROUND CEILING and TRUNCATE functions.
The CEIL function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0.6
Let's look at some MySQL CEIL function examples and explore how to use the CEIL function in MySQL.
For example:
mysql> SELECT CEIL(32.65);
*Result:* 33
mysql> SELECT CEIL(32.1);
*Result:* 33
mysql> SELECT CEIL(32);
*Result:* 32
mysql> SELECT CEIL(-32.65);
*Result:* -32
mysql> SELECT CEIL(-32.1);
*Result:* -32
mysql> SELECT CEIL(-32);
*Result:* -32
This MySQL tutorial explains how to use the MySQL CEILING function with syntax and examples.
The MySQL CEILING function returns the smallest integer value that is greater than or equal to a number.
The syntax for the CEILING function in MySQL is:
CEILING( number )
number The value used to find the smallest integer value.
- The CEIL function is a synonym for the CEILING function.
- See also the FLOOR CEIL ROUND and TRUNCATE functions.
The CEILING function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL CEILING function examples and explore how to use the CEILING function in MySQL.
For example:
mysql> SELECT CEILING(32.65);
*Result:* 33
mysql> SELECT CEILING(32.1);
*Result:* 33
mysql> SELECT CEILING(32);
*Result:* 32
mysql> SELECT CEILING(-32.65);
*Result:* -32
mysql> SELECT CEILING(-32.1);
*Result:* -32
mysql> SELECT CEILING(-32);
*Result:* -32
This MySQL tutorial explains how to use the MySQL COS function with syntax and examples.
The MySQL COS function returns the cosine of a number.
The syntax for the COS function in MySQL is:
COS( number )
number The value used to calculate the cosine. It is expressed in radians.
The COS function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL COS function examples and explore how to use the COS function in MySQL.
For example:
mysql> SELECT COS(2);
*Result:* -0.4161468365471424
mysql> SELECT COS(PI());
*Result:* -1
mysql> SELECT COS(-0.9);
*Result:* 0.6216099682706644
This MySQL tutorial explains how to use the MySQL COT function with syntax and examples.
The MySQL COT function returns the cotangent of a number.
The syntax for the COT function in MySQL is:
COT( number )
number The number used to calculate the cotangent.
- The COT function will return NULL or an error (depending on your version of MySQL) if number is 0.
The COT function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL COT function examples and explore how to use the COT function in MySQL.
For example:
mysql> SELECT COT(4);
*Result:* 0.8636911544506167
mysql> SELECT COT(-1);
*Result:* -0.6420926159343306
mysql> SELECT COT(3.4);
*Result:* 3.7833373375604737
This MySQL tutorial explains how to use the MySQL COUNT function with syntax and examples.
The MySQL COUNT function returns the count of an expression.
The syntax for the COUNT function in MySQL is:
SELECT COUNT(aggregate_expression)
FROM tables
WHERE conditions ;
OR the syntax for the COUNT function when grouping the results by one or more columns is:
SELECT expression1 expression2 ... expression_n
COUNT(aggregate_expression)
FROM tables
WHERE conditions
GROUP BY expression1 expression2 ... expression_n;
expression1 expression2 ... expression_n Expressions that are not encapsulated within the COUNT function and must be included in the GROUP BY clause at the end of the SQL statement. aggregate_expression This is the column or expression whose non-null values will be counted. tables The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause. WHERE conditions Optional. These are conditions that must be met for the records to be selected.
Not everyone realizes this but the COUNT function will only include the records in the count where the value of expression in COUNT(expression) is NOT NULL. When expression contains a NULL value it is not included in the COUNT calculations.
Let's look at a COUNT function example that demonstrates how NULL values are evaluated by the COUNT function.
For example if you have the following table called suppliers:
supplier_id | supplier_name | state |
---|---|---|
1 | IBM | CA |
2 | Microsoft | |
3 | NVIDIA |
And if you ran the following SELECT statement that uses the COUNT function:
SELECT COUNT(supplier_id)
FROM suppliers;
*Result:* 3
This COUNT example will return 3 since all supplier_id values in the query's result set are NOT NULL.
However if you ran the next SELECT statement that uses the COUNT function:
SELECT COUNT(state)
FROM suppliers;
*Result:* 1
This COUNT example will only return 1 since only one state value in the query's result set is NOT NULL. That would be the first row where the state = 'CA'. It is the only row that is included in the COUNT function calculation.
The COUNT function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL COUNT function examples and explore how to use the COUNT function in MySQL.
For example you might wish to know how many employees have a salary above $75 000 / year.
SELECT COUNT(\*) AS "Number of employees"
FROM employees
WHERE salary > 75000;
In this COUNT function example we've aliased the COUNT(*) expression as "Number of employees". As a result "Number of employees" will display as the field name when the result set is returned.
You can use the DISTINCT clause within the COUNT function. For example the SQL statement below returns the number of unique departments where at least one employee makes over $55 000 / year.
SELECT COUNT(DISTINCT department) AS "Unique departments"
FROM employees
WHERE salary > 55000;
Again the COUNT(DISTINCT department) field is aliased as "Unique departments". This is the field name that will display in the result set.
In some cases you will be required to use the GROUP BY clause with the COUNT function.
For example you could also use the COUNT function to return the name of the department and the number of employees (in the associated department) that are in the state of 'CA'.
SELECT department COUNT(\*) AS "Number of employees"
FROM employees
WHERE state = 'CA'
GROUP BY department;
Because you have listed one column in your SELECT statement that is not encapsulated in the COUNT function you must use a GROUP BY clause. The department field must therefore be listed in the GROUP BY section.
This MySQL tutorial explains how to use the MySQL DEGREES function with syntax and examples.
The MySQL DEGREES function converts a radian value into degrees.
The syntax for the DEGREES function in MySQL is:
DEGREES( number )
number The value in radians that is to be converted to degrees.
The DEGREES function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL DEGREES function examples and explore how to use the DEGREES function in MySQL.
For example:
mysql> SELECT DEGREES(1.5);
*Result:* 85.94366926962348
mysql> SELECT DEGREES(-0.9);
*Result:* -51.56620156177409
mysql> SELECT DEGREES(PI()\*2);
*Result:* 360
This MySQL tutorial explains how to use the MySQL DIV function with syntax and examples.
The MySQL DIV function is used for integer division where n is divided by m and an integer value is returned.
The syntax for the DIV function in MySQL is:
n DIV m
n The value that will be divided by m. m The value that will be divided into n.
- The DIV function will return the result as an integer value.
- The DIV function can be used with BIGINT values.
- See also the FLOOR function.
The DIV function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL DIV function examples and explore how to use the DIV function in MySQL.
For example:
mysql> SELECT 9 DIV 2;
*Result:* 4
mysql> SELECT 8 DIV 2;
*Result:* 4
mysql> SELECT 10.5 DIV 3.1;
*Result:* 3
mysql> SELECT 10.5 DIV -3.1;
*Result:* -3
This MySQL tutorial explains how to use the MySQL EXP function with syntax and examples.
The MySQL EXP function returns e raised to the power of number (or enumber).
The syntax for the EXP function in MySQL is:
EXP( number )
number The power to raise e to so the formula would be enumber.
The EXP function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL EXP function examples and explore how to use the EXP function in MySQL.
For example:
mysql> SELECT EXP(0);
*Result:* 1
mysql> SELECT EXP(1);
*Result:* 2.718281828459045
mysql> SELECT EXP(2);
*Result:* 7.38905609893065
mysql> SELECT EXP(-2);
*Result:* 0.1353352832366127
This MySQL tutorial explains how to use the MySQL FLOOR function with syntax and examples.
The MySQL FLOOR function returns the largest integer value that is equal to or less than a number.
The syntax for the FLOOR function in MySQL is:
FLOOR( number )
number The value used to find the largest integer value.
- See also the ROUND CEIL CEILING and TRUNCATE functions.
- See also the DIV function.
The FLOOR function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL FLOOR function examples and explore how to use the FLOOR function in MySQL.
For example:
mysql> SELECT FLOOR(32.65);
*Result:* 32
mysql> SELECT FLOOR(32.1);
*Result:* 32
mysql> SELECT FLOOR(32);
*Result:* 32
mysql> SELECT FLOOR(-32.65);
*Result:* -33
mysql> SELECT FLOOR(-32.1);
*Result:* -33
mysql> SELECT FLOOR(-32);
*Result:* -32
This MySQL tutorial explains how to use the MySQL GREATEST function with syntax and examples.
The MySQL GREATEST function returns the greatest value in a list of expressions.
The syntax for the GREATEST function in MySQL is:
GREATEST( expr1 expr2 ... expr_n )
expr1 expr2 ... expr_n The expressions that are evaluated by the GREATEST function.
The GREATEST function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL GREATEST function examples and explore how to use the GREATEST function in MySQL.
For example:
mysql> SELECT GREATEST(2 5 12 3);
*Result:* 12
mysql> SELECT GREATEST('2' '5' '12' '3');
*Result:* '5'
mysql> SELECT GREATEST('techonthenet.com' 'checkyourmath.com' 'bigactivities.com');
*Result:* 'techonthenet.com'
mysql> SELECT GREATEST('techonthenet.com' 'checkyourmath.com' null);
*Result:* NULL
This MySQL tutorial explains how to use the MySQL LEAST function with syntax and examples.
The MySQL LEAST function returns the smallest value in a list of expressions.
The syntax for the LEAST function in MySQL is:
LEAST( expr1 expr2 ... expr_n )
expr1 expr2 ... expr_n The expressions that are evaluated by the LEAST function.
The LEAST function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL LEAST function examples and explore how to use the LEAST function in MySQL.
For example:
mysql> SELECT LEAST(2 5 12 3);
*Result:* 2
mysql> SELECT LEAST('2' '5' '12' '3');
*Result:* '12'
mysql> SELECT LEAST('techonthenet.com' 'checkyourmath.com' 'bigactivities.com');
*Result:* 'bigactivities.com'
mysql> SELECT LEAST('techonthenet.com' 'checkyourmath.com' null);
*Result:* NULL
This MySQL tutorial explains how to use the MySQL LN function with syntax and examples.
The MySQL LN function returns the natural logarithm of a number.
The syntax for the LN function in MySQL is:
LN( number )
number The number to calculate the natural logarithm of. Must be greater than 0.
- The LN function will return NULL if number is less than or equal to 0.
- See also the LOG and EXP functions.
The LN function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL LN function examples and explore how to use the LN function in MySQL.
For example:
mysql> SELECT LN(1);
*Result:* 0
mysql> SELECT LN(2);
*Result:* 0.6931471805599453
mysql> SELECT LN(2.5);
*Result:* 0.9162907318741551
mysql> SELECT LN(0);
*Result:* NULL
mysql> SELECT LN(-1);
*Result:* NULL
This MySQL tutorial explains how to use the MySQL LOG function with syntax and examples.
The MySQL LOG function returns either the natural logarithm of a number if called with one parameter or the logarithm of a number to a specified base if called with two parameters.
The syntax for the LOG function in MySQL is:
LOG( number )
OR
LOG( base number )
number The number to take the natural logarithm of. Must be greater than 0. base The base the natural logarithm is to be calculated with. Must be greater than 1.
- The LOG function will return NULL if number is less than or equal to 0.
- The LOG function will return NULL if base is less than or equal to 1.
- See also the LN and EXP functions.
The LOG function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL LOG function examples and explore how to use the LOG function in MySQL.
For example let's look at some examples of the LOG function when one parameter is provided:
mysql> SELECT LOG(1);
*Result:* 0
mysql> SELECT LOG(2);
*Result:* 0.6931471805599453
mysql> SELECT LOG(2.5);
*Result:* 0.9162907318741551
mysql> SELECT LOG(0);
*Result:* NULL
Now let's look at some examples of the LOG function when two parameters are provided:
mysql> SELECT LOG(2 1);
*Result:* 0
mysql> SELECT LOG(3 4);
*Result:* 1.2618595071429148
mysql> SELECT LOG(2 0);
*Result:* NULL
mysql> SELECT LOG(1 4);
*Result:* NULL
This MySQL tutorial explains how to use the MySQL LOG10 function with syntax and examples.
The MySQL LOG10 function returns the base-10 logarithm of a number.
The syntax for the LOG10 function in MySQL is:
LOG10( number )
number The number to take the base-10 logarithm of. Must be greater than 0.
- The LOG10 function will return NULL if number is less than or equal to 0.
- See also the LOG function.
The LOG10 function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0.3
Let's look at some MySQL LOG10 function examples and explore how to use the LOG10 function in MySQL.
For example:
mysql> SELECT LOG10(1);
*Result:* 0
mysql> SELECT LOG10(2);
*Result:* 0.3010299956639812
mysql> SELECT LOG10(3.1);
*Result:* 0.4913616938342727
mysql> SELECT LOG10(0);
*Result:* NULL
This MySQL tutorial explains how to use the MySQL LOG2 function with syntax and examples.
The MySQL LOG2 function returns the base-2 logarithm of a number.
The syntax for the LOG2 function in MySQL is:
LOG2( number )
number The number to take the base-2 logarithm of. Must be greater than 0.
- The LOG2 function will return NULL if number is less than or equal to 0.
- See also the LOG function.
The LOG2 function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0.3
Let's look at some MySQL LOG2 function examples and explore how to use the LOG2 function in MySQL.
For example:
mysql> SELECT LOG2(1);
*Result:* 0
mysql> SELECT LOG2(8);
*Result:* 3
mysql> SELECT LOG2(1024);
*Result:* 10
mysql> SELECT LOG2(0);
*Result:* NULL
This MySQL tutorial explains how to use the MySQL MAX function with syntax and examples.
The MySQL MAX function returns the maximum value of an expression.
The syntax for the MAX function in MySQL is:
SELECT MAX(aggregate_expression)
FROM tables
WHERE conditions ;
OR the syntax for the MAX function when grouping the results by one or more columns is:
SELECT expression1 expression2 ... expression_n
MAX(aggregate_expression)
FROM tables
WHERE conditions
GROUP BY expression1 expression2 ... expression_n;
expression1 expression2 ... expression_n Expressions that are not encapsulated within the MAX function and must be included in the GROUP BY clause at the end of the SQL statement. aggregate_expression This is the column or expression from which the maximum value will be returned. tables The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause. WHERE conditions Optional. These are conditions that must be met for the records to be selected.
The MAX function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL MAX function examples and explore how to use the MAX function in MySQL.
For example you might wish to know how the maximum salary of all employees.
SELECT MAX(salary) AS "Highest Salary"
FROM employees;
In this MAX function example we've aliased the MAX(salary) expression as "Highest Salary". As a result "Highest Salary" will display as the field name when the result set is returned.
In some cases you will be required to use the GROUP BY clause with the MAX function.
For example you could also use the MAX function to return the name of the department and the maximum salary in the department.
SELECT department MAX(salary) AS "Highest salary"
FROM employees
GROUP BY department;
Because you have listed one column in your SELECT statement that is not encapsulated in the MAX function you must use a GROUP BY clause. The department field must therefore be listed in the GROUP BY section.
This MySQL tutorial explains how to use the MySQL MIN function with syntax and examples.
The MySQL MIN function returns the minimum value of an expression.
The syntax for the MIN function in MySQL is:
SELECT MIN(aggregate_expression)
FROM tables
WHERE conditions ;
OR the syntax for the MIN function when grouping the results by one or more columns is:
SELECT expression1 expression2 ... expression_n
MIN(aggregate_expression)
FROM tables
WHERE conditions
GROUP BY expression1 expression2 ... expression_n;
expression1 expression2 ... expression_n Expressions that are not encapsulated within the MIN function and must be included in the GROUP BY clause at the end of the SQL statement. aggregate_expression This is the column or expression from which the minimum value will be returned. tables The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause. WHERE conditions Optional. These are conditions that must be met for the records to be selected.
The MIN function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL MIN function examples and explore how to use the MIN function in MySQL.
For example you might wish to know how the minimum salary of all employees.
SELECT MIN(salary) AS "Lowest Salary"
FROM employees;
In this MIN function example we've aliased the MIN(salary) expression as "Lowest Salary". As a result "Lowest Salary" will display as the field name when the result set is returned.
In some cases you will be required to use the GROUP BY clause with the MIN function.
For example you could also use the MIN function to return the name of the department and the minimum salary in the department.
SELECT department MIN(salary) AS "Lowest salary"
FROM employees
GROUP BY department;
Because you have listed one column in your SELECT statement that is not encapsulated in the MIN function you must use a GROUP BY clause. The department field must therefore be listed in the GROUP BY section.
This MySQL tutorial explains how to use the MySQL MOD function with syntax and examples.
The MySQL MOD function returns the remainder of n divided by m.
The syntax for the MOD function in MySQL is:
MOD( n m )
OR
n MOD m
OR
n % m
n The value that will be divided by m. m The value that will be divided into n.
- The MOD function uses the formula of
n / m
and the remainder is what is returned. - Starting in MySQL 4.1.7 the MOD function returns the exact remainder (without any rounding).
- Before MySQL 4.1.7 the MOD function rounds the remainder to an integer value.
- The MOD function syntax of
n mod m
was introduced in MySQL 4.1.
The MOD function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL MOD function examples and explore how to use the MOD function in MySQL.
For example:
mysql> SELECT MOD(12 5);
*Result:* 2
mysql> SELECT MOD(12 0.18);
*Result:* 0.12
mysql> SELECT MOD(100 3.5938);
*Result:* 2.9674
mysql> SELECT 12 MOD 5;
*Result:* 2
mysql> SELECT 12 MOD 0.18;
*Result:* 0.12
mysql> SELECT 100 MOD 3.5938;
*Result:* 2.9674
mysql> SELECT 12 % 5;
*Result:* 2
mysql> SELECT 12 % 0.18;
*Result:* 0.12
mysql> SELECT 100 % 3.5938;
*Result:* 2.9674
This MySQL tutorial explains how to use the MySQL PI function with syntax and examples.
The MySQL PI function returns the value of π (pi) displayed with 6 decimal places.
The syntax for the PI function in MySQL is:
PI( )
There are no parameters or arguments for the PI function.
- The PI function displays the value of pi with only 6 decimal places. However internally it uses the double-precision value when used in calculations with other double-precision values.
- See also the DEGREES and RADIANS functions.
The PI function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL PI function examples and explore how to use the PI function in MySQL.
For example:
mysql> SELECT PI();
*Result:* 3.141593
mysql> SELECT PI()\*1;
*Result:* 3.141593
mysql> SELECT PI()\*1.000000000000000;
*Result:* 3.141592653589793
This MySQL tutorial explains how to use the MySQL POW function with syntax and examples.
The MySQL POW function returns m raised to the nth power.
The syntax for the POW function in MySQL is:
POW( m n )
m Numeric value. It is the base used in the calculation. n Numeric value. It is the exponent used in the calculation.
- The POWER function is a synonym for the POW function.
The POW function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL POW function examples and explore how to use the POW function in MySQL.
For example:
mysql> SELECT POW(5 2);
*Result:* 25
mysql> SELECT POW(5 -2);
*Result:* 0.04
mysql> SELECT POW(5.5 3);
*Result:* 166.375
mysql> SELECT POW(0 4);
*Result:* 0
mysql> SELECT POW(4 0);
*Result:* 1
This MySQL tutorial explains how to use the MySQL POWER function with syntax and examples.
The MySQL POWER function returns m raised to the nth power.
The syntax for the MySQL POWER function is:
POWER( m n )
m Numeric value. It is the base used in the calculation. n Numeric value. It is the exponent used in the calculation.
- The POWER function is a synonym for the POW function.
The POWER function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL POWER function examples and explore how to use the POWER function in MySQL.
For example:
mysql> SELECT POWER(6 2);
*Result:* 36
mysql> SELECT POWER(6 -2);
*Result:* 0.027777777777777776
mysql> SELECT POWER(5.4 3);
*Result:* 157.46400000000003
mysql> SELECT POWER(0 3);
*Result:* 0
mysql> SELECT POWER(3 0);
*Result:* 1
This MySQL tutorial explains how to use the MySQL RADIANS function with syntax and examples.
The MySQL RADIANS function a value in degrees to radians.
The syntax for the RADIANS function in MySQL is:
RADIANS( number )
number An angle in degrees to convert to radians.
The RADIANS function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL RADIANS function examples and explore how to use the RADIANS function in MySQL.
For example:
mysql> SELECT RADIANS(45);
*Result:* 0.7853981633974483
mysql> SELECT RADIANS(180);
*Result:* 3.141592653589793
mysql> SELECT RADIANS(0);
*Result:* 0
mysql> SELECT RADIANS(-45);
*Result:* -0.7853981633974483
This MySQL tutorial explains how to use the MySQL RAND function with syntax and examples.
The MySQL RAND function can be used to return a random number or a random number within a range.
The syntax for the RAND function in MySQL is:
RAND( seed )
seed Optional. If specified it will produce a repeatable sequence of random numbers each time that seed value is provided.
- The RAND function will return a value between 0 (inclusive) and 1 (exclusive) so value >= 0 and value < 1.
- The RAND function will return a completely random number if no seed is provided.
- The RAND function will return a repeatable sequence of random numbers each time a particular seed value is used.
To create a random decimal number between two values (range) you can use the following formula:
SELECT RAND()\*(b-a)+a;
Where a is the smallest number and b is the largest number that you want to generate a random number for.
SELECT RAND()\*(25-10)+10;
The formula above would generate a random decimal number >= 10 and < 25. (Note: this formula will never return a value of 25 because the random function will never return 1.)
To create a random integer number between two values (inclusive range) you can use the following formula:
SELECT FLOOR(RAND()\*(b-a+1))+a;
Where a is the smallest number and b is the largest number that you want to generate a random number for.
SELECT FLOOR(RAND()\*(25-10+1))+10;
The formula above would generate a random integer number between 10 and 25 inclusive.
The RAND function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's explore how to use the RAND function in MySQL to generate a random number >= 0 and < 1.
For example:
mysql> SELECT RAND();
*Result:* 0.2430297417966926 *(no seed value so your answer will vary)*
mysql> SELECT RAND(9);
*Result:* 0.406868412538309 *(with seed value of 9)*
mysql> SELECT RAND(-5);
*Result:* 0.9043048842850187 *(with seed value of -5)*
Although the RAND function will return a value of 0 it will never return a value of 1. It will always return a value smaller than 1.
Let's explore how to use the RAND function in MySQL to generate a random decimal number between two numbers (ie: range).
For example the following would generate a random decimal value that is >= 1 and < 10 (Note: it will never return a value of 10):
mysql> SELECT RAND()\*(10-1)+1;
*Result:* 3.71321560508871 *(no seed value so your answer will vary)*
mysql> SELECT RAND(9)\*(10-1)+1;
*Result:* 4.661815712844781 *(with seed value of 9)*
mysql> SELECT RAND(-5)\*(10-1)+1;
*Result:* 9.138743958565168 *(with seed value of -5)*
Let's explore how to use the RAND function in MySQL to generate a random integer number between two numbers (ie: inclusive range).
For example the following would generate a random integer value between 20 and 30:
mysql> SELECT FLOOR(RAND()\*(30-20+1))+20;
*Result:* 22 *(no seed value so your answer will vary)*
mysql> SELECT FLOOR(RAND(9)\*(30-20+1))+20;
*Result:* 24 *(with seed value of 9)*
mysql> SELECT FLOOR(RAND(-5)\*(30-20+1))+20;
*Result:* 29 *(with seed value of -5)*
This MySQL tutorial explains how to use the MySQL ROUND function with syntax and examples.
The MySQL ROUND function returns a number rounded to a certain number of decimal places.
The syntax for the ROUND function in MySQL is:
ROUND( number decimal_places )
number The number to round. decimal_places The number of decimal places to round. This value must be a positive or negative integer. If this parameter is omitted the ROUND function will round the number to 0 decimal places.
- If decimal_places is a negative number the ROUND function will make digits to the left of the decimal place 0 values.
- The behavior of the ROUND function can vary depending on the version of MySQL.
- See also the FLOOR CEIL CEILING and TRUNCATE functions.
The ROUND function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL ROUND function examples and explore how to use the ROUND function in MySQL.
For example:
mysql> SELECT ROUND(125.315);
*Result:* 125
mysql> SELECT ROUND(125.315 0);
*Result:* 125
mysql> SELECT ROUND(125.315 1);
*Result:* 125.3
mysql> SELECT ROUND(125.315 2);
*Result:* 125.32
mysql> SELECT ROUND(125.315 -1);
*Result:* 130
mysql> SELECT ROUND(125.315 -2);
*Result:* 100
mysql> SELECT ROUND(-125.315);
*Result:* -125
This MySQL tutorial explains how to use the MySQL SIGN function with syntax and examples.
The MySQL SIGN function returns a value indicating the sign of a number.
The syntax for the SIGN function in MySQL is:
SIGN( number )
number The number to test for its sign.
- The SIGN function returns -1 if the number is less than 0.
- The SIGN function returns 0 if the number is equal to 0.
- The SIGN function returns 1 if the number is greater than 0.
The SIGN function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL SIGN function examples and explore how to use the SIGN function in MySQL.
For example:
mysql> SELECT SIGN(12);
*Result:* 1
mysql> SELECT SIGN(0);
*Result:* 0
mysql> SELECT SIGN(-12);
*Result:* -1
This MySQL tutorial explains how to use the MySQL SIN function with syntax and examples.
The MySQL SIN function returns the sine of a number.
The syntax for the SIN function in MySQL is:
SIN( number )
number The value used to calculate the sine. It is expressed in radians.
The SIN function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL SIN function examples and explore how to use the SIN function in MySQL.
For example:
mysql> SELECT SIN(2);
*Result:* 0.9092974268256817
mysql> SELECT SIN(0);
*Result:* 0
mysql> SELECT SIN(-0.9);
*Result:* -0.7833269096274834
This MySQL tutorial explains how to use the MySQL SQRT function with syntax and examples.
The MySQL SQRT function returns the square root of a number.
The syntax for the SQRT function in MySQL is:
SQRT( number )
number A positive number used to calculate the square root.
- The SQRT function will return NULL if the number is a negative value.
The SQRT function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL SQRT function examples and explore how to use the SQRT function in MySQL.
For example:
mysql> SELECT SQRT(25);
*Result:* 5
mysql> SELECT SQRT(26);
*Result:* 5.0990195135927845
mysql> SELECT SQRT(0);
*Result:* 0
mysql> SELECT SQRT(-9);
*Result:* NULL
This MySQL tutorial explains how to use the MySQL SUM function with syntax and examples.
The MySQL SUM function returns the summed value of an expression.
The syntax for the SUM function in MySQL is:
SELECT SUM(aggregate_expression)
FROM tables
WHERE conditions ;
OR the syntax for the SUM function when grouping the results by one or more columns is:
SELECT expression1 expression2 ... expression_n
SUM(aggregate_expression)
FROM tables
WHERE conditions
GROUP BY expression1 expression2 ... expression_n;
expression1 expression2 ... expression_n Expressions that are not encapsulated within the SUM function and must be included in the GROUP BY clause at the end of the SQL statement. aggregate_expression This is the column or expression that will be summed. tables The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause. WHERE conditions Optional. These are conditions that must be met for the records to be selected.
The SUM function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL SUM function examples and explore how to use the SUM function in MySQL.
For example you might wish to know how the combined total salary of all employees whose salary is above $50 000 / year.
SELECT SUM(salary) AS "Total Salary"
FROM employees
WHERE salary > 50000;
In this SUM function example we've aliased the SUM(salary) expression as "Total Salary". As a result "Total Salary" will display as the field name when the result set is returned.
You can use the DISTINCT clause within the SUM function. For example the SQL statement below returns the combined total salary of unique salary values where the salary is above $50 000 / year.
SELECT SUM(DISTINCT salary) AS "Total Salary"
FROM employees
WHERE salary > 50000;
If there were two salaries of $82 000/year only one of these values would be used in the SUM function.
The expression contained within the SUM function does not need to be a single field. You could also use a formula. For example you might want to calculate the total commission.
SELECT SUM(sales \* 0.05) AS "Total Commission"
FROM orders;
In some cases you will be required to use the GROUP BY clause with the SUM function.
For example you could also use the SUM function to return the name of the department and the total sales (in the associated department).
SELECT department SUM(sales) AS "Total sales"
FROM order_details
GROUP BY department;
Because you have listed one column in your SELECT statement that is not encapsulated in the SUM function you must use a GROUP BY clause. The department field must therefore be listed in the GROUP BY section.
This MySQL tutorial explains how to use the MySQL TAN function with syntax and examples.
The MySQL TAN function returns the tangent of a number.
The syntax for the TAN function in MySQL is:
TAN( number )
number The number used to calculate the tangent. It is expressed in radians.
The TAN function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL TAN function examples and explore how to use the TAN function in MySQL.
For example:
mysql> SELECT TAN(0.75);
*Result:* 0.9315964599440725
mysql> SELECT TAN(-3);
*Result:* 0.1425465430742778
mysql> SELECT TAN(0);
*Result:* 0
This MySQL tutorial explains how to use the MySQL TRUNCATE function with syntax and examples.
The MySQL TRUNCATE function returns a number truncated to a certain number of decimal places.
The syntax for the TRUNCATE function in MySQL is:
TRUNCATE( number decimal_places )
number The number to truncate. decimal_places The number of decimal places truncate to. This value must be a positive or negative integer.
- If decimal_places is a negative number the TRUNCATE function will make digits to the left of the decimal place 0 values.
- See also the ROUND CEIL CEILING and FLOOR functions.
The TRUNCATE function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL TRUNCATE function examples and explore how to use the TRUNCATE function in MySQL.
For example:
mysql> SELECT TRUNCATE(125.315 0);
*Result:* 125
mysql> SELECT TRUNCATE(125.315 1);
*Result:* 125.3
mysql> SELECT TRUNCATE(125.315 2);
*Result:* 125.31
mysql> SELECT TRUNCATE(125.315 -1);
*Result:* 120
mysql> SELECT TRUNCATE(125.315 -2);
*Result:* 100
mysql> SELECT TRUNCATE(-125.315 0);
*Result:* -125
This MySQL tutorial explains how to use the MySQL ADDDATE function with syntax and examples.
The MySQL ADDDATE function returns a date after which a certain time/date interval has been added.
The syntax for the ADDDATE function in MySQL is:
ADDDATE( date INTERVAL value unit )
OR
ADDDATE( date days )
date The date to which the interval should be added. days The number of days to add to date (second syntax). value The value of the time/date interval that you wish to add. You can specify positive and negative values for this parameter (first syntax). unit The unit type of the interval such as DAY MONTH MINUTE HOUR and so on. It can be one of the following (first syntax):
unit | Compatibility |
---|---|
MICROSECOND | 4.1.1+ |
SECOND | 3.2.3+ |
MINUTE | 3.2.3+ |
HOUR | 3.2.3+ |
DAY | 3.2.3+ |
WEEK | 5+ |
MONTH | 3.2.3+ |
QUARTER | 5+ |
YEAR | 3.2.3+ |
SECOND_MICROSECOND | 4.1.1+ |
MINUTE_MICROSECOND | 4.1.1+ |
MINUTE_SECOND | 4.1.1+ |
HOUR_MICROSECOND | 4.1.1+ |
HOUR_SECOND | 4.1.1+ |
HOUR_MINUTE | 3.2.3+ |
DAY_MICROSECOND | 4.1.1+ |
DAY_SECOND | 3.2.3+ |
DAY_MINUTE | 3.2.3+ |
DAY_HOUR | 3.2.3+ |
YEAR_MONTH | 3.2.3+ |
- If you specify an interval value that is too short for the unit that you have specified the ADDDATE function will assume that the left-most portion of the interval value was not provided.
- The ADDDATE function (first syntax only) is a synonym for the DATE_ADD function.
- Using the ADDDATE function with a negative value as a parameter is equivalent to using the SUBDATE function.
- See also the DATE_ADD DATE_SUB SUBDATE ADDTIME and SUBTIME functions.
The ADDDATE function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL ADDDATE function examples and explore how to use the ADDDATE function in MySQL.
For example:
mysql> SELECT ADDDATE('2014-02-13 08:44:21.000001' INTERVAL 4 MICROSECOND);
*Result:* '2014-02-13 08:44:21.000005'
mysql> SELECT ADDDATE('2014-02-13 08:44:21' INTERVAL -20 SECOND);
*Result:* '2014-02-13 08:44:01'
mysql> SELECT ADDDATE('2014-02-13 08:44:21' INTERVAL 25 MINUTE);
*Result:* '2014-02-13 09:09:21'
mysql> SELECT ADDDATE('2014-02-13 08:44:21' INTERVAL -2 HOUR);
*Result:* '2014-02-13 06:44:21'
mysql> SELECT ADDDATE('2014-02-13' INTERVAL 10 DAY);
*Result:* '2014-02-23'
mysql> SELECT ADDDATE('2014-02-13' 10);
*Result:* '2014-02-23'
mysql> SELECT ADDDATE('2014-02-13' INTERVAL 12 WEEK);
*Result:* '2014-05-08'
mysql> SELECT ADDDATE('2014-02-13' INTERVAL -3 MONTH);
*Result:* '2013-11-13'
mysql> SELECT ADDDATE('2014-02-13' INTERVAL 3 QUARTER);
*Result:* '2014-11-13'
mysql> SELECT ADDDATE('2014-02-13' INTERVAL 5 YEAR);
*Result:* '2019-02-13'
mysql> SELECT ADDDATE('2014-02-13 08:44:21.000001' INTERVAL '12.000001' SECOND_MICROSECOND);
*Result:* '2014-02-13 08:44:33.000002'
mysql> SELECT ADDDATE('2014-02-13 08:44:21.000001' INTERVAL '3:12.000001' MINUTE_MICROSECOND);
*Result:* '2014-02-13 08:47:33.000002'
mysql> SELECT ADDDATE('2014-02-13 08:44:21' INTERVAL '3:12' MINUTE_SECOND);
*Result:* '2014-02-13 08:47:33'
mysql> SELECT ADDDATE('2014-02-13 08:44:21.000001' INTERVAL '1:03:12.000001' HOUR_MICROSECOND);
*Result:* '2014-02-13 09:47:33.000002'
mysql> SELECT ADDDATE('2014-02-13 08:44:21' INTERVAL '1:03:12' HOUR_SECOND);
*Result:* '2014-02-13 09:47:33'
mysql> SELECT ADDDATE('2014-02-13 08:44:21' INTERVAL '1:03' HOUR_MINUTE);
*Result:* '2014-02-13 09:47:21'
mysql> SELECT ADDDATE('2014-02-13 08:44:21.000001' INTERVAL '7 1:03:12.000001' DAY_MICROSECOND);
*Result:* '2014-02-20 09:47:33.000002'
mysql> SELECT ADDDATE('2014-02-13 08:44:21' INTERVAL '7 1:03:12' DAY_SECOND);
*Result:* '2014-02-20 09:47:33'
mysql> SELECT ADDDATE('2014-02-13 08:44:21' INTERVAL '7 1:03' DAY_MINUTE);
*Result:* '2014-02-20 09:47:21'
mysql> SELECT ADDDATE('2014-02-13 08:44:21' INTERVAL '7 1' DAY_HOUR);
*Result:* '2014-02-20 09:44:21'
mysql> SELECT ADDDATE('2014-02-13' INTERVAL '5-3' YEAR_MONTH);
*Result:* '2019-05-13'
This MySQL tutorial explains how to use the MySQL ADDTIME function with syntax and examples.
The MySQL ADDTIME function returns a time/datetime value after which a certain time interval has been added.
The syntax for the ADDTIME function in MySQL is:
ADDTIME( start_value time )
start_value The time or datetime value to which the time interval should be added. time The value of the time interval that you wish to add. It can be a positive or negative value.
- Using the ADDTIME function with a negative time value as a parameter is equivalent to using the SUBTIME function.
- See also the DATE_ADD DATE_SUB ADDDATE and SUBDATE functions.
The ADDTIME function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1.1
Let's look at some MySQL ADDTIME function examples and explore how to use the ADDTIME function in MySQL.
For example:
mysql> SELECT ADDTIME('2014-02-13 08:44:21.000001' '2.000001');
*Result:* '2014-02-13 08:44:23.000002'
mysql> SELECT ADDTIME('2014-02-13 08:44:21.000001' '3:2.000001');
*Result:* '2014-02-13 11:46:21.000002'
mysql> SELECT ADDTIME('2014-02-13 08:44:21.000001' '4:3:2.000001');
*Result:* '2014-02-13 12:47:23.000002'
mysql> SELECT ADDTIME('2014-02-13 08:44:21.000001' '5 4:3:2.000001');
*Result:* '2014-02-18 12:47:23.000002'
mysql> SELECT ADDTIME('01:15:23.999998' '0.000001');
*Result:* '01:15:23.999999'
mysql> SELECT ADDTIME('01:15:23.999998' '5.000001');
*Result:* '01:15:28.999999'
mysql> SELECT ADDTIME('01:15:23.000001' '8:12:15.003441');
*Result:* '09:27:38.003442'
mysql> SELECT ADDTIME('01:15:23.000001' '-8:12:15.003441');
*Result:* '-06:56:52.003440'
This MySQL tutorial explains how to use the MySQL CURDATE function with syntax and examples.
The MySQL CURDATE function returns the current date.
The syntax for the CURDATE function in MySQL is:
CURDATE( )
There are no parameters or arguments for the CURDATE function.
- The CURDATE function will return the current date as a 'YYYY-MM-DD' format if used in a string context.
- The CURDATE function will return the current date as a YYYYMMDD format if used in a numeric context.
- The CURRENT_DATE function is a synonym for the CURDATE function.
The CURDATE function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL CURDATE function examples and explore how to use the CURDATE function in MySQL.
For example:
mysql> SELECT CURDATE();
*Result:* '2014-01-28'
mysql> SELECT CURDATE() + 0;
*Result:* 20140128
mysql> SELECT CURDATE() + 1;
*Result:* 20140129
This MySQL tutorial explains how to use the MySQL CURRENT_DATE function with syntax and examples.
The MySQL CURRENT_DATE function returns the current date.
The syntax for the CURRENT_DATE function in MySQL is:
CURRENT_DATE( )
There are no parameters or arguments for the CURRENT_DATE function.
- The CURRENT_DATE function will return the current date as a 'YYYY-MM-DD' format if used in a string context.
- The CURRENT_DATE function will return the current date as a YYYYMMDD format if used in a numeric context.
- The CURRENT_DATE function is a synonym for the CURDATE function.
The CURRENT_DATE function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL CURRENT_DATE function examples and explore how to use the CURRENT_DATE function in MySQL.
For example:
mysql> SELECT CURRENT_DATE();
*Result:* '2014-01-28'
mysql> SELECT CURRENT_DATE() + 0;
*Result:* 20140128
mysql> SELECT CURRENT_DATE() + 1;
*Result:* 20140129
This MySQL tutorial explains how to use the MySQL CURRENT_TIME function with syntax and examples.
The MySQL CURRENT_TIME function returns the current time.
The syntax for the CURRENT_TIME function in MySQL is:
CURRENT_TIME( )
There are no parameters or arguments for the CURRENT_TIME function.
- The CURRENT_TIME function will return the current date as a 'HH:MM:SS' format if used in a string context.
- The CURRENT_TIME function will return the current date as a HHMMSS format if used in a numeric context in versions of MySQL prior to MySQL 4.1.13.
- The CURRENT_TIME function will return the current date as a HHMMSS.uuuuuu format if used in a numeric context in versions of MySQL 4.1.13 and newer.
- The CURRENT_TIME function is a synonym for the CURTIME function.
The CURRENT_TIME function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL CURRENT_TIME function examples and explore how to use the CURRENT_TIME function in MySQL.
For example:
mysql> SELECT CURRENT_TIME();
*Result:* '10:37:02'
mysql> SELECT CURRENT_TIME() + 0;
*Result:* 103702.000000
mysql> SELECT CURRENT_TIME() + 1;
*Result:* 103703.000000
This MySQL tutorial explains how to use the MySQL CURRENT_TIMESTAMP function with syntax and examples.
The MySQL CURRENT_TIMESTAMP function returns the current date and time.
The syntax for the CURRENT_TIMESTAMP function in MySQL is:
CURRENT_TIMESTAMP( )
There are no parameters or arguments for the CURRENT_TIMESTAMP function.
- The CURRENT_TIMESTAMP function will return the current date as a 'YYYY-MM-DD HH:MM:SS' format if used in a string context.
- The CURRENT_TIMESTAMP function will return the current date as a YYYYMMDDHHMMSS format if used in a numeric context in versions of MySQL prior to MySQL 4.1.13.
- The CURRENT_TIMESTAMP function will return the current date as a YYYYMMDDHHMMSS.uuuuuu format if used in a numeric context in versions of MySQL 4.1.13 and newer.
- The CURRENT_TIMESTAMP LOCALTIME and LOCALTIMESTAMP functions are synonyms for the NOW function.
The CURRENT_TIMESTAMP function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL CURRENT_TIMESTAMP function examples and explore how to use the CURRENT_TIMESTAMP function in MySQL.
For example:
mysql> SELECT CURRENT_TIMESTAMP();
*Result:* '2014-01-28 13:48:41'
mysql> SELECT CURRENT_TIMESTAMP() + 0;
*Result:* 20140128134841.000000
mysql> SELECT CURRENT_TIMESTAMP() + 1;
*Result:* 20140128134842.000000
This MySQL tutorial explains how to use the MySQL CURTIME function with syntax and examples.
The MySQL CURTIME function returns the current time.
The syntax for the CURTIME function in MySQL is:
CURTIME( )
There are no parameters or arguments for the CURTIME function.
- The CURTIME function will return the current date as a 'HH:MM:SS' format if used in a string context.
- The CURTIME function will return the current date as a HHMMSS format if used in a numeric context in versions of MySQL prior to MySQL 4.1.13.
- The CURTIME function will return the current date as a HHMMSS.uuuuuu format if used in a numeric context in versions of MySQL 4.1.13 and newer.
- The CURRENT_TIME function is a synonym for the CURTIME function.
The CURTIME function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL CURTIME function examples and explore how to use the CURTIME function in MySQL.
For example:
mysql> SELECT CURTIME();
*Result:* '10:37:02'
mysql> SELECT CURTIME() + 0;
*Result:* 103702.000000
mysql> SELECT CURTIME() + 1;
*Result:* 103703.000000
This MySQL tutorial explains how to use the MySQL DATE function with syntax and examples.
The MySQL DATE function extracts the date value from a date or datetime expression.
The syntax for the DATE function in MySQL is:
DATE( expression )
expression The date or datetime value from which the date should be extracted.
- If expression is not a date or a datetime value the DATE function will return NULL.
- See also the CAST function.
The DATE function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1.1
Let's look at some MySQL DATE function examples and explore how to use the DATE function in MySQL.
For example:
mysql> SELECT DATE('2014-02-14');
*Result:* '2014-02-14'
mysql> SELECT DATE('2014-02-14 18:20:19');
*Result:* '2014-02-14'
mysql> SELECT DATE('2014-02-15 06:18:01.000001');
*Result:* '2014-02-15'
mysql> SELECT DATE('The date is 2014-02-14');
*Result:* NULL
mysql> SELECT DATE(NULL);
*Result:* NULL
This MySQL tutorial explains how to use the MySQL DATE_ADD function with syntax and examples.
The MySQL DATE_ADD function returns a date after which a certain time/date interval has been added.
The syntax for the DATE_ADD function in MySQL is:
DATE_ADD( date INTERVAL value unit )
date The date to which the interval should be added. value The value of the time/date interval that you wish to add. You can specify positive and negative values for this parameter. unit The unit type of the interval such as DAY MONTH MINUTE HOUR and so on. It can be one of the following:
unit | Compatibility |
---|---|
MICROSECOND | 4.1.1+ |
SECOND | 3.2.3+ |
MINUTE | 3.2.3+ |
HOUR | 3.2.3+ |
DAY | 3.2.3+ |
WEEK | 5+ |
MONTH | 3.2.3+ |
QUARTER | 5+ |
YEAR | 3.2.3+ |
SECOND_MICROSECOND | 4.1.1+ |
MINUTE_MICROSECOND | 4.1.1+ |
MINUTE_SECOND | 4.1.1+ |
HOUR_MICROSECOND | 4.1.1+ |
HOUR_SECOND | 4.1.1+ |
HOUR_MINUTE | 3.2.3+ |
DAY_MICROSECOND | 4.1.1+ |
DAY_SECOND | 3.2.3+ |
DAY_MINUTE | 3.2.3+ |
DAY_HOUR | 3.2.3+ |
YEAR_MONTH | 3.2.3+ |
- If you specify an interval value that is too short for the unit that you have specified the DATE_ADD function will assume that the left-most portion of the interval value was not provided.
- Using the DATE_ADD function with a negative value as a parameter is equivalent to using the DATE_SUB function.
- See also the DATE_SUB ADDDATE SUBDATE ADDTIME and SUBTIME functions.
The DATE_ADD function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL DATE_ADD function examples and explore how to use the DATE_ADD function in MySQL.
For example:
mysql> SELECT DATE_ADD('2014-02-13 08:44:21.000001' INTERVAL 4 MICROSECOND);
*Result:* '2014-02-13 08:44:21.000005'
mysql> SELECT DATE_ADD('2014-02-13 08:44:21' INTERVAL -20 SECOND);
*Result:* '2014-02-13 08:44:01'
mysql> SELECT DATE_ADD('2014-02-13 08:44:21' INTERVAL 25 MINUTE);
*Result:* '2014-02-13 09:09:21'
mysql> SELECT DATE_ADD('2014-02-13 08:44:21' INTERVAL -2 HOUR);
*Result:* '2014-02-13 06:44:21'
mysql> SELECT DATE_ADD('2014-02-13' INTERVAL 10 DAY);
*Result:* '2014-02-23'
mysql> SELECT DATE_ADD('2014-02-13' INTERVAL 12 WEEK);
*Result:* '2014-05-08'
mysql> SELECT DATE_ADD('2014-02-13' INTERVAL -3 MONTH);
*Result:* '2013-11-13'
mysql> SELECT DATE_ADD('2014-02-13' INTERVAL 3 QUARTER);
*Result:* '2014-11-13'
mysql> SELECT DATE_ADD('2014-02-13' INTERVAL 5 YEAR);
*Result:* '2019-02-13'
mysql> SELECT DATE_ADD('2014-02-13 08:44:21.000001' INTERVAL '12.000001' SECOND_MICROSECOND);
*Result:* '2014-02-13 08:44:33.000002'
mysql> SELECT DATE_ADD('2014-02-13 08:44:21.000001' INTERVAL '3:12.000001' MINUTE_MICROSECOND);
*Result:* '2014-02-13 08:47:33.000002'
mysql> SELECT DATE_ADD('2014-02-13 08:44:21' INTERVAL '3:12' MINUTE_SECOND);
*Result:* '2014-02-13 08:47:33'
mysql> SELECT DATE_ADD('2014-02-13 08:44:21.000001' INTERVAL '1:03:12.000001' HOUR_MICROSECOND);
*Result:* '2014-02-13 09:47:33.000002'
mysql> SELECT DATE_ADD('2014-02-13 08:44:21' INTERVAL '1:03:12' HOUR_SECOND);
*Result:* '2014-02-13 09:47:33'
mysql> SELECT DATE_ADD('2014-02-13 08:44:21' INTERVAL '1:03' HOUR_MINUTE);
*Result:* '2014-02-13 09:47:21'
mysql> SELECT DATE_ADD('2014-02-13 08:44:21.000001' INTERVAL '7 1:03:12.000001' DAY_MICROSECOND);
*Result:* '2014-02-20 09:47:33.000002'
mysql> SELECT DATE_ADD('2014-02-13 08:44:21' INTERVAL '7 1:03:12' DAY_SECOND);
*Result:* '2014-02-20 09:47:33'
mysql> SELECT DATE_ADD('2014-02-13 08:44:21' INTERVAL '7 1:03' DAY_MINUTE);
*Result:* '2014-02-20 09:47:21'
mysql> SELECT DATE_ADD('2014-02-13 08:44:21' INTERVAL '7 1' DAY_HOUR);
*Result:* '2014-02-20 09:44:21'
mysql> SELECT DATE_ADD('2014-02-13' INTERVAL '5-3' YEAR_MONTH);
*Result:* '2019-05-13'
This MySQL tutorial explains how to use the MySQL DATE_FORMAT function with syntax and examples.
The MySQL DATE_FORMAT function formats a date as specified by a format mask.
The syntax for the DATE_FORMAT function in MySQL is:
DATE_FORMAT( date format_mask )
date The date to format. format_mask The format to apply to date. The following is a list of options for the format_mask parameter. These parameters can be used in many combinations.
Value | Description |
---|---|
%a | Weekday name abbreviated (Sun to Sat) |
%b | Month name abbreviated (Jan to Dec) |
%c | Month as a numeric value (0 to 12) |
%D | Day of the month as a numeric value followed by suffix (1st 2nd 3rd ...) |
%d | Day of the month as a numeric value (01 to 31) |
%e | Day of the month as a numeric value (0 to 31) |
%f | Microseconds (000000 to 999999) |
%f is available starting in MySQL 4.1.1 | |
%H | Hour (00 to 23) |
%h | Hour (00 to 12) |
%I | Hour (00 to 12) |
%i | Minutes (00 to 59) |
%j | Day of the year (001 to 366) |
%k | Hour (00 to 23) |
%l | Hour (1 to 12) |
%M | Month name in full (January to December) |
%m | Month name as a numeric value (00 to 12) |
%p | AM or PM |
%r | Time in 12 hour AM or PM format (hh:mm:ss AM/PM) |
%S | Seconds (00 to 59) |
%s | Seconds (00 to 59) |
%T | Time in 24 hour format (hh:mm:ss) |
%U | Week where Sunday is the first day of the week (00 to 53) |
%u | Week where Monday is the first day of the week (00 to 53) |
%V | Week where Sunday is the first day of the week (01 to 53) |
Available starting in MySQL 3.23.8 and used with %X | |
%v | Week where Monday is the first day of the week (01 to 53) |
Available starting in MySQL 3.23.8 and used with %X | |
%W | Weekday name in full (Sunday to Saturday) |
%w | Day of the week where Sunday=0 and Saturday=6 |
%X | Year for the week where Sunday is the first day of the week |
Available starting in MySQL 3.23.8 and used with %V | |
%x | Year for the week where Monday is the first day of the week |
Available starting in MySQL 3.23.8 and used with %v | |
%Y | Year as a numeric 4-digit value |
%y | Year as a numeric 2-digit value |
- Day and month ranges start at 00 as MySQL allows dates to be stored incomplete. For example: '2013-00-00'.
- See also the TIME_FORMAT function.
The DATE_FORMAT function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL DATE_FORMAT function examples and explore how to use the DATE_FORMAT function in MySQL.
For example:
mysql> SELECT DATE_FORMAT('2014-02-28' '%Y');
*Result:* '2014'
mysql> SELECT DATE_FORMAT('2014-02-01' '%M %d %Y');
*Result:* 'February 01 2014'
mysql> SELECT DATE_FORMAT('2014-02-01' '%M %e %Y');
*Result:* 'February 1 2014'
mysql> SELECT DATE_FORMAT('2014-02-28' '%W %M %e %Y');
*Result:* 'Friday February 28 2014'
mysql> SELECT DATE_FORMAT('2014-02-28' '%W');
*Result:* 'Friday'
This MySQL tutorial explains how to use the MySQL DATE_SUB function with syntax and examples.
The MySQL DATE_SUB function returns a date after which a certain time/date interval has been subtracted.
The syntax for the DATE_SUB function in MySQL is:
DATE_SUB( date INTERVAL value unit )
date The date to which the interval should be subtracted. value The value of the time/date interval that you wish to subtract. You can specify positive and negative values for this parameter. unit The unit type of the interval such as DAY MONTH MINUTE HOUR and so on. It can be one of the following:
unit | Compatibility |
---|---|
MICROSECOND | 4.1.1+ |
SECOND | 3.2.3+ |
MINUTE | 3.2.3+ |
HOUR | 3.2.3+ |
DAY | 3.2.3+ |
WEEK | 5+ |
MONTH | 3.2.3+ |
QUARTER | 5+ |
YEAR | 3.2.3+ |
SECOND_MICROSECOND | 4.1.1+ |
MINUTE_MICROSECOND | 4.1.1+ |
MINUTE_SECOND | 4.1.1+ |
HOUR_MICROSECOND | 4.1.1+ |
HOUR_SECOND | 4.1.1+ |
HOUR_MINUTE | 3.2.3+ |
DAY_MICROSECOND | 4.1.1+ |
DAY_SECOND | 3.2.3+ |
DAY_MINUTE | 3.2.3+ |
DAY_HOUR | 3.2.3+ |
YEAR_MONTH | 3.2.3+ |
- If you specify an interval value that is too short for the unit that you have specified the DATE_SUB function will assume that the left-most portion of the interval value was not provided.
- Using the DATE_SUB function with a negative value as a parameter is equivalent to using the DATE_ADD function.
- See also the DATE_ADD ADDDATE SUBDATE ADDTIME and SUBTIME functions.
The DATE_SUB function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL DATE_SUB function examples and explore how to use the DATE_SUB function in MySQL.
For example:
mysql> SELECT DATE_SUB('2014-02-13 08:44:21.000001' INTERVAL 4 MICROSECOND);
*Result:* '2014-02-13 08:44:20.999997'
mysql> SELECT DATE_SUB('2014-02-13 08:44:21' INTERVAL 20 SECOND);
*Result:* '2014-02-13 08:44:01'
mysql> SELECT DATE_SUB('2014-02-13 08:44:21' INTERVAL 25 MINUTE);
*Result:* '2014-02-13 08:19:21'
mysql> SELECT DATE_SUB('2014-02-13 08:44:21' INTERVAL 2 HOUR);
*Result:* '2014-02-13 06:44:21'
mysql> SELECT DATE_SUB('2014-02-13' INTERVAL 10 DAY);
*Result:* '2014-02-03'
mysql> SELECT DATE_SUB('2014-02-13' INTERVAL 12 WEEK);
*Result:* '2013-11-21'
mysql> SELECT DATE_SUB('2014-02-13' INTERVAL 3 MONTH);
*Result:* '2013-11-13'
mysql> SELECT DATE_SUB('2014-02-13' INTERVAL 3 QUARTER);
*Result:* '2013-05-13'
mysql> SELECT DATE_SUB('2014-02-13' INTERVAL 5 YEAR);
*Result:* '2009-02-13'
mysql> SELECT DATE_SUB('2014-02-13 08:44:21.000001' INTERVAL '12.000001' SECOND_MICROSECOND);
*Result:* '2014-02-13 08:44:09'
mysql> SELECT DATE_SUB('2014-02-13 08:44:21.000001' INTERVAL '3:12.000001' MINUTE_MICROSECOND);
*Result:* '2014-02-13 08:41:09'
mysql> SELECT DATE_SUB('2014-02-13 08:44:21' INTERVAL '3:12' MINUTE_SECOND);
*Result:* '2014-02-13 08:41:09'
mysql> SELECT DATE_SUB('2014-02-13 08:44:21.000001' INTERVAL '1:03:12.000001' HOUR_MICROSECOND);
*Result:* '2014-02-13 07:41:09'
mysql> SELECT DATE_SUB('2014-02-13 08:44:21' INTERVAL '1:03:12' HOUR_SECOND);
*Result:* '2014-02-13 07:41:09'
mysql> SELECT DATE_SUB('2014-02-13 08:44:21' INTERVAL '1:03' HOUR_MINUTE);
*Result:* '2014-02-13 07:41:21'
mysql> SELECT DATE_SUB('2014-02-13 08:44:21.000001' INTERVAL '7 1:03:12.000001' DAY_MICROSECOND);
*Result:* '2014-02-06 07:41:09'
mysql> SELECT DATE_SUB('2014-02-13 08:44:21' INTERVAL '7 1:03:12' DAY_SECOND);
*Result:* '2014-02-06 07:41:09'
mysql> SELECT DATE_SUB('2014-02-13 08:44:21' INTERVAL '7 1:03' DAY_MINUTE);
*Result:* '2014-02-06 07:41:21'
mysql> SELECT DATE_SUB('2014-02-13 08:44:21' INTERVAL '7 1' DAY_HOUR);
*Result:* '2014-02-06 07:44:21'
mysql> SELECT DATE_SUB('2014-02-13' INTERVAL '5-3' YEAR_MONTH);
*Result:* '2008-11-13'
This MySQL tutorial explains how to use the MySQL DATEDIFF function with syntax and examples.
The MySQL DATEDIFF function returns the difference in days between two date values.
The syntax for the DATEDIFF function in MySQL is:
DATEDIFF( date1 date2 )
date1 and date2
The two dates to calculate the difference between. The calculation is date1 - date2
.
- Only the date portion of date1 and date2 is used in the DATEDIFF calculation. The time portion of date1 and date2 is ignored.
The DATEDIFF function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1.1
Let's look at some MySQL DATEDIFF function examples and explore how to use the DATEDIFF function in MySQL.
For example:
mysql> SELECT DATEDIFF('2014-01-28' '2014-01-27');
*Result:* 1
mysql> SELECT DATEDIFF('2014-01-28 11:41:14' '2014-01-27 12:10:08');
*Result:* 1
mysql> SELECT DATEDIFF('2014-01-28 11:41:14' '2014-01-27');
*Result:* 1
mysql> SELECT DATEDIFF('2014-02-15' '2014-02-10');
*Result:* 5
mysql> SELECT DATEDIFF('2014-01-28' '2013-12-31');
*Result:* 28
mysql> SELECT DATEDIFF('2013-12-31' '2014-01-28');
*Result:* -28
This last DATEDIFF example would display the difference between current system date and '2014-02-14' (current system date is returned by the CURDATE function).
mysql> SELECT DATEDIFF(CURDATE() '2014-02-14');
This MySQL tutorial explains how to use the MySQL DAY function with syntax and examples.
The MySQL DAY function returns the day portion of a date value.
The syntax for the DAY function in MySQL is:
DAY( date_value )
date_value The date or datetime value from which to extract the day.
- The DAY function returns the day of the month (a number from 1 to 31) given a date value.
- The DAY function is a synonym for the DAYOFMONTH function.
- See also the EXTRACT YEAR QUARTER MONTH WEEK HOUR MINUTE SECOND and MICROSECOND functions.
The DAY function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL DAY function examples and explore how to use the DAY function in MySQL.
For example:
mysql> SELECT DAY('2014-01-28');
*Result:* 28
mysql> SELECT DAY('2014-01-28 15:21:05');
*Result:* 28
mysql> SELECT DAY('2013-10-15');
*Result:* 15
This last DAY example would display the day portion of the current system date (current system date is returned by the CURDATE function).
mysql> SELECT DAY(CURDATE());
This MySQL tutorial explains how to use the MySQL DAYNAME function with syntax and examples.
The MySQL DAYNAME function returns the weekday name for a date.
The syntax for the DAYNAME function in MySQL is:
DAYNAME( date_value )
date_value The date or datetime value from which to extract the weekday name.
- The DAYNAME function returns the name of the weekday (Sunday Monday Tuesday etc.) given a date value.
- See also the WEEKDAY function.
The DAYNAME function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL DAYNAME function examples and explore how to use the DAYNAME function in MySQL.
For example:
mysql> SELECT DAYNAME('2014-01-27');
*Result:* 'Monday'
mysql> SELECT DAYNAME('2014-01-28');
*Result:* 'Tuesday'
mysql> SELECT DAYNAME('2014-01-29 08:35:17');
*Result:* 'Wednesday'
This last DAYNAME example would display the weekday name for the current system date (current system date is returned by the CURDATE function).
mysql> SELECT DAYNAME(CURDATE());
This MySQL tutorial explains how to use the MySQL DAYOFMONTH function with syntax and examples.
The MySQL DAYOFMONTH function returns the day portion of a date value.
The syntax for the DAYOFMONTH function in MySQL is:
DAYOFMONTH( date_value )
date_value The date or datetime value from which to extract the day of the month.
- The DAYOFMONTH function returns the day of the month (a number from 1 to 31) given a date value.
- The DAY function is a synonym for the DAYOFMONTH function.
The DAYOFMONTH function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL DAYOFMONTH function examples and explore how to use the DAYOFMONTH function in MySQL.
For example:
mysql> SELECT DAYOFMONTH('2014-01-28');
*Result:* 28
mysql> SELECT DAYOFMONTH('2014-01-28 15:21:05');
*Result:* 28
mysql> SELECT DAYOFMONTH('2013-10-15');
*Result:* 15
This last DAYOFMONTH example would display the day portion of the current system date (current system date is returned by the CURDATE function).
mysql> SELECT DAYOFMONTH(CURDATE());
This MySQL tutorial explains how to use the MySQL DAYOFWEEK function with syntax and examples.
The MySQL DAYOFWEEK function returns the weekday index for a date value.
The syntax for the DAYOFWEEK function in MySQL is:
DAYOFWEEK( date_value )
date_value The date or datetime value from which to extract the day of the week.
- The DAYOFWEEK function returns the weekday index where 1=Sunday 2=Monday 3=Tuesday 4=Wednesday 5=Thursday 6=Friday 7=Saturday.
The DAYOFWEEK function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL DAYOFWEEK function examples and explore how to use the DAYOFWEEK function in MySQL.
For example:
mysql> SELECT DAYOFWEEK('2014-01-27');
*Result:* 2
mysql> SELECT DAYOFWEEK('2014-01-28');
*Result:* 3
mysql> SELECT DAYOFWEEK('2014-01-29');
*Result:* 4
This last DAYOFWEEK example would display the weekday index for the current system date (current system date is returned by the CURDATE function).
mysql> SELECT DAYOFWEEK(CURDATE());
This MySQL tutorial explains how to use the MySQL DAYOFYEAR function with syntax and examples.
The MySQL DAYOFYEAR function returns day of the year for a date value.
The syntax for the DAYOFYEAR function in MySQL is:
DAYOFYEAR( date_value )
date_value The date or datetime value from which to extract the day of year.
- The DAYOFYEAR function returns the day of the year (a number from 1 to 366) given a date value.
The DAYOFYEAR function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL DAYOFYEAR function examples and explore how to use the DAYOFYEAR function in MySQL.
For example:
mysql> SELECT DAYOFYEAR('2014-01-01');
*Result:* 1
mysql> SELECT DAYOFYEAR('2014-02-28');
*Result:* 59
mysql> SELECT DAYOFYEAR('2014-12-31');
*Result:* 365
This last DAYOFYEAR example would display the day of the year for the current system date (current system date is returned by the CURDATE function).
mysql> SELECT DAYOFYEAR(CURDATE());
This MySQL tutorial explains how to use the MySQL EXTRACT function with syntax and examples.
The MySQL EXTRACT function extracts parts from a date.
The syntax for the MySQL EXTRACT function is:
EXTRACT( unit FROM date )
date The date or datetime value from which the date part is to be extracted. unit The unit type of the interval such as DAY MONTH MINUTE HOUR and so on. It can be one of the following:
unit | Compatibility |
---|---|
MICROSECOND | 4.1.1+ |
SECOND | 3.2.3+ |
MINUTE | 3.2.3+ |
HOUR | 3.2.3+ |
DAY | 3.2.3+ |
WEEK | 5+ |
MONTH | 3.2.3+ |
QUARTER | 5+ |
YEAR | 3.2.3+ |
SECOND_MICROSECOND | 4.1.1+ |
MINUTE_MICROSECOND | 4.1.1+ |
MINUTE_SECOND | 4.1.1+ |
HOUR_MICROSECOND | 4.1.1+ |
HOUR_SECOND | 4.1.1+ |
HOUR_MINUTE | 3.2.3+ |
DAY_MICROSECOND | 4.1.1+ |
DAY_SECOND | 3.2.3+ |
DAY_MINUTE | 3.2.3+ |
DAY_HOUR | 3.2.3+ |
YEAR_MONTH | 3.2.3+ |
The EXTRACT function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL EXTRACT function examples and explore how to use the EXTRACT function in MySQL.
For example:
mysql> SELECT EXTRACT(MICROSECOND FROM '2014-02-13 08:44:21.000001');
*Result:* 1
mysql> SELECT EXTRACT(SECOND FROM '2014-02-13 08:44:21');
*Result:* 21
mysql> SELECT EXTRACT(MINUTE FROM '2014-02-13 08:44:21');
*Result:* 44
mysql> SELECT EXTRACT(HOUR FROM '2014-02-13 08:44:21');
*Result:* 8
mysql> SELECT EXTRACT(DAY FROM '2014-02-13');
*Result:* 13
mysql> SELECT EXTRACT(WEEK FROM '2014-02-13');
*Result:* 6
mysql> SELECT EXTRACT(MONTH FROM '2014-02-13');
*Result:* 2
mysql> SELECT EXTRACT(QUARTER FROM '2014-02-13');
*Result:* 1
mysql> SELECT EXTRACT(YEAR FROM '2014-02-13');
*Result:* 2014
mysql> SELECT EXTRACT(SECOND_MICROSECOND FROM '2014-02-13 08:44:21.000001');
*Result:* 21000001
mysql> SELECT EXTRACT(MINUTE_MICROSECOND FROM '2014-02-13 08:44:21.000001');
*Result:* 4421000001
mysql> SELECT EXTRACT(MINUTE_SECOND FROM '2014-02-13 08:44:21');
*Result:* 4421
mysql> SELECT EXTRACT(HOUR_MICROSECOND FROM '2014-02-13 08:44:21.000001');
*Result:* 84421000001
mysql> SELECT EXTRACT(HOUR_SECOND FROM '2014-02-13 08:44:21');
*Result:* 84421
mysql> SELECT EXTRACT(HOUR_MINUTE FROM '2014-02-13 08:44:21');
*Result:* 844
mysql> SELECT EXTRACT(DAY_MICROSECOND FROM '2014-02-13 08:44:21.000001');
*Result:* 13084421000001
mysql> SELECT EXTRACT(DAY_SECOND FROM '2014-02-13 08:44:21');
*Result:* 13084421
mysql> SELECT EXTRACT(DAY_MINUTE FROM '2014-02-13 08:44:21');
*Result:* 130844
mysql> SELECT EXTRACT(DAY_HOUR FROM '2014-02-13 08:44:21');
*Result:* 1308
mysql> SELECT EXTRACT(YEAR_MONTH FROM '2014-02-13');
*Result:* 201402
This MySQL tutorial explains how to use the MySQL FROM_DAYS function with syntax and examples.
The MySQL FROM_DAYS function takes a numeric representation of the day and returns a date value.
The syntax for the FROM_DAYS function in MySQL is:
FROM_DAYS( numeric_day )
numeric_day The numeric day to convert to a date.
- The FROM_DAYS function is to be used only with dates within the Gregorian calendar.
- See also the TO_DAYS function which is the reverse of the FROM_DAYS function.
The FROM_DAYS function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL FROM_DAYS function examples and explore how to use the FROM_DAYS function in MySQL.
For example:
mysql> SELECT FROM_DAYS(736038);
*Result:* 2015-03-16
mysql> SELECT FROM_DAYS(736039);
*Result:* 2015-03-17
mysql> SELECT FROM_DAYS(736040);
*Result:* 2015-03-18
This MySQL tutorial explains how to use the MySQL HOUR function with syntax and examples.
The MySQL HOUR function returns the hour portion of a date value.
The syntax for the HOUR function in MySQL is:
HOUR( date_value )
date_value The time or datetime value from which to extract the hour.
- The HOUR function returns the hour (a number ranging from 0 to 838) given a date value.
- Since a time value can range from -838:59:59' to '838:59:59' the HOUR function can return values up to 838 (ie: higher than 23).
- See also the EXTRACT YEAR QUARTER MONTH WEEK DAY MINUTE SECOND and MICROSECOND functions.
The HOUR function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL HOUR function examples and explore how to use the HOUR function in MySQL.
For example:
mysql> SELECT HOUR('2014-01-28 07:47:18.000004');
*Result:* 7
mysql> SELECT HOUR('2014-01-28 15:21:05');
*Result:* 15
mysql> SELECT HOUR('12:13:06');
*Result:* 12
mysql> SELECT HOUR('838:59:59');
*Result:* 838
This last HOUR example would display the hour portion of the current system time (current system time is returned by the CURTIME function).
mysql> SELECT HOUR(CURTIME());
This MySQL tutorial explains how to use the MySQL LAST_DAY function with syntax and examples.
The MySQL LAST_DAY function returns the last day of the month for a given date.
The syntax for the LAST_DAY function in MySQL is:
LAST_DAY( date_value )
date_value The date or datetime value from which to extract the last day of the month.
- If date_value is not a valid date or datetime value the LAST_DAY function would return NULL.
The LAST_DAY function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1.1
Let's look at some MySQL LAST_DAY function examples and explore how to use the LAST_DAY function in MySQL.
For example:
mysql> SELECT LAST_DAY('2014-01-13');
*Result:* '2014-01-31'
mysql> SELECT LAST_DAY('2014-02-09 08:21:05');
*Result:* '2014-02-28'
mysql> SELECT LAST_DAY('2016-02-17');
*Result:* '2016-02-29'
mysql> SELECT LAST_DAY('2014-3-15');
*Result:* '2014-03-31'
mysql> SELECT LAST_DAY('techonthenet.com: 2014-2-16');
*Result:* NULL
This last LAST_DAY example would display the last day of the month for the current system date (current system date is returned by the CURDATE function).
mysql> SELECT LAST_DAY(CURDATE());
This MySQL tutorial explains how to use the MySQL LOCALTIME function with syntax and examples.
The MySQL LOCALTIME function returns the current date and time.
The syntax for the LOCALTIME function in MySQL is:
LOCALTIME( )
There are no parameters or arguments for the LOCALTIME function.
- The LOCALTIME function will return the current date as a 'YYYY-MM-DD HH:MM:SS' format if used in a string context.
- The LOCALTIME function will return the current date as a YYYYMMDDHHMMSS format if used in a numeric context in versions of MySQL prior to MySQL 4.1.13.
- The LOCALTIME function will return the current date as a YYYYMMDDHHMMSS.uuuuuu format if used in a numeric context in versions of MySQL 4.1.13 and newer.
- The LOCALTIME CURRENT_TIMESTAMP and LOCALTIMESTAMP functions are synonyms for the NOW function.
The LOCALTIME function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL LOCALTIME function examples and explore how to use the LOCALTIME function in MySQL.
For example:
mysql> SELECT LOCALTIME();
*Result:* '2014-02-16 08:56:05'
mysql> SELECT LOCALTIME() + 0;
*Result:* 20140216085605.000000
mysql> SELECT LOCALTIME() + 1;
*Result:* 20140216085606.000000
This MySQL tutorial explains how to use the MySQL LOCALTIMESTAMP function with syntax and examples.
The MySQL LOCALTIMESTAMP function returns the current date and time.
The syntax for the LOCALTIMESTAMP function in MySQL is:
LOCALTIMESTAMP( )
There are no parameters or arguments for the LOCALTIMESTAMP function.
- The LOCALTIMESTAMP function will return the current date as a 'YYYY-MM-DD HH:MM:SS' format if used in a string context.
- The LOCALTIMESTAMP function will return the current date as a YYYYMMDDHHMMSS format if used in a numeric context in versions of MySQL prior to MySQL 4.1.13.
- The LOCALTIMESTAMP function will return the current date as a YYYYMMDDHHMMSS.uuuuuu format if used in a numeric context in versions of MySQL 4.1.13 and newer.
- The LOCALTIMESTAMP CURRENT_TIMESTAMP and LOCALTIME functions are synonyms for the NOW function.
The LOCALTIMESTAMP function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0.6
Let's look at some MySQL LOCALTIMESTAMP function examples and explore how to use the LOCALTIMESTAMP function in MySQL.
For example:
mysql> SELECT LOCALTIMESTAMP();
*Result:* '2014-02-16 09:00:35'
mysql> SELECT LOCALTIMESTAMP() + 0;
*Result:* 20140216090035.000000
mysql> SELECT LOCALTIMESTAMP() + 1;
*Result:* 20140216090036.000000
This MySQL tutorial explains how to use the MySQL MAKEDATE function with syntax and examples.
The MySQL MAKEDATE function returns the date for a certain year and day-of-year value.
The syntax for the MySQL MAKEDATE function is:
MAKEDATE( year day-of-year )
year The 4-digit year used to create the date. day-of-year The day of the year (greater than 0) used to create the date.
- If day-of-year is less than 1 the MAKEDATE function will return NULL.
The MAKEDATE function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1.1
Let's look at some MySQL MAKEDATE function examples and explore how to use the MAKEDATE function in MySQL.
For example:
mysql> SELECT MAKEDATE(2014 1);
-> '2014-01-01'
mysql> SELECT MAKEDATE(2014 31);
-> '2014-01-31'
mysql> SELECT MAKEDATE(2014 32);
-> '2014-02-01'
mysql> SELECT MAKEDATE(2014 200);
-> '2014-07-19'
mysql> SELECT MAKEDATE(2014 365);
-> '2014-12-31'
mysql> SELECT MAKEDATE(2014 366);
-> '2015-01-01'
This MySQL tutorial explains how to use the MySQL MAKETIME function with syntax and examples.
The MySQL MAKETIME function returns the time for a certain hour minute second combination.
The syntax for the MAKETIME function in MySQL is:
MAKETIME( hour minute second )
hour The hour value used to create the time. minute The minute value used to create the time. second The second value used to create the time.
- Time values range from '-838:59:59' to '838:59:59'.
The MAKETIME function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1.1
Let's look at some MySQL MAKETIME function examples and explore how to use the MAKETIME function in MySQL.
For example:
mysql> SELECT MAKETIME(11 28 1);
-> '11:28:01'
mysql> SELECT MAKETIME(14 31 0);
-> '14:31:00'
mysql> SELECT MAKETIME(23 59 59);
-> '23:59:59'
mysql> SELECT MAKETIME(838 59 59);
-> '838:59:59'
mysql> SELECT MAKETIME(-838 59 59);
-> '-838:59:59'
This MySQL tutorial explains how to use the MySQL MICROSECOND function with syntax and examples.
The MySQL MICROSECOND function returns the microsecond portion of a date value.
The syntax for the MICROSECOND function in MySQL is:
MICROSECOND( date_value )
date_value The time or datetime value from which the microseconds are extracted from.
- The MICROSECOND function returns the microsecond portion (a number from 0 to 999999) given a date value.
- See also the EXTRACT YEAR QUARTER MONTH WEEK DAY HOUR MINUTE and SECOND functions.
The MICROSECOND function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL MICROSECOND function examples and explore how to use the MICROSECOND function in MySQL.
For example:
mysql> SELECT MICROSECOND('2014-01-28 15:21:05.000001');
*Result:* 1
mysql> SELECT MICROSECOND('2014-01-28 15:21:05.999999');
*Result:* 999999
mysql> SELECT MICROSECOND('2014-02-15');
*Result:* 0
mysql> SELECT MICROSECOND('12:13:06.387483');
*Result:* 387483
mysql> SELECT MICROSECOND('838:11:59.000013');
*Result:* 13
This MySQL tutorial explains how to use the MySQL MINUTE function with syntax and examples.
The MySQL MINUTE function returns the minute portion of a date value.
The syntax for the MINUTE function in MySQL is:
MINUTE( date_value )
date_value A time or datetime value from which to extract the minute.
- The MINUTE function returns the minute (a number from 0 to 59) given a date value.
- See also the EXTRACT YEAR QUARTER MONTH WEEK DAY HOUR SECOND and MICROSECOND functions.
The MINUTE function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL MINUTE function examples and explore how to use the MINUTE function in MySQL.
For example:
mysql> SELECT MINUTE('2014-01-28 07:47:18.000004');
*Result:* 47
mysql> SELECT MINUTE('2014-01-28 15:21:05');
*Result:* 21
mysql> SELECT MINUTE('12:13:06');
*Result:* 13
mysql> SELECT MINUTE('838:11:59');
*Result:* 11
This last MINUTE example would display the minute portion of the current system time (current system time is returned by the CURTIME function).
mysql> SELECT MINUTE(CURTIME());
This MySQL tutorial explains how to use the MySQL MONTH function with syntax and examples.
The MySQL MONTH function returns the month portion of a date value.
The syntax for the MONTH function in MySQL is:
MONTH( date_value )
date_value A date or datetime value from which to extract the month.
- The MONTH function returns the month (a number from 1 to 12) given a date value.
- See also the EXTRACT YEAR QUARTER WEEK DAY HOUR MINUTE SECOND and MICROSECOND functions.
The MONTH function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL MONTH function examples and explore how to use the MONTH function in MySQL.
For example:
mysql> SELECT MONTH('2014-01-28');
*Result:* 1
mysql> SELECT MONTH('2014-01-28 15:21:05');
*Result:* 1
mysql> SELECT MONTH('2013-10-15');
*Result:* 10
This last MONTH example would display the month portion of the current system date (current system date is returned by the CURDATE function).
mysql> SELECT MONTH(CURDATE());
This MySQL tutorial explains how to use the MySQL MONTHNAME function with syntax and examples.
The MySQL MONTHNAME function returns the full name of the month for a date.
The syntax for the MONTHNAME function in MySQL is:
MONTHNAME( date_value )
date_value A date or datetime value from which to extract the full month name.
- The MONTHNAME function returns the full name of the month (January February ... December) given a date value.
The MONTHNAME function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL MONTHNAME function examples and explore how to use the MONTHNAME function in MySQL.
For example:
mysql> SELECT MONTHNAME('2014-01-27');
*Result:* 'January'
mysql> SELECT MONTHNAME('2014-05-08');
*Result:* 'May'
mysql> SELECT MONTHNAME('2014-12-29');
*Result:* 'December'
This last MONTHNAME example would display the month name for the current system date (current system date is returned by the CURDATE function).
mysql> SELECT MONTHNAME(CURDATE());
This MySQL tutorial explains how to use the MySQL NOW function with syntax and examples.
The MySQL NOW function returns the current date and time.
The syntax for the NOW function in MySQL is:
NOW( )
There are no parameters or arguments for the NOW function.
- The NOW function will return the current date as a 'YYYY-MM-DD HH:MM:SS' format if used in a string context.
- The NOW function will return the current date as a YYYYMMDDHHMMSS format if used in a numeric context in versions of MySQL prior to MySQL 4.1.13.
- The NOW function will return the current date as a YYYYMMDDHHMMSS.uuuuuu format if used in a numeric context in versions of MySQL 4.1.13 and newer.
- The CURRENT_TIMESTAMP LOCALTIME and LOCALTIMESTAMP functions are synonyms for the NOW function.
The NOW function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL NOW function examples and explore how to use the NOW function in MySQL.
For example:
mysql> SELECT NOW();
*Result:* '2014-01-28 13:48:41'
mysql> SELECT NOW() + 0;
*Result:* 20140118134841.000000
mysql> SELECT NOW() + 1;
*Result:* 20140118134842.000000
This MySQL tutorial explains how to use the MySQL PERIOD_ADD function with syntax and examples.
The MySQL PERIOD_ADD function takes a period (formatted as YYMM or YYYYMM) and adds a specified number of months to it.
The syntax for the PERIOD_ADD function in MySQL is:
PERIOD_ADD( period number )
period A period formatted as either YYMM or YYYYMM. number The number of months to add to the period. It can be a positive or negative value.
- The PERIOD_ADD function will return the result formatted as YYYYMM.
The PERIOD_ADD function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL PERIOD_ADD function examples and explore how to use the PERIOD_ADD function in MySQL.
For example:
mysql> SELECT PERIOD_ADD(201402 5);
*Result:* 201407
mysql> SELECT PERIOD_ADD(201402 6);
*Result:* 201408
mysql> SELECT PERIOD_ADD(201402 12);
*Result:* 201502
mysql> SELECT PERIOD_ADD(201402 16);
*Result:* 201506
mysql> SELECT PERIOD_ADD(201402 -1);
*Result:* 201401
mysql> SELECT PERIOD_ADD(1402 5);
*Result:* 201407
mysql> SELECT PERIOD_ADD(1402 6);
*Result:* 201408
This MySQL tutorial explains how to use the MySQL PERIOD_DIFF function with syntax and examples.
The MySQL PERIOD_DIFF function returns the difference in months between two periods (formatted as YYMM or YYYYMM).
The syntax for the PERIOD_DIFF function in MySQL is:
PERIOD_DIFF( period1 period2 )
period1 A period formatted as either YYMM or YYYYMM. period2 A period formatted as either YYMM or YYYYMM.
- The parameters period1 and period2 must be formatted as either YYMM or YYYYMM but do not have to be the same format as each other. So period1 could be formatted as YYMM and period2 could be formatted as YYYYMM or vice versa.
The PERIOD_DIFF function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL PERIOD_DIFF function examples and explore how to use the PERIOD_DIFF function in MySQL.
For example:
mysql> SELECT PERIOD_DIFF(201405 201402);
*Result:* 3
mysql> SELECT PERIOD_DIFF(201508 201408);
*Result:* 12
mysql> SELECT PERIOD_DIFF(201408 201508);
*Result:* -12
mysql> SELECT PERIOD_DIFF(1405 1402);
*Result:* 3
mysql> SELECT PERIOD_DIFF(201411 1409);
*Result:* 2
mysql> SELECT PERIOD_DIFF(1412 201405);
*Result:* 7
This MySQL tutorial explains how to use the MySQL QUARTER function with syntax and examples.
The MySQL QUARTER function returns the quarter portion of a date value.
The syntax for the QUARTER function in MySQL is:
QUARTER( date_value )
date_value A date or datetime value from which to extract the quarter.
- The QUARTER function returns the quarter (a number from 1 to 4) given a date value.
- Dates that have a month of Jan-Mar would return 1.
- Dates that have a month of Apr-Jun would return 2.
- Dates that have a month of Jul-Sep would return 3.
- Dates that have a month of Oct-Dec would return 4.
- See also the EXTRACT YEAR MONTH WEEK DAY HOUR MINUTE SECOND and MICROSECOND functions.
The QUARTER function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL QUARTER function examples and explore how to use the QUARTER function in MySQL.
For example:
mysql> SELECT QUARTER('2014-01-28');
*Result:* 1
mysql> SELECT QUARTER('2014-01-28 15:21:05');
*Result:* 1
mysql> SELECT QUARTER('2013-04-20');
*Result:* 2
mysql> SELECT QUARTER('2013-07-16');
*Result:* 3
mysql> SELECT QUARTER('2013-10-15');
*Result:* 4
This last QUARTER example would display the quarter portion of the current system date (current system date is returned by the CURDATE function).
mysql> SELECT QUARTER(CURDATE());
This MySQL tutorial explains how to use the MySQL SEC_TO_TIME function with syntax and examples.
The MySQL SEC_TO_TIME function converts numeric seconds into a time value.
The syntax for the SEC_TO_TIME function in MySQL is:
SEC_TO_TIME( seconds )
seconds A numeric value representing the number of seconds. This value can be positive or negative.
- Time values range from '-838:59:59' to '838:59:59'.
- The SEC_TO_TIME function will format the result as "HH:MM:SS".
- See also the TIME_TO_SEC function.
The SEC_TO_TIME function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL SEC_TO_TIME function examples and explore how to use the SEC_TO_TIME function in MySQL.
For example:
mysql> SELECT SEC_TO_TIME(1);
*Result:* '00:00:01'
mysql> SELECT SEC_TO_TIME(2);
*Result:* '00:00:02'
mysql> SELECT SEC_TO_TIME(8001);
*Result:* '02:13:21'
mysql> SELECT SEC_TO_TIME(34562);
*Result:* '09:36:02'
mysql> SELECT SEC_TO_TIME(-7005);
*Result:* '-01:56:45'
This MySQL tutorial explains how to use the MySQL SECOND function with syntax and examples.
The MySQL SECOND function returns the second portion of a date value.
The syntax for the SECOND function in MySQL is:
SECOND( date_value )
date_value A time or datetime value from which to extract the seconds.
- The SECOND function returns the seconds (a number from 0 to 59) given a date value.
- See also the EXTRACT YEAR QUARTER MONTH WEEK DAY HOUR MINUTE and MICROSECOND functions.
The SECOND function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL SECOND function examples and explore how to use the SECOND function in MySQL.
For example:
mysql> SELECT SECOND('2014-01-28 07:47:18.000004');
*Result:* 18
mysql> SELECT SECOND('2014-01-28 15:21:05');
*Result:* 5
mysql> SELECT SECOND('12:13:06');
*Result:* 6
mysql> SELECT SECOND('838:11:59');
*Result:* 59
This last SECOND example would display the second portion of the current system time (current system time is returned by the CURTIME function).
mysql> SELECT SECOND(CURTIME());
This MySQL tutorial explains how to use the MySQL STR_TO_DATE function with syntax and examples.
The MySQL STR_TO_DATE function takes a string and returns a date specified by a format mask.
The syntax for the STR_TO_DATE function in MySQL is:
STR_TO_DATE( string format_mask )
string The string value to format as a date. format_mask The format to apply to string. The following is a list of options for the format_mask parameter. These parameters can be used in many combinations.
Value | Description |
---|---|
%a | Weekday name abbreviated (Sun to Sat) |
%b | Month name abbreviated (Jan to Dec) |
%c | Month as a numeric value (0 to 12) |
%D | Day of the month as a numeric value followed by suffix (1st 2nd 3rd ...) |
%d | Day of the month as a numeric value (01 to 31) |
%e | Day of the month as a numeric value (0 to 31) |
%f | Microseconds (000000 to 999999) |
%H | Hour (00 to 23) |
%h | Hour (00 to 12) |
%I | Hour (00 to 12) |
%i | Minutes (00 to 59) |
%j | Day of the year (001 to 366) |
%k | Hour (00 to 23) |
%l | Hour (1 to 12) |
%M | Month name in full (January to December) |
%m | Month name as a numeric value (00 to 12) |
%p | AM or PM |
%r | Time in 12 hour AM or PM format (hh:mm:ss AM/PM) |
%S | Seconds (00 to 59) |
%s | Seconds (00 to 59) |
%T | Time in 24 hour format (hh:mm:ss) |
%U | Week where Sunday is the first day of the week (00 to 53) |
%u | Week where Monday is the first day of the week (00 to 53) |
%V | Week where Sunday is the first day of the week (01 to 53) |
Available starting in MySQL 3.23.8 and used with %X | |
%v | Week where Monday is the first day of the week (01 to 53) |
Available starting in MySQL 3.23.8 and used with %X | |
%W | Weekday name in full (Sunday to Saturday) |
%w | Day of the week where Sunday=0 and Saturday=6 |
%X | Year for the week where Sunday is the first day of the week |
Available starting in MySQL 3.23.8 and used with %V | |
%x | Year for the week where Monday is the first day of the week |
Available starting in MySQL 3.23.8 and used with %v | |
%Y | Year as a numeric 4-digit value |
%y | Year as a numeric 2-digit value |
- The STR_TO_DATE function will return a datetime value if the string contains both valid date and time parts.
- The STR_TO_DATE function will return a date value if the string contains only valid date parts.
- The STR_TO_DATE function will return a time value if the string contains only valid time parts.
- The STR_TO_DATE function will return a NULL value if it is unable to extract valid date and time parts using the format_mask.
The STR_TO_DATE function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL STR_TO_DATE function examples and explore how to use the STR_TO_DATE function in MySQL.
For example:
mysql> SELECT STR_TO_DATE('February 01 2014' '%M %d %Y');
*Result:* '2014-02-01'
mysql> SELECT STR_TO_DATE('March 8 2014' '%M %e %Y');
*Result:* '2014-03-08'
mysql> SELECT STR_TO_DATE('Friday February 28 2014' '%W %M %e %Y');
*Result:* '2014-02-28'
mysql> SELECT STR_TO_DATE('2014 2 28 09' '%Y %m %d %h');
*Result:* '2014-02-28 09:00:00'
mysql> SELECT STR_TO_DATE('2014 2 28 09 30 05' '%Y %m %d %h %i %s');
*Result:* '2014-02-28 09:30:05'
mysql> SELECT STR_TO_DATE('10 15 30' '%h %i %s');
*Result:* '10:15:30'
This MySQL tutorial explains how to use the MySQL SUBDATE function with syntax and examples.
The MySQL SUBDATE function returns a date after which a certain time/date interval has been subtracted.
The syntax for the SUBDATE function in MySQL is:
SUBDATE( date INTERVAL value unit )
OR
SUBDATE( date days )
date The date to which the interval should be subtracted. days The number of days to subtract from date (second syntax). value The value of the time/date interval that you wish to subtract. You can specify positive and negative values for this parameter (first syntax). unit The unit type of the interval such as DAY MONTH MINUTE HOUR and so on. It can be one of the following (first syntax):
unit | Compatibility |
---|---|
MICROSECOND | 4.1.1+ |
SECOND | 3.2.3+ |
MINUTE | 3.2.3+ |
HOUR | 3.2.3+ |
DAY | 3.2.3+ |
WEEK | 5+ |
MONTH | 3.2.3+ |
QUARTER | 5+ |
YEAR | 3.2.3+ |
SECOND_MICROSECOND | 4.1.1+ |
MINUTE_MICROSECOND | 4.1.1+ |
MINUTE_SECOND | 4.1.1+ |
HOUR_MICROSECOND | 4.1.1+ |
HOUR_SECOND | 4.1.1+ |
HOUR_MINUTE | 3.2.3+ |
DAY_MICROSECOND | 4.1.1+ |
DAY_SECOND | 3.2.3+ |
DAY_MINUTE | 3.2.3+ |
DAY_HOUR | 3.2.3+ |
YEAR_MONTH | 3.2.3+ |
- If you specify an interval value that is too short for the unit that you have specified the SUBDATE function will assume that the left-most portion of the interval value was not provided.
- The SUBDATE function (first syntax only) is a synonym for the DATE_SUB function.
- Using the SUBDATE function with a negative value as a parameter is equivalent to using the ADDDATE function.
- See also the DATE_ADD DATE_SUB ADDDATE ADDTIME and SUBTIME functions.
The SUBDATE function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL SUBDATE function examples and explore how to use the SUBDATE function in MySQL.
For example:
mysql> SELECT SUBDATE('2014-02-13 08:44:21.000001' INTERVAL 4 MICROSECOND);
*Result:* '2014-02-13 08:44:20.999997'
mysql> SELECT SUBDATE('2014-02-13 08:44:21' INTERVAL 20 SECOND);
*Result:* '2014-02-13 08:44:01'
mysql> SELECT SUBDATE('2014-02-13 08:44:21' INTERVAL 25 MINUTE);
*Result:* '2014-02-13 08:19:21'
mysql> SELECT SUBDATE('2014-02-13 08:44:21' INTERVAL 2 HOUR);
*Result:* '2014-02-13 06:44:21'
mysql> SELECT SUBDATE('2014-02-13' INTERVAL 10 DAY);
*Result:* '2014-02-03'
mysql> SELECT SUBDATE('2014-02-13' 10);
*Result:* '2014-02-03'
mysql> SELECT SUBDATE('2014-02-13' INTERVAL 12 WEEK);
*Result:* '2013-11-21'
mysql> SELECT SUBDATE('2014-02-13' INTERVAL 3 MONTH);
*Result:* '2013-11-13'
mysql> SELECT SUBDATE('2014-02-13' INTERVAL 3 QUARTER);
*Result:* '2013-05-13'
mysql> SELECT SUBDATE('2014-02-13' INTERVAL 5 YEAR);
*Result:* '2009-02-13'
mysql> SELECT SUBDATE('2014-02-13 08:44:21.000001' INTERVAL '12.000001' SECOND_MICROSECOND);
*Result:* '2014-02-13 08:44:09'
mysql> SELECT SUBDATE('2014-02-13 08:44:21.000001' INTERVAL '3:12.000001' MINUTE_MICROSECOND);
*Result:* '2014-02-13 08:41:09'
mysql> SELECT SUBDATE('2014-02-13 08:44:21' INTERVAL '3:12' MINUTE_SECOND);
*Result:* '2014-02-13 08:41:09'
mysql> SELECT SUBDATE('2014-02-13 08:44:21.000001' INTERVAL '1:03:12.000001' HOUR_MICROSECOND);
*Result:* '2014-02-13 07:41:09'
mysql> SELECT SUBDATE('2014-02-13 08:44:21' INTERVAL '1:03:12' HOUR_SECOND);
*Result:* '2014-02-13 07:41:09'
mysql> SELECT SUBDATE('2014-02-13 08:44:21' INTERVAL '1:03' HOUR_MINUTE);
*Result:* '2014-02-13 07:41:21'
mysql> SELECT SUBDATE('2014-02-13 08:44:21.000001' INTERVAL '7 1:03:12.000001' DAY_MICROSECOND);
*Result:* '2014-02-06 07:41:09'
mysql> SELECT SUBDATE('2014-02-13 08:44:21' INTERVAL '7 1:03:12' DAY_SECOND);
*Result:* '2014-02-06 07:41:09'
mysql> SELECT SUBDATE('2014-02-13 08:44:21' INTERVAL '7 1:03' DAY_MINUTE);
*Result:* '2014-02-06 07:41:21'
mysql> SELECT SUBDATE('2014-02-13 08:44:21' INTERVAL '7 1' DAY_HOUR);
*Result:* '2014-02-06 07:44:21'
mysql> SELECT SUBDATE('2014-02-13' INTERVAL '5-3' YEAR_MONTH);
*Result:* '2008-11-13'
This MySQL tutorial explains how to use the MySQL SUBTIME function with syntax and examples.
The MySQL SUBTIME function returns a time/datetime value after which a certain time interval has been subtracted.
The syntax for the SUBTIME function in MySQL is:
SUBTIME( start_value time )
start_value A time or datetime value to which the time interval should be subtracted. time The value of the time interval that you wish to subtract. It can be a positive or negative number.
- Using the SUBTIME function with a negative time value as a parameter is equivalent to using the ADDTIME function.
- See also the DATE_ADD DATE_SUB ADDDATE and SUBDATE functions.
The SUBTIME function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1.1
Let's look at some MySQL SUBTIME function examples and explore how to use the SUBTIME function in MySQL.
For example:
mysql> SELECT SUBTIME('2014-02-13 08:44:21.000002' '2.000001');
*Result:* '2014-02-13 08:44:19.000001'
mysql> SELECT SUBTIME('2014-02-13 08:44:21.000002' '3:2.000001');
*Result:* '2014-02-13 05:42:21.000001'
mysql> SELECT SUBTIME('2014-02-13 08:44:21.000002' '4:3:2.000001');
*Result:* '2014-02-13 04:41:19.000001'
mysql> SELECT SUBTIME('2014-02-13 08:44:21.000002' '5 4:3:2.000001');
*Result:* '2014-02-08 04:41:19.000001'
mysql> SELECT SUBTIME('01:15:23.999998' '0.000001');
*Result:* '01:15:23.999997'
mysql> SELECT SUBTIME('01:15:23.999998' '5.000001');
*Result:* '01:15:18.999997'
mysql> SELECT SUBTIME('01:15:23.000001' '8:12:15.003441');
*Result:* '-06:56:52.003440'
mysql> SELECT SUBTIME('01:15:23.000001' '-8:12:15.003441');
*Result:* '09:27:38.003442'
This MySQL tutorial explains how to use the MySQL SYSDATE function with syntax and examples.
The MySQL SYSDATE function returns the current date and time.
The syntax for the SYSDATE function in MySQL is:
SYSDATE( )
There are no parameters or arguments for the SYSDATE function.
- The SYSDATE function will return the current date as a 'YYYY-MM-DD HH:MM:SS' format if used in a string context.
- The SYSDATE function will return the current date as a YYYYMMDDHHMMSS format if used in a numeric context.
The SYSDATE function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL SYSDATE function examples and explore how to use the SYSDATE function in MySQL.
For example:
mysql> SELECT SYSDATE();
*Result:* '2014-02-17 10:27:21'
mysql> SELECT SYSDATE() + 0;
*Result:* 20140217102721
mysql> SELECT SYSDATE() + 1;
*Result:* 20140217102722
This MySQL tutorial explains how to use the MySQL TIME function with syntax and examples.
The MySQL TIME function extracts the time value from a time/datetime expression.
The syntax for the TIME function in MySQL is:
TIME( expression )
expression The time or datetime value from which the time should be extracted.
- If expression is not a time or a datetime value the TIME function will return '00:00:00'.
- If expression is NULL the TIME function will return NULL.
- See also the CAST function.
The TIME function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1.1
Let's look at some MySQL TIME function examples and explore how to use the TIME function in MySQL.
For example:
mysql> SELECT TIME('2014-02-14 06:18:01.000001');
*Result:* '06:18:01.000001'
mysql> SELECT TIME('2014-02-17 18:20:19');
*Result:* '18:20:19'
mysql> SELECT TIME('10:35:05');
*Result:* '10:35:05'
mysql> SELECT TIME('The time is 10:35:05');
*Result:* '00:00:00'
mysql> SELECT TIME(NULL);
*Result:* NULL
This MySQL tutorial explains how to use the MySQL TIME_FORMAT function with syntax and examples.
The MySQL TIME_FORMAT function formats a time as specified by a format mask.
The syntax for the TIME_FORMAT function in MySQL is:
TIME_FORMAT( time format_mask )
time The time to format. format_mask The format to apply to time. The following is a list of options for the format_mask parameter. These parameters can be used in many combinations.
Value | Description |
---|---|
%f | Microseconds (000000 to 999999) |
%f is available starting in MySQL 4.1.1 | |
%H | Hour (00 to 23 generally but can be higher) |
%h | Hour (00 to 12) |
%I | Hour (00 to 12) |
%i | Minutes (00 to 59) |
%p | AM or PM |
%r | Time in 12 hour AM or PM format (hh:mm:ss AM/PM) |
%S | Seconds (00 to 59) |
%s | Seconds (00 to 59) |
%T | Time in 24 hour format (hh:mm:ss) |
- The TIME_FORMAT function only formats the hours minutes seconds and microseconds found in a time value.
- See also the DATE_FORMAT function.
The TIME_FORMAT function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL TIME_FORMAT function examples and explore how to use the TIME_FORMAT function in MySQL.
For example:
mysql> SELECT TIME_FORMAT('15:02:28' '%H %i %s');
*Result:* '15 02 28'
mysql> SELECT TIME_FORMAT('15:02:28' '%h:%i:%s %p');
*Result:* '03:02:28 PM'
mysql> SELECT TIME_FORMAT('15:02:28' '%h:%i%p');
*Result:* '03:02PM'
mysql> SELECT TIME_FORMAT('17:42:03.000001' '%r');
*Result:* '05:42:03 PM'
mysql> SELECT TIME_FORMAT('17:42:03.000001' '%T');
*Result:* '17:42:03'
mysql> SELECT TIME_FORMAT('07:42:03.000001' '%f');
*Result:* '000001'
This MySQL tutorial explains how to use the MySQL TIME_TO_SEC function with syntax and examples.
The MySQL TIME_TO_SEC function converts a time value into numeric seconds.
The syntax for the TIME_TO_SEC function in MySQL is:
TIME_TO_SEC( time )
time The time value to convert to numeric seconds.
- See also the SEC_TO_TIME function.
The TIME_TO_SEC function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL TIME_TO_SEC function examples and explore how to use the TIME_TO_SEC function in MySQL.
For example:
mysql> SELECT TIME_TO_SEC('00:00:01');
*Result:* 1
mysql> SELECT TIME_TO_SEC('00:00:01.999999');
*Result:* 1
mysql> SELECT TIME_TO_SEC('00:00:02');
*Result:* 2
mysql> SELECT TIME_TO_SEC('02:13:21');
*Result:* 8001
mysql> SELECT TIME_TO_SEC('09:36:02');
*Result:* 34562
mysql> SELECT TIME_TO_SEC('-01:56:45');
*Result:* -7005
This MySQL tutorial explains how to use the MySQL TIMEDIFF function with syntax and examples.
The MySQL TIMEDIFF function returns the difference (expressed as a time value) between two time/datetime values.
The syntax for the TIMEDIFF function in MySQL is:
TIMEDIFF( time1 time2 )
time1 and time2
The two time/datetime to calculate the difference between. The calculation is time1 - time2
.
- A time value can range from -838:59:59' to '838:59:59'.
- When using the TIMEDIFF function both time1 and time2 must be both time values or both datetime values. You can not have one be a time value and the other be a datetime value or the TIMEDIFF function will return a NULL value.
The TIMEDIFF function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1.1
Let's look at some MySQL TIMEDIFF function examples and explore how to use the TIMEDIFF function in MySQL.
For example:
mysql> SELECT TIMEDIFF('2014-02-17 12:10:08' '2014-02-17 12:10:07');
*Result:* '00:00:01'
mysql> SELECT TIMEDIFF('12:10:08' '12:10:07');
*Result:* '00:00:01'
mysql> SELECT TIMEDIFF('11:41:14' '12:10:08');
*Result:* '-00:28:54'
mysql> SELECT TIMEDIFF('2014-02-17 12:10:08' '2014-02-16 12:10:08');
*Result:* '24:00:00'
mysql> SELECT TIMEDIFF('2014-02-17 12:10:08' '12:10:08');
*Result:* NULL
This MySQL tutorial explains how to use the MySQL TIMESTAMP function with syntax and examples.
The MySQL TIMESTAMP function converts an expression to a datetime value and if specified adds an optional time interval to the value.
The syntax for the TIMESTAMP function in MySQL is:
TIMESTAMP( expression interval )
expression A date or datetime value that will be converted. interval Optional. It is a time value to add to the expression.
- The TIMESTAMP function will return a datetime value.
The TIMESTAMP function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1.1
Let's look at some MySQL TIMESTAMP function examples and explore how to use the TIMESTAMP function in MySQL.
For example:
mysql> SELECT TIMESTAMP('2014-02-18');
*Result:* '2014-02-18 00:00:00'
mysql> SELECT TIMESTAMP('2014-02-18' '07:32:00');
*Result:* '2014-02-18 07:32:00'
mysql> SELECT TIMESTAMP('2014-02-18 10:05:00' '02:03:04');
*Result:* '2014-02-18 12:08:04'
This MySQL tutorial explains how to use the MySQL TO_DAYS function with syntax and examples.
The MySQL TO_DAYS function converts a date into numeric days.
The syntax for the TO_DAYS function in MySQL is:
TO_DAYS( date )
date The date to convert to numeric days.
- The TO_DAYS function is to be used only with dates within the Gregorian calendar.
- The TO_DAYS function will return NULL if date is '0000-00-00'.
- See also the FROM_DAYS function which is the reverse of the TO_DAYS function.
The TO_DAYS function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL TO_DAYS function examples and explore how to use the TO_DAYS function in MySQL.
For example:
mysql> SELECT TO_DAYS('2014-02-17');
*Result:* 735646
mysql> SELECT TO_DAYS('14-02-17');
*Result:* 735646
mysql> SELECT TO_DAYS('2014-02-18');
*Result:* 735647
mysql> SELECT TO_DAYS('2014-02-19 05:30:00');
*Result:* 735648
mysql> SELECT TO_DAYS('0000-01-01');
*Result:* 1
mysql> SELECT TO_DAYS('0000-00-00');
*Result:* NULL
This MySQL tutorial explains how to use the MySQL WEEK function with syntax and examples.
The MySQL WEEK function returns the week portion of a date value.
The syntax for the WEEK function in MySQL is:
WEEK( date_value mode )
date_value A date or datetime value from which to extract the week. mode Optional. It is used to specify what day the week starts on. It can be one of the following:
mode | Explanation | Returns |
---|---|---|
0 | First day of the week is Sunday | 0-53 |
1 | First day of the week is Monday and the first week has more than 3 days | 0-53 |
2 | First day of the week is Sunday | 1-53 |
3 | First day of the week is Monday and the first week has more than 3 days | 1-53 |
4 | First day of the week is Sunday and the first week has more than 3 days | 0-53 |
5 | First day of the week is Monday | 0-53 |
6 | First day of the week is Sunday and the first week has more than 3 days | 1-53 |
7 | First day of the week is Monday | 1-53 |
- The WEEK function will return a value between 0-53 or 1-53 depending on the mode specified.
- If you are running MySQL 4.0.14+ and the mode is not specified the WEEK function will use the value in the default_week_format system variable as the mode.
- If you are running a version of MySQL that is older than 4.0.14 and the mode is not specified the WEEK function will use 0 as the mode.
- The WEEKOFYEAR function returns the same as the WEEK function with the syntax of WEEK(date_value 3).
- See also the EXTRACT YEAR QUARTER MONTH DAY HOUR MINUTE SECOND and MICROSECOND functions.
The WEEK function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL WEEK function examples and explore how to use the WEEK function in MySQL.
For example:
(Note: Your results may vary from the examples below depending on what your default_week_format system variable is set to.)
mysql> SELECT WEEK('2014-01-01');
*Result:* 0
mysql> SELECT WEEK('2014-04-20');
*Result:* 16
mysql> SELECT WEEK('2014-07-16');
*Result:* 28
mysql> SELECT WEEK('2014-10-15');
*Result:* 41
This last WEEK example would display the week portion of the current system date (current system date is returned by the CURDATE function).
mysql> SELECT WEEK(CURDATE());
This MySQL tutorial explains how to use the MySQL WEEKDAY function with syntax and examples.
The MySQL WEEKDAY function returns the weekday index for a date.
The syntax for the WEEKDAY function in MySQL is:
WEEKDAY( date_value )
date_value A date or datetime value from which to extract the weekday index.
- The WEEKDAY function returns the index of the weekday (0=Monday 1=Tuesday 2=Wednesday 3=Thursday 4=Friday 5=Saturday 6=Sunday) given a date value.
- See also the DAYNAME function.
The WEEKDAY function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL WEEKDAY function examples and explore how to use the WEEKDAY function in MySQL.
For example:
mysql> SELECT WEEKDAY('2014-01-27');
*Result:* 0
mysql> SELECT WEEKDAY('2014-01-28');
*Result:* 1
mysql> SELECT WEEKDAY('2014-01-29 08:35:17');
*Result:* 2
This last WEEKDAY example would display the weekday index for the current system date (current system date is returned by the CURDATE function).
mysql> SELECT WEEKDAY(CURDATE());
This MySQL tutorial explains how to use the MySQL WEEKOFYEAR function with syntax and examples.
The MySQL WEEKOFYEAR function returns week of the year for a date value.
The syntax for the WEEKOFYEAR function in MySQL is:
WEEKOFYEAR( date_value )
date_value A date or datetime value from which to extract the week of the year.
- The WEEKOFYEAR function returns the week of the year (a number from 1 to 53) given a date value.
- The WEEKOFYEAR function assumes that the first day of the week is Monday and the first week has more than 3 days.
- The WEEKOFYEAR function returns the same as the WEEK function with the syntax of WEEK(date_value 3).
The WEEKOFYEAR function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL WEEKOFYEAR function examples and explore how to use the WEEKOFYEAR function in MySQL.
For example:
mysql> SELECT WEEKOFYEAR('2014-01-01');
*Result:* 1
mysql> SELECT WEEKOFYEAR('2014-02-28');
*Result:* 9
mysql> SELECT WEEKOFYEAR('2014-12-28');
*Result:* 52
This last WEEKOFYEAR example would display the week of the year for the current system date (current system date is returned by the CURDATE function).
mysql> SELECT WEEKOFYEAR(CURDATE());
This MySQL tutorial explains how to use the MySQL YEAR function with syntax and examples.
The MySQL YEAR function returns the year portion of a date value.
The syntax for the YEAR function in MySQL is:
YEAR( date_value )
date_value A date or datetime value from which to extract the year.
- The YEAR function returns a four-digit year (a number from 1000 to 9999) given a date value.
- See also the EXTRACT QUARTER MONTH WEEK DAY HOUR MINUTE SECOND and MICROSECOND functions.
The YEAR function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL YEAR function examples and explore how to use the YEAR function in MySQL.
For example:
mysql> SELECT YEAR('2014-01-28');
*Result:* 2014
mysql> SELECT YEAR('2014-01-28 15:21:05');
*Result:* 2014
mysql> SELECT YEAR('2013-10-15');
*Result:* 2013
This last YEAR example would display the year portion of the current system date (current system date is returned by the CURDATE function).
mysql> SELECT YEAR(CURDATE());
This MySQL tutorial explains how to use the MySQL YEARWEEK function with syntax and examples.
The MySQL YEARWEEK function returns the year and week for a date value.
The syntax for the YEARWEEK function in MySQL is:
YEARWEEK( date_value mode )
date_value A date or datetime value from which to extract the year and week. mode Optional. It is used to specify what day the week starts on. It can be one of the following:
mode | Explanation | Week Value |
---|---|---|
0 | First day of the week is Sunday | 0-53 |
1 | First day of the week is Monday and the first week has more than 3 days | 0-53 |
2 | First day of the week is Sunday | 1-53 |
3 | First day of the week is Monday and the first week has more than 3 days | 1-53 |
4 | First day of the week is Sunday and the first week has more than 3 days | 0-53 |
5 | First day of the week is Monday | 0-53 |
6 | First day of the week is Sunday and the first week has more than 3 days | 1-53 |
7 | First day of the week is Monday | 1-53 |
- The YEARWEEK function will return a year value as well as a week value (between 0-53 or 1-53) depending on the mode specified.
- The YEARWEEK function may return a year value that is different than the year displayed in the date_value because of the mode specified. This should only happen in the first week of the year and the last week of the year.
- If you are running MySQL 4.0.14+ and the mode is not specified the YEARWEEK function will use the value in the default_week_format system variable as the mode.
- If you are running a version of MySQL that is older than 4.0.14 and the mode is not specified the YEARWEEK function will use 0 as the mode.
- See also the EXTRACT YEAR QUARTER MONTH DAY HOUR MINUTE SECOND and MICROSECOND functions.
The YEARWEEK function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23.8
Let's look at some MySQL YEARWEEK function examples and explore how to use the YEARWEEK function in MySQL.
For example:
(Note: Your results may vary from the examples below depending on what your default_week_format system variable is set to.)
mysql> SELECT YEARWEEK('2014-01-01');
*Result:* 201352
mysql> SELECT YEARWEEK('2014-01-05');
*Result:* 201401
mysql> SELECT YEARWEEK('2014-01-12');
*Result:* 201402
mysql> SELECT YEARWEEK('2014-07-16');
*Result:* 201428
mysql> SELECT YEARWEEK('2014-12-31');
*Result:* 201452
mysql> SELECT YEARWEEK('2015-01-01');
*Result:* 201452
This last YEARWEEK example would display the year and week for the current system date (current system date is returned by the CURDATE function).
mysql> SELECT YEARWEEK(CURDATE());
This MySQL tutorial explains how to use the MySQL BIN function with syntax and examples.
The MySQL BIN function converts a decimal number to a binary number and returns the result as a string value.
The syntax for the BIN function in MySQL is:
BIN( number )
number The number to convert to a binary representation.
- The BIN function returns the binary representation as a string value.
- The BIN function is equivalent to using the CONV function with CONV(number 10 2) syntax.
The BIN function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL BIN function examples and explore how to use the BIN function in MySQL.
For example:
mysql> SELECT BIN(5);
*Result:* '101'
mysql> SELECT BIN(6);
*Result:* '110'
mysql> SELECT BIN(99);
*Result:* '1100011'
This MySQL tutorial explains how to use the MySQL BINARY function with syntax and examples.
The MySQL BINARY function converts a value to a binary string.
The syntax for the BINARY function in MySQL is:
BINARY value
value The value to convert to a binary string.
- The BINARY function is shorthand for CAST(value AS BINARY).
- See also CONVERT function.
The BINARY function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23.3
Let's look at some MySQL BINARY function examples and explore how to use the BINARY function in MySQL.
For example:
mysql> SELECT BINARY('techonthenet.com');
*Result:* 'techonthenet.com'
mysql> SELECT BINARY('T');
*Result:* 'T'
Using the BINARY function to cast a value to a binary string is one way to force a byte-by-byte comparison of strings rather than a character-by-character comparison. Let's investigate this further.
For example:
mysql> SELECT 'TECHONTHENET' = 'techonthenet';
*Result:* 1
If we ran the example above MySQL would perform a character-by-character comparison of 'TECHONTHENET' and 'techonthenet' and return 1 (because on a character-by-character basis 'TECHONTHENET' and 'techonthenet' are equivalent).
However if we modified the example by adding the BINARY function as follows changing the comparison to byte-by-byte instead of character-by-character:
mysql> SELECT BINARY 'TECHONTHENET' = 'techonthenet';
*Result:* 0
MySQL would perform a byte-by-byte comparison of 'TECHONTHENET' and 'techonthenet' and would return 0 (because on a byte-by-byte basis 'TECHONTHENET' and 'techonthenet' are NOT equivalent.)
This MySQL tutorial explains how to use the MySQL CASE function with syntax and examples.
The MySQL CASE function has the functionality of an IF-THEN-ELSE statement by allowing you to evaluate conditions and return a value when the first condition is met.
The syntax for the CASE function in MySQL is:
CASE expression
WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
...
WHEN condition_n THEN result_n
ELSE result
END
expression Optional. It is the value that you are comparing to the list of conditions. (ie: condition_1 condition_2 ... condition_n) condition_1 condition_2 ... condition_n Evaluated in the order listed. Once a condition is found to be true the CASE function will return the result and not evaluate the conditions any further. result_1 result_2 ... result_n The value returned once a condition is found to be true.
- If no condition is found to be true then the CASE function will return the value in the ELSE clause.
- If the ELSE clause is omitted and no condition is found to be true then the CASE statement will return NULL.
The CASE function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23.3
You could use the CASE function in a SQL statement where the expression is included.
SELECT supplier_id
CASE quantity
WHEN > 10 THEN 'The quantity is greater than 10'
WHEN = 10 THEN 'The quantity is 10'
ELSE 'The quantity is something else'
END
FROM suppliers;
In this CASE function example the expression is quantity whose value would be compared to each of the conditions until one is met. Then the corresponding value would be returned by the CASE function.
You could use the CASE function in a SQL statement where the expression is omitted.
SELECT
CASE
WHEN a < b THEN 1
WHEN supplier_type = 'clothing' THEN 2
ELSE 3
END
FROM suppliers;
In this CASE function example an expression has not been included so each condition is individually evaluated and can be completely different and unique. When a condition is met the corresponding value would be returned.
This MySQL tutorial explains how to use the MySQL CAST function with syntax and examples.
The MySQL CAST function converts a value from one datatype to another datatype.
The syntax for the CAST function in MySQL is:
CAST( value AS type )
value The value to convert to another datatype. type The datatype that you wish to convert value to. It can be one of the following:
Value | Description |
---|---|
DATE | Converts value to DATE type which has a date portion only. |
Format is 'YYYY-MM-DD'. | |
Supported range is '1000-01-01' to '9999-12-31'. | |
DATETIME | Converts value to DATETIME type which has both date and time portions. |
Format is 'YYYY-MM-DD HH:MM:SS'. | |
Supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59'. | |
TIME | Converts value to TIME type which has a time portion only. |
Format is 'HH:MM:SS'. | |
Supported range is '-838:59:59' to '838:59:59'. | |
CHAR | Converts value to CHAR type which is a fixed length string. |
SIGNED | Converts value to SIGNED type which is a signed 64-bit integer. |
UNSIGNED | Converts value to UNSIGNED type which is an unsigned 64-bit integer. |
BINARY | Converts value to BINARY type which is a binary string. |
- Starting in MySQL 4.0.6 you can use CHAR as type in the CAST function.
- You can use the BINARY function as shorthand for CAST(value AS BINARY).
- See also CONVERT function.
The CAST function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0.2
Let's look at some MySQL CAST function examples and explore how to use the CAST function in MySQL.
The first CAST function example shows how to cast a value to a DATE type. For example:
mysql> SELECT CAST('2014-02-28' AS DATE);
*Result:* '2014-02-28'
This CAST example takes the value '2014-02-28' and casts it as a DATE datatype.
This CAST function example shows how to cast a value to a DATETIME type. For example:
mysql> SELECT CAST('2014-02-28 08:14:57' AS DATETIME);
*Result:* '2014-02-28 08:14:57'
This CAST example takes the value '2014-02-28 08:14:57' and casts it as a DATETIME datatype.
This CAST function example shows how to cast a value to a TIME type. For example:
mysql> SELECT CAST('08:14:57' AS TIME);
*Result:* '08:14:57'
This CAST example takes the value '08:14:57' and casts it as a TIME datatype.
This CAST function example shows how to cast a value to a CHAR type. For example:
mysql> SELECT CAST(125 AS CHAR);
*Result:* '125'
This CAST example takes the value 125 and casts it as a CHAR datatype with the value of '125'.
This CAST function example shows how to cast a value to a SIGNED type. For example:
mysql> SELECT CAST(4-6 AS SIGNED);
*Result:* -2
This CAST example takes the value 4-5 and casts it as a SIGNED datatype with the value of -2.
This CAST function example shows how to cast a value to an UNSIGNED type. For example:
mysql> SELECT CAST(4-6 AS UNSIGNED);
*Result:* 18446744073709551614
This CAST example takes the value 4-5 and casts it as an UNSIGNED datatype with the value of 18446744073709551614.
This CAST function example shows how to cast a value to a BINARY type. For example:
mysql> SELECT CAST('4' AS BINARY);
*Result:* '4'
This CAST example takes the value '4' and casts it as a BINARY datatype with the binary string value of '4'.
This MySQL tutorial explains how to use the MySQL COALESCE function with syntax and examples.
The MySQL COALESCE function returns the first non-null expression in the list.
The syntax for the COALESCE function in MySQL is:
COALESCE( expression1 expression2 ... expression_n )
expression1 to expression_n The expressions to test for non-null values.
- If all expressions evaluate to null then the COALESCE function will return null.
The COALESCE function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL COALESCE function examples and explore how to use the COALESCE function in MySQL.
For example:
mysql> SELECT COALESCE(null null null 'A' 'B');
*Result:* 'A'
mysql> SELECT COALESCE('A' 'B' null 'C' 'D');
*Result:* 'A'
mysql> SELECT COALESCE(null 1 2 3 null 4);
*Result:* 1
mysql> SELECT COALESCE(null 'techonthenet.com' 'checkyourmath.com');
*Result:* 'techonthenet.com'
mysql> SELECT COALESCE(null null null null null);
*Result:* NULL
This MySQL tutorial explains how to use the MySQL CONNECTION_ID function with syntax and examples.
The MySQL CONNECTION_ID function returns the connection ID for the current connection which is a unique ID among the currently connected clients.
The syntax for the CONNECTION_ID function in MySQL is:
CONNECTION_ID( )
There are no parameters or arguments for the CONNECTION_ID function in MySQL.
- Each connection in the MySQL database has a connection ID that is unique among the currently connected clients.
The CONNECTION_ID function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23.14
Let's look at some MySQL CONNECTION_ID function examples and explore how to use the CONNECTION_ID function in MySQL.
For example:
mysql> SELECT CONNECTION_ID();
Since the CONNECTION_ID function returns the unique ID for the current connection t might display something like this:
mysql> SELECT CONNECTION_ID();
*Result:* 57
In this case the unique ID for the connection is 57.
This MySQL tutorial explains how to use the MySQL CONV function with syntax and examples.
The MySQL CONV function converts a number from one number base to another and returns the result as a string value.
The syntax for the CONV function in MySQL is:
CONV( number from_base to_base )
number The number to convert. from_base The number base that the number is currently represented in. The from_base can be between 2 and 36. to_base The number base to convert to. The to_base can be between 2 and 36 or -2 and -36.
- The CONV function returns the converted number as a string value.
- If a positive to_base is specified the CONV function treats number as an unsigned number.
- If a negative to_base is specified the CONV function treats number as a signed number.
- The CONV function with CONV(number 10 2) syntax is equivalent to using the BIN function.
- The CONV function returns NULL if any of the parameters are NULL (ie: number from_base or to_base).
The CONV function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL CONV function examples and explore how to use the CONV function in MySQL.
For example:
mysql> SELECT CONV(5 10 2);
*Result:* '101'
mysql> SELECT CONV(101 2 10);
*Result:* '5'
mysql> SELECT CONV(74 10 16);
*Result:* '4A'
mysql> SELECT CONV(-74 10 -16);
*Result:* '-44
mysql> SELECT CONV('4A' 16 10);
*Result:* '74'
This MySQL tutorial explains how to use the MySQL CONVERT function with syntax and examples.
The MySQL CONVERT function converts a value from one datatype to another or one character set to another.
There are 2 syntaxes for the CONVERT function - one syntax to convert datatypes and one syntax to convert character sets.
The first syntax for the CONVERT function is used to convert one datatype to another datatype in MySQL:
CONVERT( value type )
OR
The second syntax for the CONVERT function is used to convert one character set to another character set:
CONVERT( value USING character_set )
value The value to convert. type The datatype that you wish to convert value to. type can be one of the following:
Value | Description |
---|---|
DATE | Converts value to DATE type which has a date portion only. |
Format is 'YYYY-MM-DD'. | |
Supported range is '1000-01-01' to '9999-12-31'. | |
DATETIME | Converts value to DATETIME type which has both date and time portions. |
Format is 'YYYY-MM-DD HH:MM:SS'. | |
Supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59'. | |
TIME | Converts value to TIME type which has a time portion only. |
Format is 'HH:MM:SS'. | |
Supported range is '-838:59:59' to '838:59:59'. | |
CHAR | Converts value to CHAR type which is a fixed length string. |
SIGNED | Converts value to SIGNED type which is a signed 64-bit integer. |
UNSIGNED | Converts value to UNSIGNED type which is an unsigned 64-bit integer. |
BINARY | Converts value to BINARY type which is a binary string. |
character_set The character set to convert to.
- Starting in MySQL 4.0.6 you can use CHAR as type in the CONVERT function.
- See also CAST function.
The CONVERT function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0.2
Let's look at some MySQL CONVERT function examples and explore how to use the CONVERT function in MySQL.
The first syntax for the MySQL CONVERT function allows you to convert a value from one datatype to another datatype. Let's look at how to use the CONVERT function to convert a value to a DATE type. For example:
mysql> SELECT CONVERT('2014-02-28' DATE);
*Result:* '2014-02-28'
This CONVERT example takes the value '2014-02-28' and converts it to a DATE datatype.
This CONVERT function example shows how to convert a value to a DATETIME type. For example:
mysql> SELECT CONVERT('2014-02-28 08:14:57' DATETIME);
*Result:* '2014-02-28 08:14:57'
This CONVERT example takes the value '2014-02-28 08:14:57' and converts it to a DATETIME datatype.
This CONVERT function example shows how to convert a value to a TIME type. For example:
mysql> SELECT CONVERT('08:14:57' TIME);
*Result:* '08:14:57'
This CONVERT example takes the value '08:14:57' and converts it to a TIME datatype.
This CONVERT function example shows how to convert a value to a CHAR type. For example:
mysql> SELECT CONVERT(125 CHAR);
*Result:* '125'
This CONVERT example takes the value 125 and converts it as a CHAR datatype with the value of '125'.
This CONVERT function example shows how to convert a value to a SIGNED type. For example:
mysql> SELECT CONVERT(4-6 SIGNED);
*Result:* -2
This CONVERT example takes the value 4-5 and converts it as a SIGNED datatype with the value of -2.
This CONVERT function example shows how to convert a value to an UNSIGNED type. For example:
mysql> SELECT CONVERT(4-6 UNSIGNED);
*Result:* 18446744073709551614
This CONVERT example takes the value 4-5 and converts it as an UNSIGNED datatype with the value of 18446744073709551614.
This CONVERT function example shows how to convert a value to a BINARY type. For example:
mysql> SELECT CONVERT('4' BINARY);
*Result:* '4'
This CONVERT example takes the value '4' and converts it as a BINARY datatype with the binary string value of '4'.
The second syntax for the MySQL CONVERT function allows you to convert a value from one character set to another. Let's look at how to use the CONVERT function to convert between character sets. For example:
mysql> SELECT CONVERT('techonthenet.com' USING utf8);
*Result:* 'techonthenet.com'
This CONVERT example takes the value 'techonthenet.com' and converts it from the current character set to the utf8 character set.
We could change our example above to convert the value 'techonthenet.com' to the latin1 character set as follows:
mysql> SELECT CONVERT('techonthenet.com' USING latin1);
*Result:* 'techonthenet.com'
This MySQL tutorial explains how to use the MySQL CURRENT_USER function with syntax and examples.
The MySQL CURRENT_USER function returns the user name and host name for the MySQL account that was used by the server to authenticate the current client.
The syntax for the CURRENT_USER function in MySQL is:
CURRENT_USER( )
There are no parameters or arguments for the CURRENT_USER function in MySQL.
- The CURRENT_USER function uses the utf8 character set.
- See also the USER function which can return a different value than the CURRENT_USER function.
- The SESSION_USER and SYSTEM_USER functions are synonyms of the USER function.
The CURRENT_USER function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0.6
Let's look at some MySQL CURRENT_USER function examples and explore how to use the CURRENT_USER function in MySQL.
For example:
mysql> SELECT CURRENT_USER();
This CURRENT_USER function example would return the user name and host name for the MySQL account that the server used to authenticate the current client.
So if the MySQL account that was used by the server to authenticate the current client was 'root' and the host name was 'localhost':
mysql> SELECT USER();
*Result:* 'root@localhost'
This MySQL tutorial explains how to use the MySQL DATABASE function with syntax and examples.
The MySQL DATABASE function returns the name of the default database.
The syntax for the DATABASE function in MySQL is:
DATABASE( )
There are no parameters or arguments for the DATABASE function in MySQL.
- The DATABASE function uses the utf8 character set as of MySQL 4.1.
- The DATABASE function will return NULL if there is no default database (Starting in MySQL 4.1.1).
- The DATABASE function will return an empty string if there is no default database (Prior to MySQL 4.1.1).
The DATABASE function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL DATABASE function examples and explore how to use the DATABASE function in MySQL.
For example:
mysql> SELECT DATABASE();
*Result:* 'quotations'
This DATABASE function example would return the name of the default database. So if our default database was called quotations this example would return the string 'quotations'.
This MySQL tutorial explains how to use the MySQL IF function with syntax and examples.
The MySQL IF function returns one value if a condition evaluates to TRUE or another value if it evaluates to FALSE.
The syntax for the IF function in MySQL is:
IF( condition value_if_true value_if_false )
condition The value that you want to test. value_if_true Optional. It is the value that is returned if condition evaluates to TRUE. value_if_false Optional. It is the value that is return if condition evaluates to FALSE.
- The MySQL IF function can return either a string or a numeric value depending on the context of how it is used.
The IF function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23.3
Let's look at some MySQL IF function examples and explore how to use the IF function in MySQL.
This first IF function example shows how you would return a string value.
For example:
mysql> SELECT IF(100<200 'yes' 'no');
*Result:* 'yes'
In this IF function example the condition is 100<200. If this condition is TRUE the IF function will return 'yes'. Otherwise the IF function will return 'no'.
The first IF function example uses a numeric condition. However you can also use the IF function with a string condition.
For example:
mysql> SELECT IF(STRCMP('techonthenet.com' 'checkyourmath.com')=0 'yes' 'no');
*Result:* 'no'
In this IF function example the condition uses the STRCMP function to compare 2 strings: STRCMP('techonthenet.com' 'checkyourmath.com').
If the string 'techonthenet.com' is the same as the string 'checkyourmath.com' the IF function will return 'yes'. Otherwise the IF function will return 'no'.
This next IF function example shows how you would return a numeric value.
For example:
mysql> SELECT IF(100<200 5000 6000);
*Result:* 5000
In this IF function example the condition is 100<200. If this condition is TRUE the IF function will return the numeric value 5000. Otherwise if the condition is FALSE the IF function will return 6000.
Let's look at an example that uses the IF function to test the value of a field in a table.
For example:
mysql> SELECT supplier_id supplier_name quantity IF(quantity>10 'More' 'Less')
FROM suppliers;
In this IF function example the IF function tests the value of the quantity field in the suppliers table. The IF function will evaluate the condition quantity>10 for each row in our result set.
So (for each row) if quantity>10 the IF function will return 'More'. Otherwise the IF function will return 'Less'.
This MySQL tutorial explains how to use the MySQL IFNULL function with syntax and examples.
The MySQL IFNULL function allows you to return an alternate value if an expression is NULL.
The syntax for the IFNULL function in MySQL is:
IFNULL( expression value_if_null )
expression The value to test as NULL. value_if_null The value to return if expression is NULL.
- The IFNULL function will return expression if expression is NOT NULL.
- The IFNULL function will return value_if_null if expression is NULL.
- The IFNULL function is similar to the Nz function in MSAccess.
The IFNULL function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL IFNULL function examples and explore how to use the IFNULL function in MySQL.
For example:
mysql> SELECT IFNULL('techonthenet.com' 'checkyourmath.com');
*Result:* 'techonthenet.com'
mysql> SELECT IFNULL(NULL 'checkyourmath.com');
*Result:* 'checkyourmath.com'
mysql> SELECT IFNULL(DATE('2014-02-01') '2014-02-18');
*Result:* '2014-02-01'
mysql> SELECT IFNULL(DATE(NULL) '2014-02-18');
*Result:* '2014-02-18'
mysql> SELECT IFNULL(5 6);
*Result:* 5
mysql> SELECT IFNULL(5/0 'Dividing by 0 returns NULL');
*Result:* 'Dividing by 0 returns NULL'
This MySQL tutorial explains how to use the MySQL ISNULL function with syntax and examples.
The MySQL ISNULL function tests whether an expression is NULL.
The syntax for the ISNULL function in MySQL is:
ISNULL( expression )
expression The value to test if NULL.
- If expression is a NULL value the ISNULL function will return 1.
- If expression is not a NULL value the ISNULL function will return 0.
The ISNULL function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL ISNULL function examples and explore how to use the ISNULL function in MySQL.
For example:
mysql> SELECT ISNULL('techonthenet.com');
*Result:* 0
mysql> SELECT ISNULL('');
*Result:* 0
mysql> SELECT ISNULL(NULL);
*Result:* 1
mysql> SELECT ISNULL(28);
*Result:* 0
This MySQL tutorial explains how to use the MySQL LAST_INSERT_ID function with syntax and examples.
The MySQL LAST_INSERT_ID function returns the first AUTO_INCREMENT value that was set by the most recent INSERT or UPDATE statement that affected an AUTO_INCREMENT column.
The syntax for the LAST_INSERT_ID function in MySQL is:
LAST_INSERT_ID( expression )
expression Optional. If expression is specified the value is returned by LAST_INSERT_ID and remembered as the next value to be returned by the LAST_INSERT_ID function.
- If the most recent INSERT or UPDATE statement set more than one AUTO_INCREMENT value the LAST_INSERT_ID function returns only the first AUTO_INCREMENT value.
- The LAST_INSERT_ID function returns the last AUTO_INCREMENT value on a client-by-client basis so it will only return the last AUTO_INCREMENT value for your client. The value can not be affected by other clients.
- Executing the LAST_INSERT_ID function does not affect the value that LAST_INSERT_ID returns.
The LAST_INSERT_ID function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL LAST_INSERT_ID function examples and explore how to use the LAST_INSERT_ID function in MySQL.
For example if we had the following suppliers table with an AUTO_INCREMENT field called supplier_id:
CREATE TABLE suppliers
( supplier_id INT AUTO_INCREMENT NOT NULL PRIMARY KEY
supplier_name VARCHAR(50) NOT NULL
website VARCHAR(50) );
And the suppliers table contained the following records:
supplier_id | supplier_name | website |
---|---|---|
1 | Tech on the Net | www.techonthenet.com |
2 | Check Your Math | www.checkyourmath.com |
3 | Big Activities | www.bigactivities.com |
And we executed the following INSERT statement:
INSERT INTO suppliers
(supplier_name website)
VALUES
('Oracle' 'www.oracle.com');
The suppliers table would now look like this:
supplier_id | supplier_name | website |
---|---|---|
1 | Tech on the Net | www.techonthenet.com |
2 | Check Your Math | www.checkyourmath.com |
3 | Big Activities | www.bigactivities.com |
4 | Oracle | www.oracle.com |
And if we executed the LAST_INSERT_ID function as follows:
mysql> SELECT LAST_INSERT_ID();
*Result:* 4
The LAST_INSERT_ID function would return 4 since the last INSERT statement inserted a record into the suppliers table with a supplier_id (ie: AUTO_INCREMENT value) of 4.
Let's take a quick look at how the LAST_INSERT_ID function would behave if the most recent INSERT set more than one AUTO_INCREMENT value. In other words what would happen if we inserted 2 records with our last INSERT statement.
Let's look again at the suppliers table with an AUTO_INCREMENT field called supplier_id:
CREATE TABLE suppliers
( supplier_id INT AUTO_INCREMENT NOT NULL PRIMARY KEY
supplier_name VARCHAR(50) NOT NULL );
And the suppliers table contained the following records:
supplier_id | supplier_name | website |
---|---|---|
1 | Tech on the Net | www.techonthenet.com |
2 | Check Your Math | www.checkyourmath.com |
3 | Big Activities | www.bigactivities.com |
4 | Oracle | www.oracle.com |
We also have a customers table with the following records:
customer_id | customer_name |
---|---|
1 | HP |
2 | Samsung |
And we executed the following INSERT statement that uses a SELECT statement to insert more than one record into the suppliers table:
INSERT INTO suppliers
(supplier_name)
SELECT customer_name
FROM customers
ORDER BY customer_id;
After executing this INSERT statement the suppliers table would now look like this:
supplier_id | supplier_name | website |
---|---|---|
1 | Tech on the Net | www.techonthenet.com |
2 | Check Your Math | www.checkyourmath.com |
3 | Big Activities | www.bigactivities.com |
4 | Oracle | www.oracle.com |
5 | HP | null |
6 | Samsung | null |
As you can see the INSERT statement inserted 2 new records into the suppliers table (supplier_id=5 and supplier_id=6).
Now when we execute the LAST_INSERT_ID function as follows:
mysql> SELECT LAST_INSERT_ID();
*Result:* 5
The LAST_INSERT_ID function would return 5 because the record with the supplier_id=5 was the first AUTO_INCREMENT value to be set by the most recent INSERT statement.
This MySQL tutorial explains how to use the MySQL NULLIF function with syntax and examples.
The MySQL NULLIF function returns NULL if two expressions are equivalent. Otherwise it returns the first expression.
The syntax for the NULLIF function in MySQL is:
NULLIF( expression1 expression2 )
expression1 and expression2
Two expressions to test if equivalent expression1 = expression2
.
- The NULLIF function will return NULL if expression1 = expression2 (equal).
- The NULLIF function will return expression1 if expression1 != expression2 (not equal).
The NULLIF function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23.15
Let's look at some MySQL NULLIF function examples and explore how to use the NULLIF function in MySQL.
For example:
mysql> SELECT NULLIF('techonthenet.com' 'techonthenet.com');
*Result:* NULL
mysql> SELECT NULLIF('techonthenet.com' 'checkyourmath.com');
*Result:* 'techonthenet.com'
mysql> SELECT NULLIF(5 5);
*Result:* NULL
mysql> SELECT NULLIF(5 6);
*Result:* 5
This MySQL tutorial explains how to use the MySQL SESSION_USER function with syntax and examples.
The MySQL SESSION_USER function returns the user name and host name for the current MySQL user.
The syntax for the SESSION_USER function in MySQL is:
SESSION_USER( )
There are no parameters or arguments for the SESSION_USER function in MySQL.
- The user name returned is the name of the user specified when connecting to the server.
- The host name returned is the name of the client host that the user connected from.
- The SESSION_USER and SYSTEM_USER functions are synonyms for the USER function.
- See also the CURRENT_USER function which can return a different value than the SESSION_USER function.
The SESSION_USER function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL SESSION_USER function examples and explore how to use the SESSION_USER function in MySQL.
For example:
mysql> SELECT SESSION_USER();
This SESSION_USER function example would return the user name and host name for the current MySQL user.
So if the user name specified when connecting to the server was 'root' and the name of the client host that the user connected from was 'imac.techonthenet.com:
mysql> SELECT SESSION_USER();
*Result:* 'root@imac.techonthenet.com'
This MySQL tutorial explains how to use the MySQL SYSTEM_USER function with syntax and examples.
The MySQL SYSTEM_USER function returns the user name and host name for the current MySQL user.
The syntax for the SYSTEM_USER function in MySQL is:
SYSTEM_USER( )
There are no parameters or arguments for the SYSTEM_USER function in MySQL.
- The user name returned is the name of the user specified when connecting to the server.
- The host name returned is the name of the client host that the user connected from.
- The SESSION_USER and SYSTEM_USER functions are synonyms for the USER function.
- See also the CURRENT_USER function which can return a different value than the SYSTEM_USER function.
The SYSTEM_USER function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL SYSTEM_USER function examples and explore how to use the SYSTEM_USER function in MySQL.
For example:
mysql> SELECT SYSTEM_USER();
This SYSTEM_USER function example would return the user name and host name for the current MySQL user.
So if the user name specified when connecting to the server was 'root' and the name of the client host that the user connected from was 'imac.techonthenet.com:
mysql> SELECT SYSTEM_USER();
*Result:* 'root@imac.techonthenet.com'
This MySQL tutorial explains how to use the MySQL USER function with syntax and examples.
The MySQL USER function returns the user name and host name for the current MySQL user.
The syntax for the USER function in MySQL is:
USER( )
There are no parameters or arguments for the USER function in MySQL.
- The user name returned is the name of the user specified when connecting to the server.
- The host name returned is the name of the client host that the user connected from.
- The SESSION_USER and SYSTEM_USER functions are synonyms for the USER function.
- See also the CURRENT_USER function which can return a different value than the USER function.
The USER function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL USER function examples and explore how to use the USER function in MySQL.
For example:
mysql> SELECT USER();
This USER function example would return the user name and host name for the current MySQL user.
So if the user name specified when connecting to the server was 'root' and the name of the client host that the user connected from was 'imac.techonthenet.com:
mysql> SELECT USER();
*Result:* 'root@imac.techonthenet.com'
This MySQL tutorial explains how to use the MySQL VERSION function with syntax and examples.
The MySQL VERSION function returns the version of the MySQL database.
The syntax for the VERSION function in MySQL is:
VERSION( )
There are no parameters or arguments for the VERSION function in MySQL.
- The VERSION function uses the utf8 character set (starting in MySQL 4.1).
The VERSION function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23
Let's look at some MySQL VERSION function examples and explore how to use the VERSION function in MySQL.
For example:
mysql> SELECT VERSION();
Since the VERSION function returns the version of the MySQL database it might display something like this:
mysql> SELECT VERSION();
*Result:* '5.5.35-0ubuntu0.12.04.2'
This MySQL tutorial explains how to use the MySQL ENCRYPT function with syntax and examples.
The MySQL ENCRYPT function is used to encrypt a string using UNIX crypt().
The syntax for the ENCRYPT function in MySQL is:
ENCRYPT( string salt )
string The plaintext string that is encrypted using UNIX crypt(). salt Optional. The string that is at least 2 characters long that is used in the encryption process. If salt is not provided the ENCRYPT function will use a random value.
- The ENCRYPT function will return NULL if salt is less than 2 characters in length.
- The ENCRYPT function will return NULL if the string is NULL.
- The ENCRYPT function will return NULL if UNIX crypt() is not available on your system.
The ENCRYPT function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1
Let's look at some MySQL ENCRYPT function examples and explore how to use the ENCRYPT function in MySQL.
For example:
mysql> SELECT ENCRYPT('abc');
*Result:* 'HodO.ryHDWKR2'
mysql> SELECT ENCRYPT('password');
*Result:* 'Xp7fKf8gFYoMc'
mysql> SELECT ENCRYPT('techonthenet');
*Result:* 'ipQqyRshr94pU'
mysql> SELECT ENCRYPT('techonthenet' '123');
*Result:* '120RNc3daWyrU'
mysql> SELECT ENCRYPT('techonthenet' '1');
*Result:* NULL
mysql> SELECT ENCRYPT(NULL);
*Result:* NULL
This MySQL tutorial explains how to use the MySQL MD5 function with syntax and examples.
The MySQL MD5 function returns an MD5 128-bit checksum representation of a string.
The syntax for the MD5 function in MySQL is:
MD5( string )
string The plaintext string used to generate the MD5 128-bit checksum.
- The MD5 function will return a 32 character hex string as the result.
- The MD5 function will return NULL if the string was NULL.
- The result from the MD5 function can be used a hash key.
The MD5 function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23.2
Let's look at some MySQL MD5 function examples and explore how to use the MD5 function in MySQL.
For example:
mysql> SELECT MD5('abc');
*Result:* '900150983cd24fb0d6963f7d28e17f72'
mysql> SELECT MD5('password');
*Result:* '5f4dcc3b5aa765d61d8327deb882cf99'
mysql> SELECT MD5('techonthenet');
*Result:* 'f72cde15c34b7201d462392fffdb547f'
mysql> SELECT MD5(NULL);
*Result:* NULL
This MySQL tutorial explains how to use the MySQL OLD_PASSWORD function with syntax and examples.
The MySQL OLD_PASSWORD function is used by the authentication system to generate a hashed password from a plaintext password string using hashing techniques prior to MySQL 4.1. To use newer hashing techniques use the PASSWORD function.
The syntax for the OLD_PASSWORD function in MySQL is:
OLD_PASSWORD( string )
string A plaintext password string that is the source to create an encrypted/hashed password in MySQL using hashing techniques prior to MySQL 4.1.
- The OLD_PASSWORD function will return NULL if the string is NULL.
- The OLD_PASSWORD function was added in MySQL 4.1 when the password hashing techniques changed with the introduction of the PASSWORD function in MySQL 4.1.
- The OLD_PASSWORD function is used by the authentication system in MySQL to store passwords.
- Do not use th OLD_PASSWORD function in your own application use the MD5 or SHA1 functions instead.
- See also the ENCRYPT function.
The OLD_PASSWORD function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1
Let's look at some MySQL OLD_PASSWORD function examples and explore how to use the OLD_PASSWORD function in MySQL.
For example:
mysql> SELECT OLD_PASSWORD('abc');
*Result:* '7cd2b5942be28759'
mysql> SELECT OLD_PASSWORD('password');
*Result:* '5d2e19393cc5ef67'
mysql> SELECT OLD_PASSWORD('techonthenet');
*Result:* '74c3b52b462a1a89'
mysql> SELECT OLD_PASSWORD(NULL);
*Result:* NULL
This MySQL tutorial explains how to use the MySQL PASSWORD function with syntax and examples.
The MySQL PASSWORD function is used by the authentication system in MySQL to generate a hashed password from a plaintext password string using more powerful hashing techniques that were introduced in MySQL 4.1. To use older hashing techniques use the OLD_PASSWORD function.
The syntax for the PASSWORD function in MySQL is:
PASSWORD( string )
string A plaintext password string that is the source to create an encrypted/hashed password in MySQL.
- The PASSWORD function will return NULL if the string is NULL.
- The PASSWORD function performs encryption one-way.
- The PASSWORD function is used by the authentication system in MySQL to store passwords.
- Do not use th PASSWORD function in your own application use the MD5 or SHA1 functions instead.
- See also the ENCRYPT function.
The PASSWORD function can be used in the following versions of MySQL:
- MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1
Let's look at some MySQL PASSWORD function examples and explore how to use the PASSWORD function in MySQL.
For example:
mysql> SELECT PASSWORD('abc');
*Result:* '\*0D3CED9BEC10A777AEC23CCC353A8C08A633045E'
mysql> SELECT PASSWORD('password');
*Result:* '\*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19'
mysql> SELECT PASSWORD('techonthenet');
*Result:* '\*0886644237EED5C45BE221093802B5AB0C06D2D0'
mysql> SELECT PASSWORD(NULL);
*Result:* NULL
The following is a list of datatypes available in MySQL, which includes string, numeric, date/time, and large object datatypes.
The following are the String Datatypes in MySQL:
Data Type Syntax | Maximum Size | Explanation |
---|---|---|
CHAR(size) | Maximum size of 255 characters. | Where size is the number of characters to store. Fixed-length strings. Space padded on right to equal size characters. |
VARCHAR(size) | Maximum size of 255 characters. | Where size is the number of characters to store. Variable-length string. |
TINYTEXT(size) | Maximum size of 255 characters. | Where size is the number of characters to store. |
TEXT(size) | Maximum size of 65,535 characters. | Where size is the number of characters to store. |
MEDIUMTEXT(size) | Maximum size of 16,777,215 characters. | Where size is the number of characters to store. |
LONGTEXT(size) | Maximum size of 4GB or 4,294,967,295 characters. | Where size is the number of characters to store. |
BINARY(size) | Maximum size of 255 characters. | Where size is the number of binary characters to store. Fixed-length strings. Space padded on right to equal size characters. (Introduced in MySQL 4.1.2) |
VARBINARY(size) | Maximum size of 255 characters. | Where size is the number of characters to store. Variable-length string. (Introduced in MySQL 4.1.2) |
The following are the Numeric Datatypes in MySQL:
Data Type Syntax | Maximum Size | Explanation |
---|---|---|
BIT | Very small integer value that is equivalent to TINYINT(1). Signed values range from -128 to 127. Unsigned values range from 0 to 255. |
|
TINYINT(m) | Very small integer value. Signed values range from -128 to 127. Unsigned values range from 0 to 255. |
|
SMALLINT(m) | Small integer value. Signed values range from -32768 to 32767. Unsigned values range from 0 to 65535. |
|
MEDIUMINT(m) | Medium integer value. Signed values range from -8388608 to 8388607. Unsigned values range from 0 to 16777215. |
|
INT(m) | Standard integer value. Signed values range from -2147483648 to 2147483647. Unsigned values range from 0 to 4294967295. |
|
INTEGER(m) | Standard integer value. Signed values range from -2147483648 to 2147483647. Unsigned values range from 0 to 4294967295. |
This is a synonym for the INT datatype. |
BIGINT(m) | Big integer value. Signed values range from -9223372036854775808 to 9223372036854775807. Unsigned values range from 0 to 18446744073709551615. |
|
DECIMAL(m,d) | Unpacked fixed point number. m defaults to 10, if not specified. d defaults to 0, if not specified. |
Where m is the total digits and d is the number of digits after the decimal. |
DEC(m,d) | Unpacked fixed point number. m defaults to 10, if not specified. d defaults to 0, if not specified. |
Where m is the total digits and d is the number of digits after the decimal. This is a synonym for the DECIMAL datatype. |
NUMERIC(m,d) | Unpacked fixed-point number. m defaults to 10, if not specified. d defaults to 0, if not specified. |
Where m is the total digits and d is the number of digits after the decimal. This is a synonym for the DECIMAL datatype. |
FIXED(m,d) | Unpacked fixed-point number. m defaults to 10, if not specified. d defaults to 0, if not specified. |
Where m is the total digits and d is the number of digits after the decimal. (Introduced in MySQL 4.1) This is a synonym for the DECIMAL datatype. |
FLOAT(m,d) | Single precision floating point number. | Where m is the total digits and d is the number of digits after the decimal. |
DOUBLE(m,d) | Double precision floating point number. | Where m is the total digits and d is the number of digits after the decimal. |
DOUBLE PRECISION(m,d) | Double precision floating point number. | Where m is the total digits and d is the number of digits after the decimal. This is a synonym for the DOUBLE datatype. |
REAL(m,d) | Double precision floating point number. | Where m is the total digits and d is the number of digits after the decimal. This is a synonym for the DOUBLE datatype. |
FLOAT(p) | Floating point number. | Where p is the precision. |
BOOL | Synonym for TINYINT(1) | Treated as a boolean data type where a value of 0 is considered to be FALSE and any other value is considered to be TRUE. |
BOOLEAN | Synonym for TINYINT(1) | Treated as a boolean data type where a value of 0 is considered to be FALSE and any other value is considered to be TRUE. |
The following are the Date/Time Datatypes in MySQL:
Data Type Syntax | Maximum Size | Explanation |
---|---|---|
DATE | Values range from '1000-01-01' to '9999-12-31'. | Displayed as 'YYYY-MM-DD'. |
DATETIME | Values range from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'. | Displayed as 'YYYY-MM-DD HH:MM:SS'. |
TIMESTAMP(m) | Values range from '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC. | Displayed as 'YYYY-MM-DD HH:MM:SS'. |
TIME | Values range from '-838:59:59' to '838:59:59'. | Displayed as 'HH:MM:SS'. |
YEAR[(2|4)] | Year value as 2 digits or 4 digits. | Default is 4 digits. |
The following are the LOB Datatypes in MySQL:
Data Type Syntax | Maximum Size | Explanation |
---|---|---|
TINYBLOB | Maximum size of 255 bytes. | |
BLOB(size) | Maximum size of 65,535 bytes. | Where size is the number of characters to store (size is optional and was introduced in MySQL 4.1) |
MEDIUMBLOB | Maximum size of 16,777,215 bytes. | |
LONGTEXT | Maximum size of 4GB or 4,294,967,295 characters. |