Mysql

Published on March 2017 | Categories: Documents | Downloads: 50 | Comments: 0 | Views: 257
of 89
Download PDF   Embed   Report

Comments

Content

MYSQL: PRIMARY KEYS
This MySQL tutorial explains how to create, drop, disable, and enable a primary key in
MySQL with syntax and examples.

WHAT IS A PRIMARY KEY IN MYSQL?
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.
Note:


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.

CREATE PRIMARY KEY - USING CREATE TABLE STATEMENT
You can create a primary key in MySQL with the CREATE TABLE statement.

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

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.

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.

CREATE PRIMARY KEY - USING ALTER TABLE STATEMENT
You can create a primary key in MySQL with the ALTER TABLE statement.

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

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_namecolumns.

DROP PRIMARY KEY
You can drop a primary key in MySQL using the ALTER TABLE statement.

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.

DISABLE PRIMARY KEY
You can disable a primary key in MySQL using the ALTER TABLE statement.

Syntax
The syntax to disable a primary key in MySQL is:

ALTER TABLE table_name
DISABLE KEYS;

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.

ENABLE PRIMARY KEY
You can enable a primary key in MySQL using the ALTER TABLE statement.

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.

WHAT IS AN INDEX IN MYSQL?
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.

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 ],

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.

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, we've created the contacts table as well as an index
called contacts_idx which consists of the last_name andfirst_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.
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

( 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.

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

The name of the index that you wish to rename.
new_index_name
The new name for the index.

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.

MYSQL: GRANT/REVOKE PRIVILEGES
This MySQL tutorial explains how to grant and revoke privileges in MySQL with syntax
and examples.

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.

GRANT PRIVILEGES ON TABLE
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.

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

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.

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

REVOKE PRIVILEGES ON TABLE
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.

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

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.

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

GRANT PRIVILEGES ON FUNCTIONS/PROCEDURES

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

REVOKE PRIVILEGES ON FUNCTIONS/PROCEDURES
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.

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

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.

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

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

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:

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

MYSQL: CHANGE A USER PASSWORD
This MySQL tutorial explains how to change a user's password in MySQL with syntax and
examples.

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

MYSQL: SEQUENCES (AUTO_INCREMENT)
This MySQL tutorial explains how to create sequences using the AUTO_INCREMENT
attribute in MySQL with syntax and examples.

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:

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.

SET AUTO_INCREMENT STARTING VALUE
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.

Syntax
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.

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.

MYSQL: UPDATE STATEMENT
This MySQL tutorial explains how to use the MySQL UPDATE statement with syntax and
examples.

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.

EXAMPLE - UPDATE SINGLE COLUMN
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.

EXAMPLE - UPDATE MULTIPLE COLUMNS
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.

EXAMPLE - UPDATE TABLE WITH DATA FROM ANOTHER TABLE
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 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.

EXAMPLE - UPDATE MULTIPLE TABLES
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.

MYSQL: DELETE STATEMENT
This MySQL tutorial explains how to use the MySQL DELETE statement with syntax and
examples.

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.

EXAMPLE - WITH ONE CONDITION
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';

EXAMPLE - WITH TWO CONDITIONS
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_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;

EXAMPLE - WITH LIMIT MODIFIER
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;

EXAMPLE - USING EXISTS CONDITION
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 );

MYSQL: TRUNCATE TABLE STATEMENT
This MySQL tutorial explains how to use the MySQL TRUNCATE TABLE statement with
syntax and examples.

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.

MYSQL: UNION OPERATOR
This MySQL tutorial explains how to use the MySQL UNION operator with syntax and
examples.

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:


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.

EXAMPLE - RETURN SINGLE FIELD
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.

EXAMPLE - USING ORDER BY
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
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.

MYSQL: UNION ALL OPERATOR
This MySQL tutorial explains how to use the MySQL UNION ALL operator with syntax and
examples.

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:



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.

EXAMPLE - RETURN SINGLE FIELD
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 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.

EXAMPLE - USING ORDER BY
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.

MYSQL: INTERSECT OPERATOR
This MySQL tutorial explains how to use the INTERSECT operator with syntax and
examples.

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.

EXAMPLE - WITH SINGLE EXPRESSION
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.

EXAMPLE - WITH MULTIPLE EXPRESSIONS
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 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.

WHAT IS A SUBQUERY IN MYSQL?
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.
Note:


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.

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

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.

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;

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.

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;

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.

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:


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.

INNER JOIN (SIMPLE JOIN)
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.

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;

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.

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;

LEFT OUTER JOIN
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).

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;

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

<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.

RIGHT OUTER JOIN
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).

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

Google

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

Google

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.

EXAMPLE - ALIAS A COLUMN
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.

EXAMPLE - ALIAS A TABLE
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.

MYSQL: CREATE TABLE STATEMENT
This MySQL tutorial explains how to use the MySQL CREATE TABLE statement with
syntax and examples.

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' ],

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

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.

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.

MYSQL: CREATE TABLE AS STATEMENT
This MySQL tutorial explains how to use the MySQL CREATE TABLE AS statement with
syntax and examples.

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.

MYSQL: ALTER TABLE STATEMENT
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).

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.

ADD COLUMN IN TABLE
Syntax
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.

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.

ADD MULTIPLE COLUMNS IN TABLE
Syntax
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.

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.

MODIFY COLUMN IN TABLE
Syntax
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.

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.

MODIFY MULTIPLE COLUMNS IN TABLE
SyntaX
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.

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

DROP COLUMN IN TABLE
Syntax
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.

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.

RENAME COLUMN IN TABLE
Syntax
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.

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.

WHAT IS A VIEW IN MYSQL?
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.

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

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;

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.

MYSQL: DATA TYPES
The following is a list of datatypes available in MySQL, which includes string, numeric,
date/time, and large object datatypes.

STRING 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.

Maximum size of
MEDIUMTEXT(size
16,777,215
)
characters.

LONGTEXT(size)

BINARY(size)

Where size is the number of characters to
store.

Maximum size of 4GB
Where size is the number of characters to
or 4,294,967,295
store.
characters.
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)

NUMERIC DATATYPES
The following are the Numeric Datatypes in MySQL:
Data Type
Syntax

Maximum Size

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

Explanation

from 0 to 4294967295.

INTEGER(m)

Standard integer value.
Signed values range from -2147483648
to 2147483647. Unsigned values range
from 0 to 4294967295.

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.

DEC(m,d)

NUMERIC(m,d)

FIXED(m,d)

Unpacked fixed point number.
m defaults to 10, if not specified.
d defaults to 0, if not specified.

Unpacked fixed-point number.
m defaults to 10, if not specified.
d defaults to 0, if not specified.

Unpacked fixed-point number.
m defaults to 10, if not specified.
d defaults to 0, if not specified.

This is a synonym for the
INT datatype.

Where m is the total digits
and d is the number of
digits after the decimal.
Where m is the total digits
and d is the number of
digits after the decimal.
This is a synonym for the
DECIMAL datatype.
Where m is the total digits
and d is the number of
digits after the decimal.
This is a synonym for the
DECIMAL datatype.
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)

DOUBLE(m,d)

DOUBLE
PRECISION(m,d)

Single precision floating point number.

Where m is the total digits
and d is the number of
digits after the decimal.

Double precision floating point number.

Where m is the total digits
and d is the number of
digits after the decimal.

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)

BOOL

BOOLEAN

Floating point number.

Where p is the precision.

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.

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.

DATE/TIME DATATYPES
The following are the Date/Time Datatypes in MySQL:
Data Type
Syntax

Maximum Size

Explanation

DATE

Values range from '1000-01-01' to '999912-31'.

Displayed as 'YYYY-MMDD'.

DATETIME

Values range from '1000-01-01 00:00:00'
to '9999-12-31 23:59:59'.

Displayed as 'YYYY-MMDD 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-MMDD 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.

LARGE OBJECT (LOB) DATATYPES
The following are the LOB Datatypes in MySQL:
Data Type
Syntax

Maximum Size

TINYBLOB

Maximum size of 255
bytes.

BLOB(size)

Maximum size of 65,535
bytes.

Explanation

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.

Sponsor Documents

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close