Beruflich Dokumente
Kultur Dokumente
This MySQL tutorial explains how to create, drop, disable, and enable a primary key in
MySQL with syntax and examples.
You use the ALTER TABLE statement in MySQL to drop, disable or enable a primary
key.
Syntax
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
Example
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_idcolumn.
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.
Syntax
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.
Example
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
This example we've created a primary key called contacts_pk that is made up of a
combination of the last_name and first_namecolumns.
Syntax
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.
Example
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.
Syntax
The syntax to disable a primary key in MySQL is:
table_name
The name of the table to modify.
Example
Let's look at an example of how to disable a primary key using the ALTER TABLE statement
in MySQL.
ALTER TABLE contacts
DISABLE KEYS;
In this example, we're disabling the keys (ie: primary key) on the contacts table.
Syntax
The syntax to enable a primary key in MySQL is:
ALTER TABLE table_name
ENABLE KEYS;
table_name
The name of the table to modify.
Example
Let's look at an example of how to enable a primary key using the ALTER TABLE statement
in MySQL.
ALTER TABLE contacts
ENABLE KEYS;
In this example, we're enabling the keys (ie: primary key) on the contacts table.
MYSQL: INDEXES
This MySQL tutorial explains how to create, drop, and rename indexes in MySQL with
syntax and examples.
CREATE AN INDEX
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.
Syntax
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 ],
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.
Example
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, 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.
Unique Index
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
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.
DROP AN INDEX
You can drop an index in MySQL using the DROP INDEX statement.
Syntax
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.
Example
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.
RENAME AN INDEX
You can rename an index in MySQL. Depending on your version of MySQL, there are two
different syntaxes.
Syntax
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
Example
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.
DESCRIPTION
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.
Syntax
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
INSERT
UPDATE
DELETE
INDEX
CREATE
ALTER
DROP
GRANT
OPTION
Allows you to grant the privileges that you possess to other users.
ALL
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.
Example
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 namesmithj, 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';
Syntax
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
INSERT
UPDATE
DELETE
INDEX
CREATE
ALTER
DROP
GRANT
OPTION
Allows you to grant the privileges that you possess to other users.
ALL
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.
Example
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.
Syntax
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.
Example - Function
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';
Example - Procedure
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';
Syntax
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
Example - Function
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';
Example - Procedure
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:
DESCRIPTION
The SET PASSWORD statement is used to change a user's password in the MySQL
database.
SYNTAX
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'
};
Parameters or Arguments
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 inplaintext_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.
Note: The FOR user_name parameter must be specified in the format
of user_name@host_name, such as 'jane'@'localhost'.
EXAMPLE
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';
DESCRIPTION
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.
SYNTAX
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.
Note: You can use the LAST_INSERT_ID function to find last value assigned by the
AUTO_INCREMENT field.
EXAMPLE
Let's look at an example of how to use a sequence or the AUTO_INCREMENT attribute in
MySQL.
For example:
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 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.
Syntax
In MySQL, the syntax to change the starting value for an AUTO_INCREMENT column using
the ALTER TABLE statement is:
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.
Example
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.
DESCRIPTION
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.
SYNTAX
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 column [ 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;
Parameters or Arguments
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.
conditions
The conditions that must be met for the update to execute.
ORDER BY
Optional. It may be used in combination with LIMIT to sort the records appropriately
when limiting the number of records to be updated.
LIMIT
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.
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.
This UPDATE example would update only the customers table for all records where
the customer_id is greater than 2000. When thesupplier_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.
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.
DESCRIPTION
The MySQL DELETE statement is used to delete a single record or multiple records from a
table in MySQL.
SYNTAX
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 column [ ASC | DESC ] ]
[ LIMIT number_rows ];
Parameters or Arguments
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, index 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.
conditions
The conditions that must be met for the records to be deleted.
ORDER BY
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.
Note: You do not need to list fields in the MySQL DELETE statement since you are deleting
the entire row from the table.
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';
This MySQL DELETE example would delete all records from the contacts table where
the last_name is 'Johnson' and the customer_idis 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;
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;
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 );
DESCRIPTION
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.
SYNTAX
The syntax for the TRUNCATE TABLE statement in MySQL is:
TRUNCATE TABLE [database_name.]table_name;
Parameters or Arguments
database_name
Optional. If specified, it is the name of the database.
table_name
The table that you wish to truncate.
Note:
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.
EXAMPLE
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.
DESCRIPTION
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.
SYNTAX
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;
Parameters or Arguments
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.
conditions
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.
Note:
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.
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
bysupplier_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.
DESCRIPTION
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 (even if the row exists in more than one of the
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.
SYNTAX
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;
Parameters or Arguments
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.
conditions
The conditions that must be met for the records to be selected.
Note:
The column names from the first SELECT statement are used as the column names
for the result set.
This MySQL UNION ALL operator would return a supplier_id multiple times in your result
set if the supplier_id appeared in both thesuppliers and orders table. The MySQL UNION
ALL operator does not remove duplicates. If you wish to remove duplicates, try using
the MySQL UNION operator.
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.
DESCRIPTION
Although there is no INTERSECT operator in MySQL, you can easily simulate this type of
query using either the IN clause or theEXISTS 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.
Intersect Query
Explanation: The INTERSECT query will return the records in the blue shaded area. These
are the records that exist in both Dataset1 and Dataset2.
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
In this example, the WHERE clauses have been added that filter both the products table as
well as the results from the inventory table.
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
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 thecontact_id, last_name, and first_name fields
from the contacts table.
MYSQL: SUBQUERIES
This MySQL tutorial explains how to use subqueries in MySQL with syntax and examples.
In MySQL, the main query that contains the subquery is also called the OUTER
QUERY or OUTER SELECT.
WHERE CLAUSE
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);
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.
FROM CLAUSE
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;
This subquery has been aliased with the name subquery1. This will be the name used to
reference this subquery or any of its fields.
SELECT CLAUSE
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;
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.
MYSQL: JOINS
This MySQL tutorial explains how to use MySQL JOINS (inner and outer) with syntax, visual
illustrations, and examples.
DESCRIPTION
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:
So let's discuss MySQL JOIN syntax, look at visual illustrations of MySQL JOINS, and
explore MySQL JOIN examples.
Syntax
The syntax for the INNER JOIN in MySQL is:
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;
Visual Illustration
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.
Example
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;
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.
Old Syntax
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;
Syntax
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.
Visual Illustration
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.
Example
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;
supplier_id
supplier_name
order_date
10000
IBM
2013/05/12
10001
Hewlett Packard
2013/05/13
10002
Microsoft
<null>
10003
NVIDIA
<null>
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 <null>
value.
Syntax
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.
Visual Illustration
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.
Example
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;
order_id
order_date
supplier_name
500125
2013/08/12
Apple
500126
2013/08/13
500127
2013/08/14
<null>
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 <null>
value.
MYSQL: ALIASES
This MySQL tutorial explains how to use MySQL ALIASES (temporary names for columns
or tables) with syntax and examples.
DESCRIPTION
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).
SYNTAX
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
Parameters or Arguments
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.
Note:
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.
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:
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.
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.
DESCRIPTION
The MySQL CREATE TABLE statement allows you to create and define a table.
SYNTAX
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' ],
...
| [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)
| 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, ... )
);
Parameters or Arguments
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 ]
Note: There can only be one column in a table that is set as AUTO_INCREMENT and this
column must be the primary key.
EXAMPLE
Let's look at a MySQL CREATE TABLE example.
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 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.
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 primary key is called suppliers_pk and is set to the supplier_id column.
DESCRIPTION
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).
SYNTAX
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;
Parameters or Arguments
IF NOT EXISTS
Optional. If specified, the CREATE TABLE AS statement will not raise an error if the
table already exists.
table_name
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).
conditions
The conditions that must be met for the records to be copied to the new_table.
Note:
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.
EXAMPLE
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.
DESCRIPTION
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.
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.
Example
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.
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.
Example
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. Thefirst_name column will be created as a
varchar(35) NULL column and will appear after the last_name column in the table.
table_name
Example
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.
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.
Example
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. Thefirst_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).
table_name
The name of the table to modify.
column_name
The name of the column to delete from the table.
Example
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.
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.
Example
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.
RENAME TABLE
Syntax
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.
Example
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.
MYSQL: VIEW
This MySQL tutorial explains how to create, update, and drop VIEWS in MySQL with
syntax and examples.
CREATE VIEW
Syntax
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.
Example
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
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;
UPDATE VIEW
You can modify the definition of a VIEW in MySQL without dropping it by using the ALTER
VIEW statement.
Syntax
The syntax for the ALTER VIEW statement in MySQL is:
ALTER VIEW view_name AS
SELECT columns
FROM table
WHERE conditions;
Example
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.
DROP VIEW
Once a VIEW has been created in MySQL, you can drop it with the DROP VIEW statement.
Syntax
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.
Example
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.
STRING DATATYPES
The following are the String Datatypes in MySQL:
Data Type Syntax
Maximum Size
Explanation
CHAR(size)
VARCHAR(size)
TINYTEXT(size)
TEXT(size)
Maximum size of
65,535 characters.
Maximum size of
MEDIUMTEXT(size
16,777,215
)
characters.
LONGTEXT(size)
BINARY(size)
VARBINARY(size)
NUMERIC DATATYPES
The following are the Numeric Datatypes in MySQL:
Data Type
Syntax
Maximum Size
BIT
TINYINT(m)
SMALLINT(m)
MEDIUMINT(m)
INT(m)
Explanation
from 0 to 4294967295.
INTEGER(m)
BIGINT(m)
DECIMAL(m,d)
DEC(m,d)
NUMERIC(m,d)
FIXED(m,d)
DECIMAL datatype.
FLOAT(m,d)
DOUBLE(m,d)
DOUBLE
PRECISION(m,d)
REAL(m,d)
FLOAT(p)
BOOL
BOOLEAN
DATE/TIME DATATYPES
The following are the Date/Time Datatypes in MySQL:
Data Type
Syntax
Maximum Size
Explanation
DATE
Displayed as 'YYYY-MMDD'.
DATETIME
TIMESTAMP(m)
TIME
Displayed as 'HH:MM:SS'.
YEAR[(2|4)]
Default is 4 digits.
Maximum Size
TINYBLOB
BLOB(size)
Explanation
MEDIUMBLOB
Maximum size of
16,777,215 bytes.
LONGTEXT