MY SQL
MY SQL
2. Network
Full stack application
It allows us to hold the data into tables-> rows, columns, and index
We can access and manage the records through the database very easily.
create a database mainly in two ways:
>show databases ;
We can create tables bu using databases
use table3;
All the database names, table names, and table field names are case sensitive.
Case sensitive uppercase or lowercase dogha chalel.
MySQL Workbench
This visual tool supports SQL development, data modeling, data migration, and
comprehensive administration tools for server configuration, user administration,
backup, and many more.
Data modeling is a process that helps you organize data into relational
tables or object types
Data migration in MySQL refers to the process of transferring data from
one database to another
>show databases;
>show schemas
Pattern Matching clause (like and where )
DROP Database
rules or conditions
delete database along with all the tables, indexes, and constraints permanently.
If the database is not available in the MySQL server, the DROP DATABASE
statement throws an error.
syntax:
Example:
COPY Database
three-step process:
1. First, the original database records are dumped (copied) to a temporary file that
holds the SQL commands for reinserting the data into the new database.
3. Finally, the SQL file is processed, and the data will be copied into the new
database.
For the demonstration, we will copy the testdb database to testdb_copy database
In the next step, we need to use the mysqldump tool to copy the database objects
and data into the SQL file. Suppose we want to dump (copy) the database objects and
data of the testdb into an SQL file located at D:\Database_backup folder. To do
this, execute the below statement:
The above statement instructs mysqldump tool to log in to the MySQL database
server using the username and password and then exports the database objects and
data of the testdb database to D:\Database_backup\testdb.sql. It is to note that
the operator (>) used for exporting the database from one location to another.
It is to note that the operator (<) used for importing the database from one
location to another.
Finally, we can verify whether the above operation is successful or not by using
the SHOW TABLES command in the MySQL command-line tool:
In this output, we can see that all the objects and data from the testdb database to
testdb_copy database have successfully copied.
MySQL Keys
MySQL Unique Key
It can accept a null value, allowed only one null value per column.
Syntax
If we want to create more than one unique key column into a table, use the syntax as
below:
Output
If you want to define the unique key on multiple columns, use the query as below:
In the output, we can see that the unique key value contains two columns that
are Roll_No and Email.
To verify this, execute the following statement:
Here, we can see that the unique constraint has successfully added into the table:
In the above syntax, the table_name is the name of the table that we want to
modify, and constraint_name is the name of the unique key we are going to remove.
Example
This statement will remove the uc_rollno_email constraint from the table
permanently.
Syntax
Following are the syntax of the ALTER TABLE statement to add a unique key:
Example
This statement creates a table "Students3" that have no unique key column into the
table definition.
After creating a table, if we want to add a unique key to this table, we need to
execute the ALTER TABLE statement as below:
Here, we can see that the unique constraint has successfully added into the table:
MySQL primary key is a single or combination of the field, which is used to identify
each record in a table uniquely.
If the column contains primary key constraints, then it cannot be null or empty.
A table may have duplicate columns, but it can contain only one primary key. It
always contains unique value into a column.
When you insert a new row into the table, the primary key column can also use
the AUTO_INCREMENT attribute to generate a sequential number for that row
automatically. MySQL automatically creates an index named "Primary" after defining
a primary key into the table. Since it has an associated index, we can say that the
primary key makes the query performance fast.
Syntax
If we want to create more than one primary key column into the table, use the below
syntax:
Output
In the below output, we can see that the first insert query executes successfully.
While the second insert statement fails and gives an error that says: Duplicate entry
for the primary key column.
If you want to define the primary key on multiple columns, use the query as below:
In the output, we can see that the primary key value contains two columns that
are Student_ID and Roll_No.
When the table does not have a primary key, this statement is used to add the
primary key to the column of an existing table.
Syntax
Following are the syntax of the ALTER TABLE statement to create a primary key in
MySQL:
Example
The following statement creates a table "Persons" that have no primary key column
into the table definition.
After creating a table, if we want to add a primary key to this table, we need to
execute the ALTER TABLE statement as below:
If the table needs to add the primary key into a table that already has data into the
column, then it must be sure to the column does not contains duplicates or null
values.
DROP Primary Key
The ALTER TABLE statement also allows us to drop the primary key from the table.
The following syntax is used to drop the primary key:
Example
The following comparison chart explains some of the common differences between
both of them:
1. It is a single or combination of the field, which It also determines each row of the table
is used to identify each record in a table uniquely in the absence of a primary
uniquely. key.
2. It does not allow to store a NULL value into the It can accept only one NULL value into
primary key column. the unique key column.
3. A table can have only one primary key. A table can have more than one unique
key.
The foreign key is used to link one or more than one table together.
It means a foreign key field in one table refers to the primary key field of the other
table.
It identifies each row of another table uniquely that maintains the referential
integrity in MySQL.
Syntax
CREATE TABLE OR ALTER TABLE
1. [CONSTRAINT constraint_name]
2. FOREIGN KEY [foreign_key_name] (col_name, ...)
3. REFERENCES parent_tbl_name (col_name,...)
4. ON DELETE referenceOption
5. ON UPDATE referenceOption
col_name: It is the names of the column that we are going to make foreign key.
MySQL contains five different referential options, which are given below:
CASCADE: It is used when we delete or update any row from the parent table, the
values of the matching rows in the child table will be deleted or updated
automatically.
SET NULL: It is used when we delete or update any row from the parent table, the
values of the foreign key columns in the child table are set to NULL.
RESTRICT: It is used when we delete or update any row from the parent table that
has a matching row in the reference(child) table, MySQL does not allow to delete or
update rows in the parent table.
SET DEFAULT: The MySQL parser recognizes this action. However, the InnoDB and
NDB tables both rejected this action.
NOTE: MySQL mainly provides full support to CASCADE, RESTRICT, and SET NULL
actions. If we have not specified the ON DELETE and ON UPDATE clause, MySQL takes
default action RESTRICT.
Next, we need to create two tables named "customer" and "contact" using the
below statement:
Table: customer
1. customer (
2. ID INT NOT NULL AUTO_INCREMENT,
3. Name varchar(50) NOT NULL,
4. City varchar(50) NOT NULL,
5. PRIMARY KEY (ID)
6. );
Table: contact
Now, we have to insert the records into both tables. Execute this statement to insert
data into table customer:
It means if we delete any customer record from the customer table, then the related
records in the contact table should also be deleted. And the ON UPDATE CASCADE will
updates automatically on the parent table to referenced fields in the child table(Here,
it is Customer_Id).
Execute this statement that deletes a record from the table whose name is JOHN.
Again, if we look at our tables, we can see that both tables were changed. It means
the fields with name JOHN will be removed entirely from both tables.
Now, test the ON UPDATE CASCADE. Here, we are going to update the Customer_Id
of Mary in the contact table as:
First, we have to create two table named Persons and Contacts, as shown below:
Table: Persons
Table: Customers
Next, we need to insert the data into both tables using the following statement:
MySQL allows the ALTER TABLE statement to remove an existing foreign key
from the table. The following syntax is used to drop a foreign key:
Here, the table_name is the name of a table from where we are going to remove the
foreign key. The constraint_name is the name of the foreign key that was added
during the creation of a table.
If we have not known the name of an existing foreign key into the table, execute the
following command:
It will give the output as below where we can see that the table contact has one
foreign key named fk_customer shown in the red rectangle.
Now, to delete this foreign key constraint from the contact table, execute the
statement as below:
We can verify whether foreign key constraint removes or not, use the SHOW CREATE
TABLE statement. It will give the output as below where we can see that the foreign
key is no longer available in the table contact.
This statement allows us to do the modification into the existing table. Sometimes
there is a need to add a foreign key to the column of an existing table; then, this
statement is used to add the foreign key for that column.
Syntax
Following are the syntax of the ALTER TABLE statement to add a foreign key in the
existing table:
When we add a foreign key using the ALTER TABLE statement, it is recommended to
first create an index on the column(s), which is referenced by the foreign key.
Example
The following statement creates two tables, "Person" and "Contact", without having
a foreign key column into the table definition.
Table: Person
Table: Contact
After creating a table, if we want to add a foreign key to an existing table, we need to
execute the ALTER TABLE statement as below:
Sometimes there is a need for disabling the foreign key checking, which is very useful
when:
1. SET foreign_key_checks = 0;
1. SET foreign_key_checks = 1;
MySQL Composite Key
Any key such as primary key, super key, or candidate key can be called
composite key when they have combined with more than one attribute.
A composite key is useful when the table needs to identify each record with
more than one attribute uniquely.
A column used in the composite key can have different data types.
Thus, it is not required to be the same data type for the columns to make a
composite key in MySQL.
In the above statement, we have created a composite primary with the column
names Name and Manufacturer.
1. DESCRIBE Product;
After the successful execution, we can see that the Key column has two PRI. It means
we have successfully added the composite primary key on Name and Manufacturer
columns.
Next, we need to insert the values into this table as given below:
Again execute the below insert statement to understand composite key more clearly:
second insert statement, it will be added successfully into the table. It is because we
can insert any number of soap in the product column, but the manufacturer column
should be different.
Hence, we can say that the composite key always enforces the uniqueness of the
columns of that table, which has two keys.
Now, execute the ALTER TABLE statement to add a composite primary key as follows:
We can verify the composite primary key added into a table or not using the following
command:
1. DESCRIBE Student;
In the output, we can see that the key column has PRI, which means we have
successfully added the composite primary key to stud_id and subject columns.
acno Cid Type balance
1 100 saving 50000
2 100 current 400000
3 100 Demat 400000
4 101 saving 600000
5 101
Marks
Employee table
Alternate key—all candidate keys which are not chosen as primary key are
alternate key
Candidate key---Any minimal set of attributes which identifies the row uniquely is a
candidate key
Employee table
Empid , adhar num, email,passportno,mpbile
Super Key-→ any combination which identifies the row uniquely is called as super
key.
Unique key---→the attribute whose values should be unique, but it is not primary key,
MySQL allows us to create a table into the database mainly in two ways:
Parameter Explanation
Parameter Description
database_nam It is the name of a new table. It should be unique in the MySQL database that we
e avoids an error when we create a table into the selected database that already exi
column_definiti It specifies the name of the column along with data types for each column. The c
on by the comma operator. The syntax of column
column_name1 data_type(size) [NULL | NOT NULL]
table_constrain It specifies the table constraints such as PRIMARY KEY, UNIQUE KEY, FOREIGN KEY,
ts
Example
Let us understand how to create a table into the database with the help of an
example. Open the MySQL console and write down the password, if we have set
during installation. Now open the database in which you want to create a table. Here,
we are going to create a table name "employee_table" in the
database "employeedb" using the following statement:
We can use the following command to see the information or structure of the newly
created table:
1. Go to the Navigation tab and click on the Schema menu. Here, we can see all the
previously created databases. Now we are ready to select the database in which a
table is created.
2. Select the database, double click on it, and we will get the sub-menu under the
database. These sub-menus are Tables, Views, Functions, and Stored Procedures, as
shown in the below screen.
3. Select Tables sub-menu, right-click on it, and select Create Table option. We can
also click on create a new table icon (shown in red rectangle) to create a table.
4. On the new table screen, we need to fill all the details to create a table. Here, we
will enter the table name (for example, employee_table) and use default collation
and engine.
5. Click inside the middle window and fill the column details. Here, the column name
contains many attributes such as Primary Key(PK), Not Null (NN), Unique Index (UI),
Binary(B), Unsigned Data type(UN), Auto Incremental (AI), etc. The following screen
explains it more clearly. After filling all the details, click on the Apply button.
6. As soon as you click on the Apply button, it will open the SQL statement window.
Again, click on the Apply button to execute the statement and Finish button to save
the changes.
7. Now, go to the Schema menu and select the database which contains the newly
created table, as shown in the screen below.
MySQL ALTER Table
MySQL ALTER statement is used when you want to change the name of your table or
any table field. It is also used to add or delete an existing column in a table.
The ALTER statement is always used with "ADD", "DROP" and "MODIFY" commands
according to the situation.
Parameters
table_name: It specifies the name of the table that you want to modify.
new_column_name: It specifies the name of the new column that you want to add to the
table.
column_definition: It specifies the data type and definition of the column (NULL or NOT
NULL, etc).
FIRST | AFTER column_name: It is 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:
In this example, we add a new column "cus_age" in the existing table "cus_tbl".
Output:
Output:
Example:
In this example, we add two new columns "cus_address", and cus_salary in the
existing table "cus_tbl". cus_address is added after cus_surname column and
cus_salary is added after cus_age column.
Syntax:
Example:
Let's take an example to drop the column name "cus_address" from the table
"cus_tbl".
Output:
See the table structure:
Example:
Output:
6) RENAME table
Syntax:
Example:
Output:
See the renamed table:
Step 1: Open the MySQL Command Line Client that appeared with a mysql>
prompt. Next, log in to the MySQL database server using the password that you
have created during the installation of MySQL. Now, you are connected to the MySQL
server, where you can execute all the SQL statements.
Step 2: Next, choose the specific database by using the command below:
Let us understand it with the example given below. Suppose we have a database
name "mystudentdb" that contains many tables. Then execute the below statement
to list the table it contains:
We can also use the FULL modifier with the SHOW TABLES query to get the type of
table (Base or View) that appears in a second output column.
When we execute the below statements, we will get the same result:
Output:
Syntax
The following are the syntax to use pattern matching with show table command:
We can understand it with the example given below where percent (%) sign assumes
zero, one, or multiple characters:
Let us see another statement that returned the table names starting with "time":
Now, we are going to see how we can use the WHERE clause with the SHOW TABLES
command to list different types of tables (either Base or View type) in the selected
database:
Here, we can also see another example of Show Tables statement with the WHERE
clause:
NOTE: If we use the RENAME TABLE statement, it is required to have ALTER and DROP TABLE
privileges to the existing table. Also, this statement cannot change the name of a temporary
table.
We can also use the MySQL RENAME TABLE statement to change more than one
table name with a single statement, as shown below:
From the MySQL 8.0.13 version, we can change the old table name locked with a
LOCK statement and also uses the WRITE LOCK clause. For example, following are the
valid statement:
Before MySQL 8.0.13 version, we cannot change the table name that was locked with
the LOCK TABLE statement.
MySQL also use the RENAME TABLE statement for moving a table from one database
to other database, which is show below:
Output
We will see that the table named "employee" will be changed into a new table name
"customer":
In the above output, we can see that if we use the table name employee after
executing a RENAME TABLE statement, it will throw an error message.
Output
We can see that the table name customer into employee and table name shirts into
garments have successfully renamed.
See the following query that changes the existing table name garments into new table
name shirts:
Output
Here, we can see that the table name garments renamed into table name shirts.
Next, run the show table command to check the temporary table:
Now, run the following command to change the name of the temporary table:
Thus, MySQL allows ALTER table statement to rename the temporary table:
The TRUNCATE command works the same as a DELETE command without using
a WHERE clause that deletes complete rows from a table. However, the TRUNCATE
command is more efficient as compared to the DELETE command because it removes
and recreates the table instead of deleting single records one at a time. Since this
command internally drops the table and recreates it, the number of rows affected by
the truncate statement is zero, unlike the delete statement that returns the number of
deleted rows.
This command does not maintain the transaction log during the execution. It
deallocates the data pages instead of rows and makes an entry for the deallocating
pages instead of rows in transaction logs. This command also locks the pages instead
of rows; thus, it requires fewer locks and resources.
The following points must be considered while using the TRUNCATE command:
o We cannot use the WHERE clause with this command so that filtering of records is not
possible.
o We cannot rollback the deleted data after executing this command because the log
is not maintained while performing this operation.
o We cannot use the truncate statement when a table is referenced by a foreign key or
participates in an indexed view.
o The TRUNCATE command doesn't fire DELETE triggers associated with the table that is
being truncated because it does not operate on individual rows.
Syntax
The following syntax explains the TRUNCATE command to remove data from the
table:
In this syntax, first, we will specify the table name which data we are going to
remove. The TABLE keyword in the syntax is not mandatory. But it's a good practice
to use it to distinguish between the TRUNCATE() function and the TRUNCATE TABLE
statement.
Next, we will add values to this table using the below statement:
1. INSERT INTO customer ( Id, Name, Product, Country, Year)
2. VALUES (1, 'Stephen', 'Computer', 'USA', 2015),
3. (2, 'Joseph', 'Laptop', 'India', 2016),
4. (3, 'John', 'TV', 'USA', 2016),
5. (4, 'Donald', 'Laptop', 'England', 2015),
6. (5, 'Joseph', 'Mobile', 'India', 2015),
7. (6, 'Peter', 'Mouse', 'England', 2016);
Now, verify the table by executing the SELECT statement whether the records
inserted or not:
Now, execute the following statement that truncates the table customer using the
TRUNCATE syntax discussed above:
As we can see, this query returns 0 rows are affected even if all the table records
are deleted. We can verify the deletion of the data by executing the SELECT
statement again. This command gives the following output that shows none of the
records present in the table:
How to Truncate Table with Foreign key?
If we perform the TRUNCATE operation for the table that uses a foreign key constraint,
we will get the following error:
1. ERROR 1217 (23000): Cannot delete or update a parent row: a foreign key c
onstraint fails
In that case, we need to log into the MySQL server and disable foreign key checks
before executing the TRUNCATE statement as below:
1. SET FOREIGN_KEY_CHECKS=0;
Now, we are able to truncate tables. After execution, re-enable foreign key checks
as given below:
1. SET FOREIGN_KEY_CHECKS=1;
How to truncate all tables in MySQL?
The TRUNCATE statement in MySQL will delete only one table at a time. If we want to
delete more than one table, we need to execute the separate TRUNCATE statement.
The below example shows how to truncate multiple tables in MySQL:
We can also use the below SQL query that generates several TRUNCATE TABLE
commands at once using the table names in our database:
Syntax
The following are the syntax to display the table structure:
We can use the following steps to show all columns of the table:
Let us understand it with the help of an example that explains how to show columns
of the table in the selected database.
1. >mysql -u root -p
2. Enter password: **********
3. mysql>
Switch to a Specific Database
The next step is to open a particular database from which you want to display the
table information using the following query. After the execution of a query, we should
see the below output:
For example, if we want to show a customer table's structure, execute the below
statement. After successful execution, it will give the output as below image:
1. Go to the Navigation tab and click on the Schema menu. Here, we can see all
the previously created databases. Select any database under the Schema menu, for
example, mysqltestdb. It will pop up the multiple options that can be shown in the
following image.
2. Next, click on the "Tables" that shows all tables stored in the mysqltestdb
database. Select a table whose column information you want to display. Then, mouse
hour on that table, it will show three icons. See the below image:
Now, click the icon (i) shown in the red rectangular box. It will display the following
image:
Finally, click on the "Columns" menu to display the table structure.
Syntax:
For example, if we execute the below query, we will get all columns information of a
table in a particular database:
In the below image, we can see that we had used the mysqltestdb database. But we
had displayed the column's information of a table from another database without
switching to the current database.
If we want to display the more column information, we need to add FULL keyword
with the SHOW TABLES statement as follows:
For example, the below SQL query lists all columns of the student_info table in
the mystudentdb database:
After execution, we can see that this command adds the collation, privileges,
default, and comment columns to the result set.
MySQL EXPLAIN
The EXPLAIN keyword is synonyms to the DESCRIBE statement, which is used to
obtain information about how MySQL executes the queries. It can work
with INSERT, SELECT, DELETE, UPDATE, and REPLACE queries. From MySQL
8.0.19 and later versions, it can also work with TABLE statements. When we use this
keyword in queries, it will process the statement and provide the information about
how tables are joined, the order of the table, estimated partitions and rows.
Example
If we want to show the execution plan of a SELECT statement, we can use the query
as below:
Output:
Syntax
The following are the syntax to remove the table in MySQL:
The above syntax used many parameters or arguments. Let us discuss each in detail:
TEMPORARY It is an optional parameter that specifies to delete the temporary tables only.
table_name It specifies the name of the table which we are going to remove from the data
IF EXISTS It is optional, which is used with the DROP TABLE statement to remove the tab
RESTRICT and Both are optional parameters that do not have any impact or effect on this st
CASCADE for future versions of MySQL.
NOTE: It is to be noted that you must have a DROP privileges to execute the DROP TABLE
statement in the MySQL.
Example
This example specifies how we can drop an existing table from the database. Suppose
our database contains a table "orders" as shown in the image below:
To delete the above table, we need to run the following statement:
It will remove the table permanently. We can also check the table is present or not as
shown in the below output:
If we try to delete a table that does not exist in the database, we will get an error
message as given below:
If we use the IF EXISTS clause with the DROP TABLE statement, MySQL gives the
warning message which can be shown in the below output:
If we use a PHP script to run the code, this table removes automatically as long as
the script has finished its execution. If the user is connected with the server through
the MySQL client, then this table will exist until the user closes the MySQL client
program or terminates the connection or removed the table manually.
A temporary table provides a very useful and flexible feature that allows us to achieve
complex tasks quickly, such as when we query data that requires a single SELECT
statement with JOIN clauses. Here, the user can use this table to keep the output and
performs another query to process it.
A temporary table in MySQL has many features, which are given below:
o MySQL uses the CREATE TEMPORARY TABLE statement to create a temporary table.
o This statement can only be used when the MySQL server has the CREATE TEMPORARY
TABLES privilege.
o It can be visible and accessible to the client who creates it, which means two different
clients can use the temporary tables with the same name without conflicting with each
other. It is because this table can only be seen by that client who creates it. Thus, the
user cannot create two temporary tables with the same name in the same session.
o A temporary table in MySQL will be dropped automatically when the user closes the
session or terminates the connection manually.
o A temporary table can be created by the user with the same name as a normal table in
a database. For example, if the user creates a temporary table with the name student,
then the existing student table cannot be accessible. So, the user performs any query
against the student table, is now going to refer to the temporary student table. When
the user removes a temporary table, the permanent student table becomes accessible
again.
If the user wants to create a temporary table whose structure is the same as an
existing table in the database, then the above statement cannot be used. Instead, we
use the syntax as given below:
1. Mysql> CREATE TEMPORARY TABLE temporary_table_name SELECT * FROM
original_table_name LIMIT 0;
MySQL Temporary Table Example
Let us understand how we can create a temporary table in MySQL. Execute the
following statement that creates a temporary table in the selected database:
After executing the above statement, it will give the below output:
After the successful execution of the above statement, we will get the output as
below:
It is to be noted that when we run a SHOW TABLES command, then our temporary
table will not be shown on the list. Also, if we close the current session and then will
execute the SELECT statement, we will get a message saying that no data available in
the database, and even the temporary table will not exist.
Here, the structure of a temporary table is created by using the SELECT statement
and merge two tables using the INNER JOIN clause and sorts them based on the price.
Write the following statement in the MySQL prompt:
When we execute the above statement, we will get the following message:
Now, run the below command to see the temporary table:
We can also perform queries from the above temporary table "temp_customers"
similar to the querying data from a permanent table. The following query explains it
more clearly:
After executing the above statement, it will give the output as below:
NOTE: It is noted that we can use IF NOT EXISTS keyword to avoid the "table already exists"
error.
How to Drop Temporary Table in MySQL
MySQL allows us to remove the temporary table using the DROP TABLE statement.
But, it"s a good practice to use the TEMPORARY keyword with the DROP TABLE
statement. This keyword helps us to avoid the mistake of deleting a permanent table
when the temporary table and permanent table have the same name in the current
session. So, it is recommended to use the following query for removing the temporary
table:
This query will not remove a permanent table of the database that means it only
deletes a temporary table. If we try to delete a permanent table with this statement, it
will throw an error message saying that you are deleting a table is unknown. For
example, if we want to remove the above temporary table "temp_customers", we
need to use the following statement:
From the above, first, it creates a new table that indicates in the CREATE TABLE
statement. Second, the result set of a SELECT statement defines the structure of a
new table. Finally, MySQL fills data getting from the SELECT statement to the newly
created table.
If there is a need to copy only partial data from an existing table to a new table,
use WHERE clause with the SELECT statement as shown below:
We have to ensure that the table we are going to create should not already exist in
our database. The IF NOT EXISTS clause in MySQL allows us to check whether a
table exists in the database or not before creating a new table. So, the below
statement explains it more clearly:
It is to be noted that this statement only copies the table and its data. It doesn't copy
all dependent objects of the table, such as indexes, triggers, primary key constraints,
foreign key constraints, etc. So the command of copying data along with its
dependent objects from an existing to the new table can be written as the following
statements:
In the above, we can see that we need to execute two statements for copying data
along with structure and constraints. The first command creates a new
table new_table_name that duplicates the existing_table_name, and the second
command adds data from the existing table to the new_table_name.
Next, it is required to add values to this table. Execute the below statement:
After the successful execution, we can verify the table data using the SELECT
statement. See the below output:
Sometimes there is a need to copy only partial data from an existing table to a new
table. In that case, we can use the WHERE clause with the SELECT statement as
follows:
This statement creates a duplicate table that contains data for the year 2016 only.
We can verify the table using a SELECT statement, as shown below:
Suppose there a need to copy an existing table along with all dependent objects
associated with the table, execute the two statements that are given below:
In the above, the first command creates a new table in the selected(destination)
database by cloning the existing table from the source database. The second
command copies data from the existing table to the new table in the selected
database.
Now, we are going to copy this table into another database named mystudentdb using
the following statement:
After successful execution, we can verify the table in mystudentdb database using the
below command:
In the below output, we can see that the table is successfully copied into one
database to another database.
MySQL REPAIR TABLE
How to Fix a Corrupted Table in MySQL?
MySQL Repair Table allows us to repair or fix the corrupted table. The repair table in
MySQL provides support only for selected storage engines, not for all. It is to ensure that we
have a few privileges like SELECT and INSERT to use this statement. Normally, we
should never use the repair table until disastrous things happen with the table. This
statement rarely gets all data from the MyISAM table. Therefore, we need to find why
our table is corrupted to eliminate the use of this statement.
When we execute the REPAIR TABLE statement, it first checks the table that we are
going to repair is required an upgradation or not. If required, it will perform
upgradation with the same rules as CHECK TABLE ... FOR UPGRADE statement works.
It is always good to keep our table's backup before performing the "table repair"
option because it might cause a loss of our data.
Syntax
The following is the syntax to repair a corrupted table in MySQL:
QUICK: The quick option allows the REPAIR TABLE statement for repairing only the
index file. It does not allow to repair of the data file. This type of repair gives the same
result as the myisamchk --recover -quick command works.
EXTENDED: Instead of creating the index row by row, this option allows MySQL to
create one index at a time with sorting. This type of repair gives the same result as
the myisamchk --safe-recover command works.
USE_FRM: This option is used when the .MYI index file is not found or if its header is
corrupted. The USE-FRM option informs MySQL to do not trust the information present
in this file header and re-create it by using the information provided from the data
dictionary. This type of repair cannot work with the myisamchk command.
We can also use the repair table statement for partitioned tables. But, here, we
cannot use the USE_FRM option with this statement. If we want to repair multiple
partitions, we can use the ALTER TABLE ... REPAIR PARTITION statement.
MySQL REPAIR TABLE Example
Let us understand the working of the repair table statement in MySQL through
example. First, we need to create a new table named vehicle in the selected database
as follows:
Next, we will insert some data into this table with the below statement:
Next, we will execute the below statement to check the storage engine of the vehicle
table:
To remove this error, we first need to alter the table storage engine to MyISAM with
the following query and then used the repair table statement.
In this output, we can see that the REPAIR TABLE statement contains the following columns in the
result set:
2. Op This column always contains repair word whether the storage engine su
3. Msg_type This column can be either status, error, info, note, or warning.
Let us see another example to use a repair table statement with any QUICK,
EXTENDED or USE_FRM options. Thus, we will first create another table
named memberships and stored this table in the "MyISAM" storage engine instead of
the default one InnoDB.
We will insert some data into this table with the below statement:
Next, execute the SELECT statement to verify the data. We will get the below result:
Since we have created the MyISAM storage engine table, the repair table statement
does not issue any error. See the below statement:
In this article, we have learned how to repair the corrupted table in MySQL using the
Repair Table statement. This statement works only for certain storage engines. Thus,
before using this query, we first check the table storage engine supports it or not. If it
is not supported, we need to change it into MyISAM, ARCHIVE, or CSV. It is always
good to keep our table's backup before performing the "table repair" query because it
might cause a loss of our data.
MySQL Add/Delete Column
A column is a series of cells in a table that may contain text, numbers, and images.
Every column stores one value for each row in a table. In this section, we are going to
discuss how to add or delete columns in an existing table.
In the above,
Sometimes it is required to add multiple columns into the existing table. Then, we
can use the syntax as follows:
After creating a table, we want to add a new column named City to the Test table.
Since we have not specified the new column position explicitly after the column name,
MySQL will add it as the last column.
Next, we want to add a new column named Phone_number to the Test table. This
time, we will explicitly specify the new column position so that MySQL adds the
column to the specified place.
In the below output, we can see that the two columns are added successfully at the
specified position.
Let us add some data into the Test table using the INSERT statement as follows:
Suppose we want to add more than one column ,(Branch, Email) in the Test table. In
that case, execute the statement as follows:
It is to note that columns Branch and Email are assigned to default value NULL.
However, the Test table already has data so that MySQL will use null values for those
new columns.
If we accidentally add a new column with the existing column name, MySQL
will throw an error. For example, execute the below statement that issues an error:
In the above,
This example shows how we can change the column name in the MySQL table:
This statement will change the column name Phone_number with the new
name Mobile_number in the Test table. The below output explains it more clearly.
How can we drop a column from MySQL table?
Sometimes, we want to remove single or multiple columns from the table. MySQL
allows the ALTER TABLE DROP COLUMN statement to delete the column from the
table. The following are the syntax to do this:
In the above,
o First, we need to specify the table name from which we want to remove the column.
o Next, after the DROP COLUMN clause, we have to specify the column name that we
want to delete from the table. It is to note that the COLUMN keyword is optional in the
DROP COLUMN clause.
If we want to remove multiple columns from the table, execute the following
statements:
This example explains how we can delete a column from the MySQL table. Here, we
will take a table "Test" that we have created earlier and look like the below image:
Suppose we want to delete a column name "Branch" from the Test table. To do this,
execute the below statement:
After successful execution, we can verify the result below where a column Branch is
deleted from the table:
In some cases, it is required to remove multiple columns from the table. To do this, we
need to execute the below statement:
The command will delete both columns. We can verify it using the queries given in the
below image.
Remember the following key points before deleting a column from the table:
MySQL works with relational databases where the schema of one table can depend on
the columns of another table. So when we remove a column from one table, it will
effects all dependent tables also. Consider the below points while removing column:
o When we remove columns from a table, it will affect all associated objects such as
triggers, stored procedures, and views. Suppose we delete a column that is referencing
in the trigger. After removing the column, the trigger becomes invalid.
o The dropped column depends on other applications code, must also be changed, which
takes time and effort.
o When we remove a column from the large table, it will affect the database's
performance during removal time.
MySQL Show Columns
Columns in the table are a series of cells that can stores text, numbers, and images.
Every column stores one value for each row in a table. When we work with the MySQL
server, it is common to display the column information from a particular table. In this
section, we are going to discuss how to display or list columns in an existing table.
Syntax
The following is a syntax to display the column information in a specified table:
The FULL is also an optional keyword to display the column information, including
collation, comments, and the privileges we have for each column.
The table_name is the name of a table from which we are going to show column
information.
The db_name is the name of a database containing a table from which we will show
column information.
The LIKE or WHERE clause is used to display only the matched column information in
a given table.
If we want to filter the columns of a table, we need to use the LIKE or WHERE clause in
the statement. See the below query:
This query shows the column information that starts with the letter S only. See the
below output:
If we want to display hidden column information, we need to add the FULL keyword to
the SHOW COLUMNS statement as follows:
1. mysql> SHOW FULL COLUMNS FROM student_info;
It returns the below output that displays all columns information of the student_info
table in the sample database.
The SHOW COLUMNS statement provides the below information for each
column in a given table:
Null: It indicates the nullability of a column. If a column can store NULL values, it
returns YES. And if a column cannot store NULL value, it contains NO value.
Key: It indicates the indexing of the columns as PRI, UNI, and MUL. Let us understand
this field in detail.
o If we have not specified any key, it means the column is not indexed. Otherwise, index
as a secondary column in a multiple-column.
o If the column is specified as a PRI, it means the column is a PRIMARY KEY or one of the
fields in a multiple-column PRIMARY KEY.
o If the column is specified as a UNI, it means the column contains a UNIQUE index.
o If the column is specified as a MUL, it means the column is the first column of a non-
unique index where we can use a given value multiple times.
o If the column is specified by more than one key-value, this field displays the key which
has the highest priority (the key priority is in the order of PRI, UNI, and MUL).
Default: It indicates the default value to the column. If the column includes no
DEFAULT clause or has an explicit NULL default, it contains a NULL value.
Extra: It indicates the additional information related to a given column. This field is
non-empty in the following cases:
o If the column is specified with the AUTO_INCREMENT attribute, its value is filled with
auto_increment.
o If the column is specified with TIMESTAMP or DATETIME that have the ON UPDATE
CURRENT_TIMESTAMP attribute, its value is filled with on update CURRENT_TIMESTAMP.
o For the generated columns, its value filled with VIRTUAL GENERATED or VIRTUAL
STORED.
o If the column contains an expression default value, its value is filled with
DEFAULT_GENERATED.
Privileges: It indicates the privileges that we have for the column. We will see this
column only when we use the FULL keyword.
Comment: It indicates the comment that we have included in the column definition.
We will see this column only when we use the FULL keyword.
Syntax
The following is the syntax to display the column information in a given table:
In this syntax, the DESCRIBE and DESC clause return the same result.
Example
If we want to show column information of students_info table, we can execute the
below statement.
1. Go to the Navigation tab and click on the Schema menu where all the previously
created databases available. Select your desired database (for
example, mstudentdb). It will pop up the following options.
2. Click on the Tables that show all tables stored in the mysqltestdb database.
Select a table whose column information you want to display. Then, mouse hour on
that table, it will show three icons. See the below image:
3. Click the icon (i) shown in the red rectangular box. We should get the screen as
follows:
4. Finally, click on the "Columns" menu. We can see the column information as like
below output.
In this syntax, we can see that we may require re-specification of all the column
attributes. This syntax can also allow us to change the column's data types. But,
sometimes the CHANGE statement might have the following disadvantages:
o All information of column attributes might not be available to the application for
renaming.
o There is a risk of accidental data type change that might result in the application's data
loss.
Example
Let us understand how the CHANGE statement works in MySQL to rename a column
through the various examples. Suppose we have a table named balance that
contains the data as follows:
Due to some reason, we need to change the column name account_num along
with its data type. In that case, we first check the structure of the table using
the DESCRIBE statement as follows:
In this image, we can see that the data type of column name account_num is int.
And we want to change this column name as account_no and its data type as int to
varchar. Thus, we can execute the below statement to do this:
After executing the above command, we can verify it by using the DESCRIBE
statement again. In the below image, the column name account_num and its data
type have changed successfully.
OR
After executing the above command, we can verify it by using the SELECT statement
again. In the below image, the column name id and customer_name have changed
successfully:
Let us again change the currently modifying column name through the RENAME
COLUMN statement as follows:
After executing the above command, we can verify it by using the DESCRIBE
statement again. In the below image, the column name cust_id and
cust_name have changed successfully:
In this article, we have learned an introduction of the MySQL RENAME column and how
to change the column name in a specified table, along with a query example for
better understanding.
MySQL View
A view is a database object that has no values. Its contents are based on the base
table. It contains rows and columns similar to the real table. In MySQL, the View is
a virtual table created by a query by joining one or more tables. It is operated
similarly to the base table but does not contain any data of its own. The View and
table have one main difference that the views are definitions built on top of other
tables (or views). If any changes occur in the underlying table, the same changes
reflected in the View also.
Syntax
Following is the syntax to create a view in MySQL:
view_name: It specifies the name of the VIEW that you want to create in MySQL.
WHERE conditions: It is also optional. It specifies the conditions that must be met
for the records to be included in the VIEW.
Example
Let us understand it with the help of an example. Suppose our database has a
table course, and we are going to create a view based on this table. Thus, the below
example will create a VIEW name "trainer" that creates a virtual table made by
taking data from the table courses.
Once the execution of the CREATE VIEW statement becomes successful, MySQL will
create a view and stores it in the database.
Syntax:
Example:
The following example will alter the already created VIEW name "trainer" by adding a
new column.
Once the execution of the ALTER VIEW statement becomes successful, MySQL will
update a view and stores it in the database. We can see the altered view using the
SELECT statement, as shown in the output:
Syntax:
The following is the syntax used to delete the view:
Parameters:
IF EXISTS: It is optional. If we do not specify this clause and the VIEW doesn't exist,
the DROP VIEW statement will return an error.
Example:
Suppose we want to delete the view "trainer" that we have created above. Execute
the below statement:
After successful execution, it is required to verify the view is available or not as below:
Now execute the below statement that will create a view Trainer along with the join
statement:
We can verify the view using the SELECT statement shown in the below image:
Create View using MySQL Workbench
To create a view in the database using this tool, we first need to launch the MySQL
Workbench and log in with the username and password to the MySQL server. It will
show the following screen:
1. Go to the Navigation tab and click on the Schema menu. Here, we can see all the
previously created databases. Select any database under the Schema menu, for
example, testdb. It will pop up the option that can be shown in the following screen.
2. Next, we need to right-click on the view option, and a new pop up screen will come:
3. As soon as we select the "Create View" option, it will give the below screen where
we can write our own view.
4. After completing the script's writing, click on the Apply button, we will see the
following screen:
5. In this screen, we will review the script and click the Apply button on the database
6. Finally, click on the Finish button to complete the view creation. Now, we can
verify the view as below:
Why we use View?
MySQL view provides the following advantages to the user:
It allows the user to simplify complex queries. If we are using the complex query, we
can create a view based on it to use a simple SELECT statement instead of typing the
complex query again.
We know that View simplifies the complex queries and converts them into a single line
of code to use VIEWS. Such type of code makes it easier to integrate with our
application. This will eliminate the chances of repeatedly writing the same formula in
every query, making the code reusable and more readable.
It also allows us to show only authorized information to the users and hide essential
data like personal and banking information. We can limit which information users can
access by authoring only the necessary data to them.
A view can also enable the backward compatibility in legacy systems. Suppose we
want to split a large table into many smaller ones without affecting the current
applications that reference the table. In this case, we will create a view with the same
name as the real table so that the current applications can reference the view as if it
were a table.
MySQL Table Locking
A lock is a mechanism associated with a table used to restrict the unauthorized access
of the data in a table. MySQL allows a client session to acquire a table lock
explicitly to cooperate with other sessions to access the table's data. MySQL
also allows table locking to prevent it from unauthorized modification into the same
table during a specific period.
A session in MySQL can acquire or release locks on the table only for itself. Therefore,
one session cannot acquire or release table locks for other sessions. It is to note that
we must have a TABLE LOCK and SELECT privileges for table locking.
MySQL provides two types of locks onto the table, which are:
READ LOCK: This lock allows a user to only read the data from a table.
WRITE LOCK: This lock allows a user to do both reading and writing into a table.
It is to note that the default storage engine used in MySQL is InnoDB. The InnoDB
storage engine does not require table locking manually because MySQL automatically
uses row-level locking for InnoDB tables. Therefore, we can do multiple transactions
on the same table simultaneously to read and write operations without making each
other wait. All other storage engines use table locking in MySQL.
Before understanding the table locking concept, first, we will create a new table
named "info_table" using the statement as follows:
In the above syntax, we have specified the table name on which we want to acquire
a lock after the LOCK TABLES keywords. We can specify the lock type, either READ
or WRITE.
We can also lock more than one table in MySQL by using a list of comma-separated
table's names with lock types. See the below syntax:
LOCK TYPES
Let us understand the lock types in detail.
READ Locks
The following are the features of the READ lock:
o At the same time, MySQL allows multiple sessions to acquire a READ lock for a table.
And all other sessions can read the table without acquiring the lock.
o If the session holds the READ lock on a table, they cannot perform a write operation on
it. It is because the READ lock can only read data from the table. All other sessions that
do not acquire a READ lock are not able to write data into the table without releasing
the READ lock. The write operations go into the waiting states until we have not
released the READ lock.
o When the session is terminated normally or abnormally, MySQL implicitly releases all
types of locks on to the table. This feature is also relevant for the WRITE lock.
Let us take an example to see how READ locks work in MySQL with the given scenario.
We will first connect to the database and use the CONNECTION_ID() function that
gives the current connection id in the first session as follows:
1. mysql> SELECT CONNECTION_ID();
Next, we will insert few rows into the info_table using the below statement:
Now, verify the data into the table using the below statement:
Now, we will execute the LOCK TABLE statement to acquire a lock onto the table:
After that, we will try to insert a new record into the info_table as follows:
We will get the below output where MySQL issues the following message "Table
'info_table' was locked with a READ lock and can't be updated".
Thus, we can see that once the READ lock is acquired on to the table, we cannot write
data to the table in the same session.
Now, we will check how the READ lock work from a different session. First, we will
connect to the database and see the connection id:
Next, we will query data from the info_table that returns the output as follows:
We can see the detailed information about them using the SHOW
PROCESSLIST statement in the first session. See the below output:
Finally, we need to release the lock by using the UNLOCK TABLES statement in the
first session. Now, we are able to execute the INSERT operation in the second session.
Write Locks
The following are the features of a WRITE lock:
o It is the session that holds the lock of a table and can read and write data both from the
table.
o It is the only session that accesses the table by holding a lock. And all other sessions
cannot access the data of the table until the WRITE lock is released.
Let us take an example to see how WRITE locks works in MySQL with the given
scenario. In the first session, we will acquire a WRITE lock using the below statement:
The above statement worked. Now, we can verify the output using the SELECT
statement:
Again, we will attempt to access (read/write) the table from the second session:
We can see that these operations are put into a waiting state. See the detailed
information about them using the SHOW PROCESSLIST statement:
Finally, we will release the lock from the first session. Now, we can execute the
pending operations.
We can lock the user accounts by using the CREATE USER... ACCOUNT LOCK statement
as follows:
The ACCOUNT LOCK clause specifies the initial locking state for a new user account.
If we do not specify this clause with the statement, then a newly created user is
stored in an unlocked state by default. If we have enabled
the validate_password plugin during user creation, we cannot create an account
without a password, even if it is locked.
MySQL also allows us to provide the lock on an existing user account by using the
ALTER USER… ACCOUNT LOCK statement as follows:
1. ALTER USER account_name IDENTIFIED BY 'password' ACCOUNT LOCK;
The account locking state remains unchanged if we do not specify the ACCOUNT LOCK
clause with the statement.
MySQL uses the account_locked column of the mysql.user system table to store
the account locking state. We can use the SHOW CREATE USER statement to
validate whether the account is unlocked or locked. If this column value is Y, it means
the account is locked. If it contains N, it means the account is unlocked.
If we will try to access the locked account, the attempt fails, and MySQL issues an
error that writes the below message to the error log:
Next, we will execute the below statement to show the user account and its status:
If we try to access the user account javatpoint to connect to the MySQL Server, the
attempt fails, and we will receive an error:
1. mysql -u javatpoint -p
2. Enter password: *********
Next, we will log in to the MySQL server with a newly created user account
markus@localhost as follows:
1. mysql -u markus -p
2. Enter password: *********
We will get the below output that means the user account markus@localhost is login
successfully.
Now, we will use the ALTER TABLE LOCK ACCOUNT statement to lock this user
account as follows:
Again, we will execute the below statement to show the user status:
We can see the below output that indicates user account markus was locked
successfully:
If we want to show the number of attempts to connect to the MySQL Server of locked
accounts, we need the locked_connects variables. Each time we try to connect the
locked user account, MySQL increases this variable's status by 1. See the below
command:
After execution, we will get this output that shows we have tried three times to
connect the locked user account:
MySQL Unlock Account
Unlock is a mechanism that allows the user to release all locks or any specific lock
associated with the account. In this article, we will learn how to unlock the user
accounts in the MySQL server.
When the CREATE USER… UNLOCK statement creates a new user account, the new
user stored as a locked state.
If we want to release a lock from the existing user account, we need to use the ALTER
USER… ACCOUNT UNLOCK statement as follows:
In this syntax, we have to first specify the user account name that we want to
release a lock after the ALTER USER keyword. Next, we need to provide
the ACCOUNT UNLOCK clause next to the user name. It is to note the IF
EXISTS option can also be used to unlock the account only if it has existed in the
server.
MySQL also allows us to unlock multiple user accounts at the same time by using
the below statement:
In this syntax, we need to provide a list of comma-separated user name for unlocking
multiple accounts within a single query. If we do not specify the ACCOUNT UNLOCK
clause with the statement, the account unlocking state remains unchanged.
MySQL uses the account_locked column of the mysql.user system table to store
the account locking state. We can use the SHOW CREATE USER statement to
validate whether the account is unlocked or locked. If this column value is Y, it means
the account is locked. If it contains N, it means the account is unlocked.
If we will try to connect to the account without unlocking, MySQL issues an error that
writes the below message to the error log:
Next, we will execute the below statement to show the user account and its status:
If we try to connect with this account without unlocking in the MySQL Server, it
returns the following error:
1. mysql -u javatpoint -p
2. Enter password: *********
Thus, we can use the ALTER USER statement to unlock the account before accessing
it as follows:
In the below output, we can see that the account_locked column status is N. It means
the user account javatpoint does not have any lock.
In this article, we have learned how we can use the ALTER TABLE ACCOUNT UNLOCK
statement to release a lock from an existing user account.
MySQL Queries
A list of commonly used MySQL queries to create database, use database, create
table, insert record, update record, delete record, select record, truncate table and
drop table are given below.
More Details...
1. use db1;
More Details...
More Details...
More Details...
More Details...
More Details...
More Details...
More Details...
More Details...
1. Column Level Constraints: These constraints are applied only to the single column that limits
the type of particular column data.
2. Table Level Constraints: These constraints are applied to the entire table that limits the type
of data for the whole table.
How to create constraints in MySQL
We can define the constraints during a table created by using the CREATE TABLE
statement. MySQL also uses the ALTER TABLE statement to specify the constraints in
the case of the existing table schema.
Syntax
o NOT NULL
o CHECK
o DEFAULT
o PRIMARY KEY
o AUTO_INCREMENT
o UNIQUE
o INDEX
o ENUM
o FOREIGN KEY
This constraint specifies that the column cannot have NULL or empty values. The
below statement creates a table with NOT NULL constraint.
1. mysql> CREATE TABLE Student(Id INTEGER, LastName TEXT NOT NULL, FirstN
ame TEXT NOT NULL, City VARCHAR(35));
In the above image, we can see that the first INSERT query executes correctly, but the
second statement fails and gives an error that says column LastName cannot be null.
UNIQUE Constraint
This constraint ensures that all values inserted into the column will be unique. It
means a column cannot stores duplicate values. MySQL allows us to use more than
one column with UNIQUE constraint in a table. The below statement creates a table
with a UNIQUE constraint:
Output
In the below output, we can see that the first INSERT query executes correctly, but the
second statement fails and gives an error that says: Duplicate entry 'Cantabil' for key
BrandName.
CHECK Constraint
It controls the value in a particular column. It ensures that the inserted value in a
column must be satisfied with the given condition. In other words, it determines
whether the value associated with the column is valid or not with the given condition.
Before the version 8.0.16, MySQL uses the limited version of this constraint syntax, as
given below:
1. CHECK (expr)
After the version 8.0.16, MySQL uses the CHECK constraints for all storage engines
i.e., table constraint and column constraint, as given below:
Let us understand how a CHECK constraint works in MySQL. For example, the
following statement creates a table "Persons" that contains CHECK constraint on the
"Age" column. The CHECK constraint ensures that the inserted value in a column must
be satisfied with the given condition means the Age of a person should be greater
than or equal to 18:
Execute the listed queries to insert the values into the table:
Output
In the below output, we can see that the first INSERT query executes successfully, but
the second statement fails and gives an error that says: CHECK constraint is violated
for key Age.
DEFAULT Constraint
This constraint is used to set the default value for the particular column where we
have not specified any value. It means the column must contain a value, including
NULL.
For example, the following statement creates a table "Persons" that contains DEFAULT
constraint on the "City" column. If we have not specified any value to the City column,
it inserts the default value:
Execute the listed queries to insert the values into the table:
Output
In the below output, we can see that the first insert query that contains all fields
executes successfully, while the second insert statement does not contain the "City"
column but also executed successfully. It is because it has a default value.
Now, executes the following statement to validate the default value for the 4th
column:
1. mysql> SELECT * FROM Persons;
We can see that it works perfectly. It means default value "New York" stored
automatically in the City column.
This constraint is used to identify each record in a table uniquely. If the column
contains primary key constraints, then it cannot be null or empty. A table may have
duplicate columns, but it can contain only one primary key. It always contains unique
value into a column.
The following statement creates a table "Person" and explains the use of this primary
key more clearly:
Output
In the below output, we can see that the first insert query executes successfully.
While the second insert statement fails and gives an error that says: Duplicate entry
for the primary key column.
AUTO_INCREMENT Constraint
We can understand it with the following example where the id column going to be
auto-incremented in the Animal table:
Output
In the output, we can see that I have not specified any value for the auto-increment
column, so MySQL automatically generates a unique number in the sequence order
for this field.
ENUM Constraint
The ENUM data type in MySQL is a string object. It allows us to limit the value chosen
from a list of permitted values in the column specification at the time of table
creation. It is short for enumeration, which means that each column may have one of
the specified possible values. It uses numeric indexes (1, 2, 3…) to represent string
values.
The following illustration creates a table named "shirts" that contains three columns:
id, name, and size. The column name "size" uses the ENUM data type that contains
small, medium, large, and x-large sizes.
Next, we need to insert the values into the "Shirts" table using the below statements:
Now, execute the SELECT statement to see the inserted values into the table:
INDEX Constraint
This constraint allows us to create and retrieve values from the table very quickly and
easily. An index can be created using one or more than one column. It assigns a
ROWID for each row in that way they were inserted into the table.
The following illustration creates a table named "shirts" that contains three columns:
id, name, and size.
Next, we need to insert the values into the "Shirts" table using the below statements:
Output
Table: Persons
Table: Orders
In the above table structures, we can see that the "Person_ID" field in the "Orders"
table points to the "Person_ID" field in the "Persons" table. The "Person_ID" is the
PRIMARY KEY in the "Persons" table, while the "Person_ID" column of the "Orders"
table is a FOREIGN KEY.
Output
Syntax:
The below is generic syntax of SQL INSERT INTO command to insert a single record
in MySQL table:
In the above syntax, we first have to specify the table name and list of comma-
separated columns. Second, we provide the list of values corresponding to columns
name after the VALUES clause.
NOTE: Field name is optional. If we want to specify partial values, the field name is mandatory.
It also ensures that the column name and values should be the same. Also, the position of
columns and corresponding values must be the same.
If we want to insert multiple records within a single command, use the following
statement:
In the above syntax, all rows should be separated by commas in the value fields.
1. If we want to store single records for all fields, use the syntax as follows:
2. If we want to store multiple records, use the following statements where we can
either specify all field names or don't specify any field.
3. If we want to store records without giving all fields, we use the following partial
field statements. In such case, it is mandatory to specify field names.
We can use the below syntax to show the records of the People table:
If we want to insert a date in the mm/dd/yyyy format, it is required to use the below
statement:
The UPDATE statement is used with the SET and WHERE clauses. The SET clause is
used to change the values of the specified column. We can update single or multiple
columns at a time.
Syntax
Following is a generic syntax of UPDATE command to modify data into
the MySQL table:
1. UPDATE table_name
2. SET column_name1 = new-value1,
3. column_name2=new-value2, ...
4. [WHERE Clause]
Parameter Explanation
The description of parameters used in the syntax of the UPDATE statement is given
below:
Parameter Descriptions
column_na It is the name of a column in which we want to perform updation with the new value u
me update multiple columns, separate the columns with a comma operator by specifying
WHERE It is optional. It is used to specify the row name in which we are going to perform
Clause updates all rows.
Note:
IGNORE: This modifier allows the statement to do not abort the execution even if
errors occurred. If it finds duplicate-key conflicts, the rows are not updated.
This query will update the email id of Java course with the new id as follows:
1. UPDATE trainer
2. SET email = 'mike@tutorialandexamples.com'
3. WHERE course_name = 'Java';
After successful execution, we will verify the table using the below statement:
In the output, we can see that our table is updated as per our conditions.
This statement explains will update the name and occupation whose id = 105 in
the People table as follows:
1. UPDATE People
2. SET name = 'Mary', occupation = 'Content Writer'
3. WHERE id = 105;
We can also use the UPDATE statement in MySQL to change the string name in the
particular column. The following example updates the domain parts of emails
of Android course:
1. UPDATE Trainer_table
2. SET email = REPLACE(email,'@javatpoint.com','@tutorialandexample.com')
3. WHERE course_name = 'Testing';
Once we delete the records using this query, we cannot recover it. Therefore
before deleting any records from the table, it is recommended to create a backup of
your database. The database backups allow us to restore the data whenever we
need it in the future.
Syntax:
The following are the syntax that illustrates how to use the DELETE statement:
In the above statement, we have to first specify the table name from which we want
to delete data. Second, we have to specify the condition to delete records in
the WHERE clause, which is optional. If we omit the WHERE clause into the statement,
this query will remove whole records from the database table.
If we want to delete records from multiple tables using a single DELETE query, we
must add the JOIN clause with the DELETE statement.
If we want to delete all records from a table without knowing the count of deleted
rows, we must use the TRUNCATE TABLE statement that gives better performance.
Let us understand how the DELETE statement works in MySQL through various
examples.
MySQL DELETE Statement Examples
Here, we are going to use the "Employees" and "Payment" tables for the
demonstration of the DELETE statement. Suppose the Employees and Payment tables
contain the following data:
If we want to delete an employee whose emp_id is 107, we should use the DELETE
statement with the WHERE clause. See the below query:
After the execution of the query, it will return the output as below image. Once the
record is deleted, verify the table using the SELECT statement:
If we want to delete all records from the table, there is no need to use the WHERE
clause with the DELETE statement. See the below code and output:
In the above output, we can see that after removing all rows, the Employees table will
be empty. It means no records available in the selected table.
For example, the following query first sorts the employees according to their names
alphabetically and deletes the first three employees from the table:
Output:
To read more information about the DELETE statement with the JOIN clause, click here.
Parameter Explanation
The SELECT statement uses the following parameters:
field_name(s) or * It is used to specify one or more columns to returns in the result set. The ast
WHERE It is an optional clause. It specifies the condition that returned the matched r
GROUP BY It is optional. It collects data from multiple records and grouped them by one
HAVING It is optional. It works with the GROUP BY clause and returns only those rows
ORDER BY It is optional. It is used for sorting the records in the result set.
OFFSET It is optional. It specifies to which row returns first. By default, It starts with z
LIMIT It is optional. It is used to limit the number of returned records in the result s
NOTE: It is to note that MySQL always evaluates the FROM clause first, and then the SELECT
clause will be evaluated.
MySQL SELECT Statement Example:
Let us understand how SELECT command works in MySQL with the help of various
examples. Suppose we have a table named employee_detail that contains the
following data:
1. If we want to retrieve a single column from the table, we need to execute the
below query:
We will get the below output where we can see only one column records.
2. If we want to query multiple columns from the table, we need to execute the
below query:
We will get the below output where we can see the name, email, and city of
employees.
3. If we want to fetch data from all columns of the table, we need to use all
column's names with the select statement. Specifying all column names is not
convenient to the user, so MySQL uses an asterisk (*) to retrieve all column data as
follows:
4. Here, we use the SUM function with the HAVING clause in the SELECT command to
get the employee name, city, and total working hours. Also, it uses the GROUP
BY clause to group them by the Name column.
5. MySQL SELECT statement can also be used to retrieve records from multiple tables
by using a JOIN statement. Suppose we have a table
named "customer" and "orders" that contains the following data:
Table: customer
Table: orders
Execute the following SQL statement that returns the matching records from both
tables using the INNER JOIN query:
After successful execution of the query, we will get the output as follows:
MySQL REPLACE
The REPLACE statement in MySQL is an extension of the SQL Standard. This statement
works the same as the INSERT statement, except that if an old row matches the new
record in the table for a PRIMARY KEY or a UNIQUE index, this command deleted the
old row before the new row is added.
This statement is required when we want to update the existing records into the table
to keep them updated. If we use the standard insert query for this purpose, it will give
a Duplicate entry for PRIMARY KEY or a UNIQUE key error. In this case, we will use the
REPLACE statement to perform our task. The REPLACE command requires one of the
two possible actions take place:
o If no matching value is found with the existing data row, then a standard INSERT
statement is performed.
o
o If the duplicate record found, the replace command will delete the existing row and
then adds the new record in the table.
In the REPLACE statement, the updation performed in two steps. First, it will delete
the existing record, and then the newly updated record is added, similar to a standard
INSERT command. Thus, we can say that the REPLACE statement performs two
standard functions, DELETE and INSERT.
Syntax
Let us understand the working of the REPLACE statement in MySQL with the help of an
example. First, we are going to create a table named "Person" using the following
statement:
Next, we need to fill the record into the table using the INSERT statement as below:
Execute the SELECT statement to verify the records that can be shown in the below
output:
After verifying the data into a table, we can replace any old row with the new row
using the REPLACE statement. Execute the below statement that updates the city of
a person whose id is 4.
After the successful execution of the above statement, it is required to query the data
of the table Person again to verify the replacement.
The value in the name and email columns are NULL now. It is because the REPLACE
statement works as follows:
o This statement first tries to insert a new row into the Person table. But the insertion of a
new row is failed because the id = 4 already exists in the table.
o So this statement first delete the row whose id = 4 and then insert a new row with the
same id and city as Amsterdam. Since we have not specified the value for the name
and email column, it was set to NULL.
The above syntax is similar to the UPDATE statement except for the REPLACE keyword. It
is to note that we cannot use the WHERE clause with this statement.
Execute the below example that uses the REPLACE statement to update the city of the
person named Mike from California to Birmingham.
If we have not specified the column's value in the SET clause, this command works
like the UPDATE statement, which means the REPLACE statement will use the
default value of that column.
It is to note that the above REPLACE query is similar to the INSERT INTO
SELECT statement. Execute the below example that uses the REPLACE INTO
statement to copy a row within the same table.
After verification of the table, we will get the following output. In this output, we can
see that the copy of a row within the same table is successfully added.
MySQL INSERT ON DUPLICATE KEY UPDATE
The Insert on Duplicate Key Update statement is the extension of the INSERT
statement in MySQL. When we specify the ON DUPLICATE KEY UPDATE clause in a SQL
statement and a row would cause duplicate error value in a UNIQUE or PRIMARY
KEY index column, then updation of the existing row occurs.
In other words, when we insert new values into the table, and it causes duplicate row
in a UNIQUE OR PRIMARY KEY column, we will get an error message. However, if we
use ON DUPLICATE KEY UPDATE clause in a SQL statement, it will update the old row
with the new row values, whether it has a unique or primary key column.
For example, if column col1 is defined as UNIQUE and contains the value 10 into the
table tab1, we will get a similar effect after executing the below two statements:
1. mysql> INSERT INTO tab1 (col1, col2, col3) VALUES (10,20,30) ON DUPLICAT
E KEY UPDATE col3=col3+1;
2.
3. mysql> UPDATE tab1 SET col3=col3+1 WHERE col1=1;
It makes sure that if the inserted row matched with more than one unique index into
the table, then the ON DUPLICATE KEY statement only updates the first matched
unique index. Therefore, it is not recommended to use this statement on tables that
contain more than one unique index.
If the table contains AUTO_INCREMENT primary key column and the ON DUPLICATE
KEY statement tries to insert or update a row, the Last_Insert_ID() function returns its
AUTO_INCREMENT value.
The following are the syntax of Insert on Duplicate Key Update statement
in MySQL:
In this syntax, we can see that the INSERT statement only adds the ON DUPLICATE
KEY UPDATE clause with a column-value pair assignment whenever it finds
duplicate rows. The working of ON DUPLICATE KEY UPDATE clause first tries to insert
the new values into the row, and if an error occurs, it will update the existing row with
the new row values.
The VALUES() function only used in this clause, and it does not have any meaning in
any other context. It returns the column values from the INSERT portion and
particularly useful for multi-rows inserts.
Next, insert the data into the table. Execute the following statement:
We will get the output as below where we have three rows into the table:
Again, add one more row into the table using the below query:
The above statement will add row successfully because it does not have any duplicate
values.
Finally, we are going to add a row with a duplicate value in the Stud_ID column:
MySQL gives the following message after successful execution of the above query:
In the below out, we can see that the row id=4 already exists. So the query only
updates the City New York with California.
MySQL INSERT IGNORE
Insert Ignore statement in MySQL has a special feature that ignores the invalid
rows whenever we are inserting single or multiple rows into a table. We can
understand it with the following explanation, where a table contains a primary key
column.
The primary key column cannot stores duplicate values into a table. For example,
student_roll_number should always be unique for every student. Similarly,
the employee_id in the company should always be distinct into the employee table.
When we try to insert a duplicate record into a table with a primary key column, it
produces an error message. However, if we use the INSERT IGNORE statement to add
duplicate rows into a table with a primary key column, MySQL does not produce any
error. This statement is preferred when we are trying to insert records in bulk, and
resulting errors can interrupt the execution process. As a result, it does not store any
record into a table. In such a case, the INSERT IGNORE statement only generates the
warnings.
Below are the cases where an INSERT IGNORE statement avoids error:
o When we will try to insert a duplicate key where the column of a table has a PRIMARY or
UNIQUE KEY constraint.
o When we will try to add a NULL value where the column of a table has a NOT NULL
constraint.
o When we will try to insert a record to a partitioned table where the entered values do
not match the format of listed partitions.
Syntax
The following are a syntax to use the INSERT IGNORE statement in MySQL:
The UNIQUE constraint ensures that we cannot insert duplicate values into the email
column. Next, it is required to insert the records into the table. We can execute the
below statement to add data into a table:
We can see the below output where we have three rows into the table:
Let us execute the below statement that will try to add two records into the table:
Now, let us see what happened if we use the INSERT IGNORE statement into the
above query:
MySQL will produce a message: one row added, and the other row was ignored.
We can see the detailed warning using the SHOW WARNINGS command:
Thus, we can say that if we use the INSERT IGNORE statement, MySQL gives a
warning instead of issuing an error.
Let us understand it with the help of an example. First, we are going to create a table
named "Test" using the below statement:
In the above table, the name column only accepts the string whose length is less than
or equal to five characters. Now, execute the below statement to insert the records
into a table.
We can see that the specified name validates the name column constraint so it will be
added successfully. Execute the SELECT statement to verify the result. It will give the
output as below:
MySQL does not add values and gives an error message because the strict mode is
ON. However, if we use the INSERT IGNORE statement to insert the same string, it will
give the warning message instead of throwing an error.
Finally, we have executed the SHOW WARNINGS command to check the warning
message. The below output explains it more clearly that shows MySQL tries to
truncate data before inserting it into a table.
MySQL INSERT INTO SELECT
Sometimes we want to insert data of one table into the other table in the same or
different database. It is not very easy to enter these data using the INSERT query
manually. We can optimize this process with the use of MySQL INSERT INTO SELECT
query. It allows us to populate the MySQL tables quickly. This section will cover the
INSERT INTO SELECT command, syntax, and its use cases.
The INSERT INTO SELECT statement in MySQL allows us to insert values into a table
where data comes from a SELECT query. In other words, this query copies data
from one table and inserts them in the other table. We must consider the
following point before using this statement:
o The data types in source and target tables must be the same.
o The existing records in the target table should be unaffected.
The INSERT INTO SELECT command is advantageous when we need to copy data from
one table to another table or to summarize data from more than one table into a
single table.
Syntax
Earlier, we have used the INSERT command for adding single or multiple records
into a table along with listing column values in the VALUES clause as follows:
The following is the basic syntax that illustrates the use of the INSERT INTO SELECT
command in MySQL. If we want to copy all data from one table into another table, we
can use the below statement:
From the MySQL version 8.0.19, we can use a TABLE statement in place of
SELECT query to get the same output, as shown below:
Here, TABLE table1 is equivalent to SELECT * FROM table1. When we want to add all
records from the source table into the target table without filtering the values, it is
used.
If we want to copy only some columns from one table to another table, we can use the
below statement:
In this syntax, we have used a SELECT statement instead of using the VALUES clause.
Here SELECT command retrieves values from one or more tables.
Parameter Explanation
The INSERT INTO SELECT statement uses the following parameters:
table_name2: It is the name of a target table where we will copy source table data.
Next, we will insert values into the table. We can execute the below statement to add
data into a table:
After executing the query, we can see the below output where we have five rows into
the table:
Suppose we want to insert a person's name who belongs to Texas City into
another table. The following query is used to search all person who locates in Texas:
Now, we will create another table named person_info that have a same number of
column, and data types in the same order as of the above table:
Second, we will use the INSERT INTO SELECT statement to insert persons located in
Texas from the person table into the person_info table:
After executing this statement, we can verify the insert operation using the SELECT
query. We will get the below output where all persons located in the Texas City
inserted successfully.
Suppose we want to insert all person's table data into the person_info
table without filtering any values; we can do this using the below statement:
Execute the SELECT statement to verify the data. Here is the output:
When a table is created with a primary key or unique key, it automatically creates a
special index named PRIMARY. We called this index as a clustered index. All indexes
other than PRIMARY indexes are known as a non-clustered index or secondary index.
To find the name and contact of the user from table contactbooks, generally, we
used to execute the following query:
This query is very simple and easy. Although it finds the phone number and name of
the user fast, the database searches entire rows of the table until it will not find the
rows that you want. Assume, the contactbooks table contains millions of rows, then,
without an index, the data retrieval takes a lot of time to find the result. In that case,
the database indexing plays an important role in returning the desired result and
improves the overall performance of the query.
If we want to add index in table, we will use the CREATE INDEX statement as follows:
In this statement, index_name is the name of the index, table_name is the name of
the table to which the index belongs, and the column_names is the list of columns.
Let us add the new index for the column col4, we use the following statement:
By default, MySQL allowed index type BTREE if we have not specified the type of
index. The following table shows the different types of an index based on the storage
engine of the table.
1. InnoDB BTREE
2. Memory/Heap HASH, BT
3. MYISAM BTREE
Example
In this example, we are going to create a table student and perform the CREATE
INDEX statement on that table.
Now, execute the following statement to return the result of the student
whose class is CS branch:
In the above table, we can see the four rows that are indicating the students whose
class is the CS branch.
If you want to see how MySQL performs this query internally, execute the following
statement:
You will get the output below. Here, MySQL scans the whole table that contains seven
rows to find the student whose class is the CS branch.
Now, let us create an index for a class column using the following statement.
In this output, MySQL finds four rows from the class index without scanning the whole
table. Hence, it increases the speed of retrieval of records on a database table.
If you want to show the indexes of a table, execute the following statement:
o First, we have to specify the name of the index that we want to remove.
o Second, name of the table from which your index belongs.
The Drop Index syntax contains two optional options, which are Algorithm and Lock
for reading and writing the tables during the index modifications. Let us explain both
in detail:
Algorithm Option
The algorithm_option enables us to specify the specific algorithm for removing the
index in a table. The syntax of algorithm_option are as follows:
The Drop Index syntax supports mainly two algorithms which are INPLACE and COPY.
COPY: This algorithm allows us to copy one table into another new table row by row
and then DROP Index statement performed on this new table. On this table, we cannot
perform an INSERT and UPDATE statement for data manipulation.
INPLACE: This algorithm allows us to rebuild a table instead of copy the original
table. We can perform all data manipulation operations on this table. On this
table, MySQL issues an exclusive metadata lock during the index removal.
Note: If you not defined the algorithm clause, MySQL uses the INPLACE algorithm. If INPLACE
is not supported, it uses the COPY algorithm. The DEFAULT algorithm works the same as
without using any algorithm clause with the Drop index statement.
Lock Option
This clause enables us to control the level of concurrent reads and writes during the
index removal. The syntax of lock_option are as follows:
In the syntax, we can see that the lock_option contains four modes that are
DEFAULT, NONE, SHARED, and EXCLUSIVE. Now, we are going to discuss all the
modes in detail:
SHARED: This mode supports only concurrent reads, not concurrent writes. When the
concurrent reads are not supported, it gives an error.
DEFAULT: This mode can have the maximum level of concurrency for a specified
algorithm. It will enable concurrent reads and writes if supported otherwise enforces
exclusive mode.
NONE: You have concurrent read and write if this mode is supported. Otherwise, it
gives an error.
Example
First, execute the following command to show the indexes available in the table.
In the output, we can see that there are three indexes available. Now, execute the
following statement to removes the class index from table student.
Again, execute the SHOW INDEXES statement to verify the index is removed or not.
After performing this statement, we will get the following output, where only two
indexes are available.
The following statement drops the age index form the student table using an
algorithm and a lock option.
To remove the primary key index from the student table, execute the following
statement:
In the above syntax, we can see that if we want to get the index of a table, it requires
to specify the table_name after the FROM keyword. After the successful execution of
the statement, it will return the index information of a table in the current database.
OR,
1. mysql> SHOW KEYS FROM table_name IN database_name;
Key_name: It is the name of an index. If the table contains a primary key, the index
name is always PRIMARY.
Seq_in_index: It is the sequence number of the column in the index that starts from
1.
Collation: It gives information about how the column is sorted in the index. It
contains values where A represents ascending, D represents descending,
and Null represents not sorted.
Cardinality: It gives an estimated number of unique values in the index table where
the higher cardinality represents a greater chance of using indexes by MySQL.
Sub_part: It is a prefix of the index. It has a NULL value if all the column of the table
is indexed. When the column is partially indexed, it will return the number of indexed
characters.
NULL: It contains blank if the column does not have NULL value; otherwise, it returns
YES.
Index_type: It contains the name of the index method like BTREE, HASH, RTREE,
FULLTEXT, etc.
Comment: It contains the index information when they are not described in its
column. For example, when the index is disabled, it returns disabled.
Index_column: When you create an index with comment attributes, it contains the
comment for the specified index.
Visible: It contains YES if the index is visible to the query optimizer, and if not, it
contains NO.
o For functional parts, the expression column represents expression for the key part, and
column_name represents NULL.
o For the non-functional part, the expression represents NULL, and column_name
represents the column indexed by the key part.
MySQL SHOW INDEX Example
Here, we are going to create a table student_info that contains the student id, name,
age, mobile number, and email details. Execute the following command to create a
table:
Now, execute the following command that returns the all index information from the
student_info table:
If you want to get only invisible indexes of the student_info table, execute the
following command:
MySQL allows another constraint called the UNIQUE INDEX to enforce the
uniqueness of values in one or more columns. We can create more than one UNIQUE
index in a single table, which is not possible with the primary key constraint.
Syntax
The following is a generic syntax used to create a unique index in MySQL table:
MySQL allows another approach to enforcing the uniqueness value in one or more
columns using the UNIQUE Key statement. We can read more information about
the UNIQUE KEY here.
NULL values in MySQL considers distinct values similar to other databases. Hence, we
can store multiple NULL values in the UNIQUE index column. This feature of MySQL
sometimes reported as a bug, but it is not a bug.
If we execute the below statement, we can see that MySQL created a UNIQUE index
for Email column of Employee_Detail table:
In the below screen, we can see that the Email column is created as a unique index.
Next, we are going to insert records to the table using the following statements:
The above statement executed successfully because all columns are unique. If we
insert a record whose email is suzi@javatpoint.com, we will get the duplicate error
message.
The following output explains all of the above steps more clearly:
Suppose we want the Name and Phone of the Employee_Detail table is also unique.
In this case, we will use the below statement to create a UNIQUE index for those
columns:
If we execute the SHOW INDEX statement again, we can see that MySQL created a
UNIQUE index index_name_phone for name and phone columns also.
Adding this record into the table produces an error. It is because of the combination of
a name and phone already exists.
A clustered index is actually a table where the data for the rows are stored. It defines
the order of the table data based on the key values that can be sorted in only one
way. In the database, each table can have only one clustered index. In a relational
database, if the table column contains a primary key or unique key, MySQL allows you
to create a clustered index named PRIMARY based on that specific column.
Characteristics
The essential characteristics of a clustered index are as follows:
Advantages
The main advantages of the clustered index are as follows:
o It helps us to maximize the cache hits and minimizes the page transfer.
o It is an ideal option for range or group with max, min, and count queries.
o At the start of the range, it uses a location mechanism for finding an index entry.
Disadvantages
The main disadvantages of the clustered index are as follows:
When the primary key is defined in an InnoDB table, MySQL always uses it as a
clustered index named PRIMARY. If the table does not contain a primary key column,
MySQL searches for the unique key. In the unique key, all columns are NOT
NULL and use it as a clustered index. Sometimes, the table does not have a primary
key nor unique key, then MySQL internally creates hidden clustered
index GEN_CLUST_INDEX that contains the values of row id. Thus, there is only one
clustered index in the InnoDB table.
The indexes other than the PRIMARY Indexes (clustered indexes) are known as a
secondary index or non-clustered indexes. In the MySQL InnoDB tables, every record
of the non-clustered index has primary key columns for both row and columns. MySQL
uses this primary key value for searching a row in the clustered index or secondary
index.
Example
In the below statement, the PRIMARY KEY is a clustered index.
Indexing in MySQL is a process that helps us to return the requested data from the
table very fast. If the table does not have an index, it scans the whole table for the
requested data. MySQL allows two different types of Indexing:
1. Clustered Index
2. Non-Clustered Index
Example
The following example explains how the clustered index created in MySQL:
Example
1. //It will create non-clustered index
2. CREATE NonClustered INDEX index_name ON table_name (column_name ASC);
Characteristics
Following are the essential characteristics of a non-clustered index:
Definition A clustered index is a table where the data for the rows are stored. In The indexes
a relational database, if the table column contains a primary key, indexes) ca
MySQL automatically creates a clustered index named PRIMARY. clustered i
indexes.
Use for It can be used to sort the record and store the index in physical It creates a
memory. pointers for
Type of Key It uses the primary key as a clustered index. It can work
composite k
This SQL statement reads the data from the SQL database and shows it as the output
to the database user.
the Emp_ID, First_Name, Last_Name, Salary, and City of those employees from
the Employee_details table whose Salary is 100000.
The output shows all the specified details according to the ascending alphabetical
order of Last_Name.
2. UPDATE Statement
This SQL statement changes or modifies the stored data in the SQL database.
1. UPDATE table_name
2. SET column_name1 = new_value_1, column_name2 = new_value_2, ...., column_nameN =
new_value_N
3. [ WHERE CONDITION ];
1. UPDATE Employee_details
2. SET Salary = 100000
3. WHERE Emp_ID = 10;
3. DELETE Statement
This SQL statement deletes the stored data from the SQL database.
This SQL statement creates the new table in the SQL database.
This example creates the table Employee_details with five columns or fields in the
SQL database. The fields in the table are Emp_Id, First_Name, Last_Name,
Salary, and City. The Emp_Id column in the table acts as a primary key, which
means that the Emp_Id column cannot contain duplicate values and null values.
This SQL statement adds, deletes, and modifies the columns of the table in the SQL
database.
The above SQL alter statement adds the column with its datatype in the existing
database table.
The above 'SQL alter statement' renames the old column name to the new column
name of the existing database table.
The above SQL alter statement deletes the column of the existing database table.
Example of ALTER TABLE Statement:
This example adds the new field whose name is Designation with size 18 in
the Employee_details table of the SQL database.
The above syntax of the drop statement deletes specified tables completely if they
exist in the database.
This example drops the Employee_details table if it exists in the SQL database. This
removes the complete information if available in the table.
The above example deletes the company database from the system.
This SQL statement inserts the data or records in the existing table of the SQL
database. This statement can easily insert single and multiple records in a single
query statement.
This example inserts 101 in the first column, Akhil in the second column, Sharma in
the third column, 40000 in the fourth column, and Bangalore in the last column of
the table Employee_details.
This example inserts the records of three employees in the Employee_details table
in the single query statement.
This example deletes the record of all employees from the Employee_details table of
the database.
11. DESCRIBE Statement
This SQL statement tells something about the specified table or view in the query.
1. DESCRIBE Employee_details;
This example shows the distinct values of the City and Salary column from
the Employee_details table.
This SQL statement saves the changes permanently, which are done in the
transaction of the SQL database.
1. COMMIT
This SQL statement undo the transactions and operations which are not yet
saved to the SQL database.
1. ROLLBACK
This example deletes the records of those employees whose City is Mumbai and then
undo the changes in the database.
This SQL statement creates the new index in the SQL database table.
This SQL statement deletes the existing index of the SQL database table.
This SQL statement selects the existing SQL database. Before performing the
operations on the database table, you have to select the database from the multiple
existing databases.
1. USE database_name;
1. USE Company;
SQL
keywords are NOT case sensitive: select is the same as SELECT
SELECT - extracts data from a database
UPDATE - updates data in a database
DELETE - deletes data from a database
INSERT INTO - inserts new data into a database
CREATE DATABASE - creates a new database
ALTER DATABASE - modifies a database
CREATE TABLE - creates a new table
ALTER TABLE - modifies a table
DROP TABLE - deletes a table
CREATE INDEX - creates an index (search key)
DROP INDEX - deletes an index
Select Syntax
MySQL WHERE Clause is used with SELECT, INSERT, UPDATE and DELETE clause
to filter the results. It specifies a specific position where you have to do the
operation.
Syntax:
1. WHERE conditions;
MySQL WHERE Clause with single condition
Table structure:
Output:
1. SELECT *
2. FROM officers
3. WHERE address = 'Lucknow'
4. AND officer_id < 5;
Output:
1. SELECT *
2. FROM officers
3. WHERE address = 'Lucknow'
4. OR address = 'Mau';
Output:
MySQL WHERE Clause with combination of AND & OR conditions
1. SELECT *
2. FROM officers
3. WHERE (address = 'Mau' AND officer_name = 'Ajeet')
4. OR (officer_id < 5);
Output:
MySQL Distinct Clause
MySQL DISTINCT clause is used to remove duplicate records from the table and
fetch only the unique records.
Syntax:
Parameters
expressions: specify the columns or calculations that you want to retrieve.
tables: specify the name of the tables from where you retrieve records. There must
be at least one table listed in the FROM clause.
WHERE conditions: It is optional. It specifies the conditions that must be met for the
records to be selected.
Note:
o If you put only one expression in the DISTINCT clause, the query will return the unique
values for that expression.
o If you put more than one expression in the DISTINCT clause, the query will retrieve
unique combinations for the expressions listed.
o In MySQL, the DISTINCT clause doesn't ignore NULL values. So if you are using the
DISTINCT clause in your SQL statement, your result set will include NULL as a distinct
value.
If you use a single expression then the MySQL DISTINCT clause will return a single
field with unique records (no duplicate record).
If you use multiple expressions with DISTINCT Clause then MySQL DISTINCT clause will
remove duplicates from more than one field in your SELECT statement.
The MySQL FROM Clause is used to select some records from a table.
It can also be used to retrieve records from multiple tables using JOIN condition.
Syntax:
1. FROM table1
2. [ { INNER JOIN | LEFT [OUTER] JOIN| RIGHT [OUTER] JOIN } table2
3. ON table1.column1 = table2.column1 ]
Parameters
table1 and table2: specify tables used in the MySQL statement. The two tables are
joined based on table1.column1 = table2.column1.
Note:
o If you are using the FROM clause in a MySQL statement then at least one table must
have been selected.
o If you are using two or more tables in the MySQL FROM clause, these tables are
generally joined using INNER or OUTER joins.
MySQL FROM Clause: Retrieve data from one table
The following query specifies how to retrieve data from a single table.
1. SELECT *
2. FROM officers
3. WHERE officer_id <= 3;
MySQL FROM Clause: Retrieve data from two tables with inner
join
Let's take an example to retrieve data from two tables using INNER JOIN.
MySQL FROM Clause: Retrieve data from two tables using outer
join
Syntax:
1. SELECT expressions
2. FROM tables
3. [WHERE conditions]
4. ORDER BY expression [ ASC | DESC ];
Parameters
tables: It specifies the tables, from where you want to retrieve records. There must
be at least one table listed in the FROM clause.
WHERE conditions: It is optional. It specifies conditions that must be fulfilled for the
records to be selected.
ASC: It is optional. It sorts the result set in ascending order by expression (default, if
no modifier is provider).
DESC: It is also optional. It sorts the result set in descending order by expression.
Note: You can use MySQL ORDER BY clause in a SELECT statement, SELECT LIMIT
statement, and DELETE LIMIT statement.
If you use MySQL ORDER BY clause without specifying the ASC and DESC modifier
then by default you will get the result in ascending order.
1. SELECT *
2. FROM officers
3. WHERE address = 'Lucknow'
4. ORDER BY officer_name;
Output:
MySQL ORDER BY: with ASC attribute
1. SELECT *
2. FROM officers
3. WHERE address = 'Lucknow'
4. ORDER BY officer_name ASC;
Output:
MySQL ORDER BY: with DESC attribute
1. SELECT *
2. FROM officers
3. WHERE address = 'Lucknow'
4. ORDER BY officer_name DESC;
MySQL ORDER BY: using both ASC and DESC attributes
Output:
MySQL GROUP BY Clause
The MYSQL GROUP BY Clause is used to collect data from multiple records and group
the result by one or more column. It is generally used in a SELECT statement.
You can also use some aggregate functions like COUNT, SUM, MIN, MAX, AVG etc.
on the grouped column.
Syntax:
Parameters
expression1, expression2, ... expression_n: It specifies the expressions that are
not encapsulated within an aggregate function and must be included in the GROUP BY
clause.
WHERE conditions: It is optional. It specifies the conditions that must be fulfilled for
the records to be selected.
Output:
MySQL GROUP BY Clause with SUM function
Now, the following query will GROUP BY the example using the SUM function and
return the emp_name and total working hours of each employee.
Output:
MySQL GROUP BY Clause with MIN function
Output:
MySQL GROUP BY Clause with MAX function
Output:
Output:
Syntax:
HAVING condition: It is used to restrict the groups of returned rows. It shows only
those groups in result set whose conditions are TRUE.
Conditions
MySQL AND Condition
The MySQL AND condition is used with SELECT, INSERT, UPDATE or DELETE
Syntax:
1. WHERE condition1
2. AND condition2
3. ...
4. AND condition_n;
Parameter explanation:
1. SELECT *
2. FROM cus_tbl
3. WHERE cus_firstname = 'Ajeet'
4. AND cus_id > 3;
Output:
MySQL OR Condition
The MySQL OR condition specifies that if you take two or more conditions then one of
the conditions must be fulfilled to get the records as result.
Syntax:
1. WHERE condition1
2. OR condition2
3. ...
4. OR condition_n;
Parameter explanation
1. SELECT *
2. FROM cus_tbl
3. WHERE cus_firstname = 'Ajeet'
4. OR cus_id > 100;
Output:
MySQL AND & OR condition
In MySQL, you can use AND & OR condition both together with the SELECT, INSERT,
UPDATE and DELETE statement. While combine these conditions, you must be aware
where to use round brackets so that the database know the order to evaluate each
condition.
Syntax:
1. WHERE condition1
2. AND condition2
3. ...
4. OR condition_n;
Parameter
1. SELECT *
2. FROM students
3. WHERE (course_name = 'Java' AND student_name = 'Aryan')
4. OR (student_id < 2);
Output:
MySQL Boolean
A Boolean is the simplest data type that always returns two possible values,
either true or false.
It can always use to get a confirmation in the form of YES or No value.
MySQL does not contain built-in Boolean or Bool data type.
They provide a TINYINT data type instead of Boolean or Bool data types.
MySQL considered value zero as false and non-zero value as true.
If you want to use Boolean literals, use true or false that always evaluates to 0 and
1 value.
The 0 and 1 represent the integer values.
Execute the following statement to see the integer values of Boolean literals:
In the above query, we can see that the pass field is defined as a Boolean when
showing the definition of a table; it contains TINIINT as follows:
Let us add two new rows in the above table with the help of following query:
When the above query executed, immediately MySQL checks for the Boolean data
type in the table. If the Boolean literals found, it will be converted into integer values
0 and 1. Execute the following query to get the data from the student table:
You will get the following output where the true and false literal gets converted into 0
and 1 value.
Since MySQL always use TINYINT as Boolean, we can also insert any integer values
into the Boolean column. Execute the following statement:
In some cases, you need to get the result in true and false literals. In that case, you
need to execute the if() function with the select statement as follows:
1. Mysql> SELECT studentid, name, IF(pass, 'true', 'false') completed FROM student
1;
The above statement only returns the pass result if the value is equal to 1. We can fix
it by using the IS operator. This operator validates the value with the Boolean value.
The following statement explains this:
After executing this statement, you will get the following result:
If you want to see the pending result, use IS FALSE or IS NOT TRUE operator as
below:
Syntax:
Parameters
expression: It specifies a column or field.
1. SELECT officer_name
2. FROM officers
3. WHERE address LIKE 'Luck%';
Output:
1.
2. SELECT officer_name
3. FROM officers
4. WHERE address LIKE 'Luc_now';
Output:
3) Using NOT Operator:
You can also use NOT operator with MySQL LIKE condition. This example shows the
use of % wildcard with the NOT Operator.
1. SELECT officer_name
2. FROM officers
3. WHERE address NOT LIKE 'Luck%';
Output:
MySQL IN Condition
The MySQL IN condition is used to reduce the use of multiple OR conditions in a
SELECT, INSERT, UPDATE and DELETE statement.
Syntax:
Parameters
expression: It specifies a value to test.
value1, value2, ... or value_n: These are the values to test against expression. If
any of these values matches expression, then the IN condition will evaluate to true.
This is a quick method to test if any one of the values matches expression.
MySQL IN Example
Consider a table "officers", having the following data.
Execute the following query:
1. SELECT *
2. FROM officers
3. WHERE officer_name IN ('Ajeet', 'Vimal', 'Deepika');
Output:
1. SELECT *
2. FROM officers
3. WHERE officer_name = 'Ajeet'
4. OR officer_name = 'Vimal'
5. OR officer_name = 'Deepika';
Output:
The ANY operator works like comparing the value of a table to each value in the result
set provided by the subquery condition. And then, if it finds any value that matches at
least one value/row of the subquery, it returns the TRUE result.
Syntax
The following is the syntax that illustrates the use of ANY operator in MySQL:
We can understand how ANY works in MySQL through the below statement:
1. SELECT colm1 FROM table1 WHERE colm1 > ANY (SELECT colm1 FROM table
2);
Suppose table1 has a row that contains a number (10). In such a case, the above
expression returns true if table2 contains (20, 15, and 6). It is because there is a
value 6 in table2, which is less than 10. This expression returns false if table2
contains (15, 20), or if table2 is empty. If all the table fields contain (NULL, NULL,
NULL), this expression is unknown.
Example
Let us create a two table named table1 and table2 and then insert some values into
them using the below statements:
Now, we will execute the below statement to understand the use of the ANY operator:
This statement returns true and gives the below output because table2 contains (20,
10, and 7) and there is a value 7 in table2 which is less than 10, 20, and 25 of table1.
The IN keyword in MySQL is an alias for = ANY when used with a subquery in the
statement. Hence, the below two statements are identical in MySQL:
1. SELECT colm1 FROM table1 WHERE colm1 = ANY (SELECT colm1 FROM table
2);
2. SELECT colm1 FROM table1 WHERE colm1 IN (SELECT colm1 FROM table2);
But we cannot say that IN and = ANY were synonyms when we used it with an
expression list. It is because IN can take a list of expressions, but = ANY cannot.
Also, NOT IN cannot be an alias for <> ANY operator, but it can be used for <> ALL.
The word SOME in MySQL can be an alias for ANY. Therefore, these
two SQL statements are equivalent:
1. SELECT colm1 FROM table1 WHERE colm1 <>ANY (SELECT colm1 FROM tabl
e2);
2. SELECT colm1 FROM table1 WHERE colm1 <> SOME (SELECT colm1 FROM table2);
Advantages of ANY operator in MySQL
o ANY is a logical operator that returns the Boolean value. It allows us to select any or
some rows of the SELECT statement.
o Since comparison operators precede this operator, it always returns TRUE if any
subqueries satisfy the specified condition.
o It provides the result, which is a unique column value from a table that matches any
record in the second table.
o We can perform several comparisons using ANY operator with the SELECT and WHERE
keywords.
In this article, we have learned how to use the ANY operator in MySQL. It filters the
result set from SQL syntax only when any of the values satisfy the condition.
Otherwise, it gives a false value.
MySQL Exists
The EXISTS operator in MySQL is a type of Boolean operator which returns the true or
false result. It is used in combination with a subquery and checks the existence of
data in a subquery. It means if a subquery returns any record, this operator returns
true. Otherwise, it will return false. The true value is always represented numeric
value 1, and the false value represents 0. We can use it with SELECT, UPDATE,
DELETE, INSERT statement.
Syntax
The following are the syntax to use the EXISTS operator in MySQL:
1. SELECT col_names
2. FROM tab_name
3. WHERE [NOT] EXISTS (
4. SELECT col_names
5. FROM tab_name
6. WHERE condition
7. );
The NOT operator is used to negates the EXISTS operator. It returns true when the
subquery does not return any row. Otherwise, it returns false.
Generally, the EXISTS query begins with SELECT *, but it can start with the SELECT
column, SELECT a_constant, or anything in the subquery. It will give the same output
because MySQL ignores the select list in the SUBQUERY.
This operator terminates immediately for further processing after the matching result
found. This feature improves the performance of the query in MySQL.
Parameter Explanation
The following are parameters used in the EXISTS operator:
tab_name It is the name of the table from which we are going to perform the EXISTS
condition It specifies for searching the specific value from the table.
subquery It is usually the SELECT statement that begins with SELECT *, but MySQL
Next, we need to insert values into both tables. Execute the below statements:
Again, if we want to get the name of the customer who has not placed an order, then
use the NOT EXISTS operator:
In the output, we can see that the table record whose order_id=3 is deleted
successfully.
If we want to check whether a row exists in a table or not, use the following query:
We will get the output 1 that means true. Hence, cust_id=104 exists in the table.
Difference between EXISTS and IN operator
The main differences between the EXISTS and IN operator is given in a tabular form:
S IN EXISTS
N
1. It is used to minimize the multiple OR conditions in MySQL. It is used to check the existen
3. It compares all values inside the IN operator. It stops for further execut
occurrence.
4. It can use for comparing NULL values. It cannot use for comparing N
5. It executes faster when the subquery result is less. It executes faster when the s
6. It performs a comparison between parent query and child It does not perform a comp
query or subquery. query or subquery.
MySQL NOT Condition
The MySQL NOT condition is opposite of MySQL IN condition. It is used to negate a
condition in a SELECT, INSERT, UPDATE or DELETE statement.
Syntax:
1. NOT condition
Parameter
condition: It specifies the conditions that you want to negate.
1. SELECT *
2. FROM officers
3. WHERE officer_name NOT IN ('Ajeet','Vimal','Deepika');
Output:
1. SELECT *
2. FROM officers
3. WHERE officer_name IS NOT NULL;
Output:
1. SELECT *
2. FROM officers
3. WHERE officer_name NOT LIKE 'A%';
Output:
1. SELECT *
2. FROM officers
3. WHERE officer_id NOT BETWEEN 3 AND 5;
Output:
MySQL Not Equal
MySQL Not Equal is an inequality operator that used for returning a set of rows
after comparing two expressions that are not equal. The MySQL contains two types of
Not Equal operator, which are (< >) and (! =).
Difference Between (< >) and (! =) Operator
The Not Equal operators in MySQL works the same to perform an inequality test
between two expressions. They always give the same result. However, they contain
one difference that “< >” follows the ISO standard whereas “!=” does not follow ISO
standard.
Example 1
Let us create a table student to understand how Not Equal operator works in MySQL.
Suppose the “students” table contains the following data:
Table: students
If you want to get the student details who do not belong to England, then you need
to execute the following statement:
OR,
After successful execution of the above queries, we will get the same output as below:
Example 2
In this example, we are going to understand how Not Equal operator works
with Group By clause. We can use the Group By clause for grouping rows that have
the same data. If we want to get all customers who do not have cellphone
number and duplicate income value, execute the following statement:
In this example, we are going to understand how Not Equal operator works with
a JOIN statement. Let us create a table "contacts" and "customers" in a database
that contains the following data:
Table: contacts
Table: customers
If we want to get all the records from table customers and contacts where the
cellphone is Null, execute the following statement that returns all customers who do
not have a cellphone number:
Example 4
In this example, we are going to understand how the Not Equal operator works with
multiple conditions in the WHERE clause. For example, we want to get the customer
details where income is higher than 40000, and occupation is not
a developer. Execute the following statement to get the result:
1. SELECT * FROM customers Where income>40000 and occupation<>"Develop
er";
After the successful execution of the above statement, we will get the following
output.
Syntax:
1. expression IS NULL
Parameter
expression: It specifies a value to test if it is NULL value.
1. SELECT *
2. FROM officers
3. WHERE officer_name IS NULL;
Output:
Note: Here, you are getting the empty result because there is no NULL value in
officer_name column.
MySQL IS NOT NULL Condition
MySQL IS NOT NULL condition is used to check the NOT NULL value in the expression.
It is used with SELECT, INSERT, UPDATE and DELETE statements.
Syntax:
Parameter
expression: It specifies a value to test if it is not NULL value.
1. SELECT *
2. FROM officers
3. WHERE officer_name IS NOT NULL;
Output:
Note: Here, you are getting the complete "officers" table as result because every
value is NOT NULL in the table.
MySQL BETWEEN Condition
The MYSQL BETWEEN condition specifies how to retrieve values from an expression
within a specific range. It is used with SELECT, INSERT, UPDATE and DELETE
statement.
Syntax:
Parameters
expression: It specifies a column.
value1 and value2: These values define an inclusive range that expression is
compared to.
1. SELECT *
2. FROM officers
3. WHERE officer_id BETWEEN 1 AND 3;
Output:
Note: In the above example, you can see that only three rows are returned between 1 and 3.
1. SELECT *
2. FROM employees
3. WHERE working_date BETWEEN CAST ('2015-01-24' AS DATE) AND CAST
('2015-01-25' AS DATE);
Output:
Note: In the above example you can see that only data between specific dates are shown.
Aggregate Functions
Syntax:
The following are the syntax to use aggregate functions in MySQL:
There are various aggregate functions available in MySQL. Some of the most
commonly used aggregate functions are summarised in the below table:
count() It returns the number of rows, including rows with NULL values in
Let us take an example of myflix (video streaming website which has huge collections
of the movie) database, where management may require the following details:
We can easily produce these details with the help of aggregate functions.
Let us discuss the most commonly used aggregate functions in detail. First, we will
create a new table for the demonstration of all aggregate functions.
Execute the below statement to insert the records into the employee table:
Count() Function
MySQL count() function returns the total number of values in the expression. This
function produces all rows or only some rows of the table based on a specified
condition, and its return type is BIGINT. It returns zero if it does not find any
matching rows. It can work with both numeric and non-numeric data types.
Example
Suppose we want to get the total number of employees in the employee table, we
need to use the count() function as shown in the following query:
Output:
After execution, we can see that this table has six employees.
Sum() Function
The MySQL sum() function returns the total summed (non-NULL) value of an
expression. It returns NULL if the result set does not have any rows. It works with
numeric data type only.
Suppose we want to calculate the total number of working hours of all employees in
the table, we need to use the sum() function as shown in the following query:
Output:
After execution, we can see the total working hours of all employees in the table.
AVG() Function
MySQL AVG() function calculates the average of the values specified in the
column. Similar to the SUM() function, it also works with numeric data type only.
Suppose we want to get the average working hours of all employees in the table, we
need to use the AVG() function as shown in the following query:
1. mysql> SELECT AVG(working_hours) AS "Average working hours" FROM emplo
yee;
Output:
After execution, we can see that the average working hours of all employees in the
organization:
MIN() Function
MySQL MIN() function returns the minimum (lowest) value of the specified
column. It also works with numeric data type only.
Output:
After execution, we can see that the minimum working hours of an employee
available in the table:
MAX() Function
MySQL MAX() function returns the maximum (highest) value of the specified
column. It also works with numeric data type only.
Output:
After execution, we can see that the maximum working hours of an employee
available in the table:
FIRST() Function
This function returns the first value of the specified column. To get the first value
of the column, we must have to use the LIMIT clause. It is because FIRST() function
only supports in MS Access.
Suppose we want to get the first working date of an employee available in the table,
we need to use the following query:
Output:
After execution, we can see that the first working date of an employee available in the
table:
LAST() Function
This function returns the last value of the specified column. To get the last value of
the column, we must have to use the ORDER BY and LIMIT clause. It is because the
LAST() function only supports in MS Access.
Suppose we want to get the last working hour of an employee available in the table,
we need to use the following query:
Output:
After execution, we can see that the last working hour of an employee available in the
table:
GROUP_CONCAT() Function
The GROUP_CONCAT() function returns the concatenated string from multiple
rows into a single string. If the group contains at least one non-null value, it always
returns a string value. Otherwise, we will get a null value.
If we want to concatenate the designation of the same dept_id on the employee table,
we need to use the following query:
Output:
After execution, we can see that the designation of the same dept_id concatenated
successfully:
To read more information, click here.
We can use the count function in three forms, which are explained below:
o Count (*)
o Count (expression)
o Count (distinct)
COUNT(*) Function: This function uses the SELECT statement to returns the count of
rows in a result set. The result set contains all Non-Null, Null, and duplicates rows.
COUNT(expression) Function: This function returns the result set without
containing Null rows as the result of an expression.
Syntax
The following are the syntax of the COUNT() function:
table_name: It specifies the tables from where you want to retrieve records. There
must be at least one table listed in the FROM clause.
WHERE conditions: It is optional. It specifies the conditions that must be fulfilled for
the records to be selected.
Example1
Execute the following query that uses the COUNT(expression) function to calculates
the total number of employees name available in the table:
Output:
Example2
Execute the following statement that returns all rows from the employee table
and WHERE clause specifies the rows whose value in the column emp_age is greater
than 32:
Output:
Example3
This statement uses the COUNT(distinct expression) function that counts the Non-Null
and distinct rows in the column emp_age:
Output:
MySQL Count() Function with GROUP BY Clause
We can also use the count() function with the GROUP BY clause that returns the count
of the element in each group. For example, the following statement returns the
number of employee in each city:
Syntax
Following are the syntax of sum() function in MySQL:
1. SELECT SUM(aggregate_expression)
2. FROM tables
3. [WHERE conditions];
Parameter Explanation
aggregate_expression: It specifies the column or expression that we are going to
calculate the sum.
table_name: It specifies the tables from where we want to retrieve records. There
must be at least one table listed in the FROM clause.
WHERE conditions: It is optional. It specifies the conditions that must be fulfilled for
the records to be selected.
1. Basic Example
Execute the following query that calculates the total number of working hours of all
employees in the table:
Output:
This example is used to return the result based on the condition specified in the
WHERE clause. Execute the following query to calculate the total working hours of
employees whose working_hours >= 12.
Output:
We can also use the SUM() function with the GROUP BY clause to return the total
summed value for each group. For example, this statement calculates the total
working hours of each employee by using the SUM() function with the GROUP BY
clause, as shown in the following query:
Output:
Here, we can see that the total working hours of each employee calculates by
grouping them based on their occupation.
Output:
MySQL uses the DISTINCT keyword to remove the duplicate rows from the column
name. This clause can also be used with sum() function to return the total summed
value of a Unique number of records present in the table.
Execute the following query that removes the duplicate records in the working_hours
column of the employee table and then calculates the sum:
Output:
MySQL avg() function
The MySQL avg() is an aggregate function used to return the average value of an
expression in various records.
Syntax
The following are the basic syntax an avg() function in MySQL:
1. SELECT AVG(aggregate_expression)
2. FROM tables
3. [WHERE conditions];
Parameter explanation
aggregate_expression: It specifies the column or expression that we are going to
find the average result.
table_name: It specifies the tables from where we want to retrieve records. There
must be at least one table listed in the FROM clause.
WHERE conditions: It is optional. It specifies the conditions that must be fulfilled for
the records to be selected.
Execute the following query that calculates the average working hours of all
employees in the table:
Output:
The WHERE clause specifies the conditions that must be fulfilled for the selected
records. Execute the following query to calculate the total average working hours of
employees whose working_hours >= 12.
Output:
The GROUP BY clause is used to return the result for each group by one or more
columns. For example, this statement calculates the average working hours of each
employee using the AVG() function and then group the result with the GROUP BY
clause:
1. mysql> SELECT emp_name, occupation, AVG(working_hours) Avg_working_hou
rs FROM employees GROUP BY occupation;
Output:
Here, we can see that the total working hours of each employee calculates by
grouping them based on their occupation.
The HAVING clause is used to filter the average values of the groups in MySQL.
Execute the following statement that calculates the average working hours of all
employees, grouping them based on their occupation and returns the result
whose Avg_working_hours>9.
Output:
Execute the following query that removes the duplicate records in the working_hours
column of the employee table and then returns the average value:
Output:
Syntax
The following is the basic syntax of MIN() function in MySQL:
Table_name(s): It specifies the tables from where we want to retrieve records. There
must be at least one table listed in the FROM clause.
WHERE conditions: It is optional. It specifies the conditions that must be fulfilled for
the records to be selected.
DISTINCT: It allows us to return the minimum of the distinct values in the expression.
However, it does not affect the MIN() function and produces the same result without
using this keyword.
1. Basic Example
Execute the following query that uses the MIN function to find the minimum
income of the employee available in the table:
Output
The above query produces the result of minimum values in all rows. After execution,
we will get the output as below:
2. MySQL MIN() Function with WHERE Clause
The WHERE clause allows us to filter the result from the selected records. The
following statement finds the minimum income in all rows from the employee table
and WHERE clause specifies all those rows whose emp_age column is greater than
or equal to 32 and less than or equal to 40.
Output
Output
After the successful execution, we can see that the income of each employee returns
by grouping them based on their age:
4. MySQL MIN() Function with HAVING Clause
The HAVING clause is always used with the GROUP BY clause to filter the records from
the table. For example, the below statement returns the minimum income of all
employees, grouping them based on their city and returns the result whose
MIN(income)>150000.
Output
Execute the following query that removes the duplicate records in the income column
of the employee table, group by city, and then returns the minimum value:
1. mysql> SELECT emp_name, city, MIN(DISTINCT income) AS Minimum_Income
2. FROM employees
3. GROUP BY city;
Output
Syntax
The following is the basic syntax of MAX() function in MySQL:
table_name(s): It specifies the tables from where we want to retrieve records. There
must be at least one table listed in the FROM clause.
WHERE conditions: It is optional. It specifies the conditions that must be fulfilled for
the records to be selected.
Output
The above query produces the result of maximum values in all rows. After execution,
we will get the output as below:
Output
Output
After the successful execution, we can see that the maximum income of the employee
returns by grouping them based on their age:
Output
This statement will return the output as below:
Execute the following query that removes the duplicate records in the employee
table's income column, group by city, and then returns the maximum value:
Output
The subquery first finds the maximum age of employees from the table. Then, the
main query (outer query) returns the result of age being equal to the maximum age
returned from the subquery and other information.
Output
1. GROUP_CONCAT(
2. DISTINCT expression
3. ORDER BY expression
4. SEPARATOR sep
5. );
OR,
Distinct: This clause removes the duplicate values in the group before doing
concatenation.
Order By: It allows us to sorts the group data in ascending or descending order and
then perform concatenation. By default, it performs the sorting in the ascending
order. But, you can sort values in descending order using the DESC option explicitly.
Separator: By default, this clause uses comma(,) operator as a separator. If you want
to change the default separator, you can specify the literal value.
NOTE: This function always returns a result in binary or non-binary string value that depends
on the specified arguments. By default, it returns maximum length of string value equal to
1024. If you want to increase this length, you can use the group_concat_max_len system
variable.
GROUP_CONCAT() Example
Let us create a table employee to understand how this function works in MySQL using
different queries.
After successful execution of the above statement, we will get the following output:
1. mysql>SELECT emp_fname,
2. GROUP_CONCAT(DISTINCT designation SEPARATOR '; ') as "designation" FROM emplo
yee group by emp_id;
Here, the separator clause changes the default returning string comma(,) to a
semicolon(;) and a whitespace character.
Now, you are aware of the working of the GROUP_CONCAT() function. Sometimes, we
can use this function with the CONCAT_WS() function that gives the more useful
result. The following statement explains it more clearly:
In this statement, the CONCAT_WS() function first concatenates the first name and
last name of each employee and results in the full name of the employees. Next, we
use the GROUP_CONCAT() function with a semicolon (;) separator clause to make the
list of all employees in a single row. Finally, execute the statement. After successful
execution, we will get the following output:
This function returns the result in a single row, not a list of values. Therefore, we
cannot work GROUP_CONCAT() function with the IN operator. If we use an IN operator
with this function, then the query will not work because the IN operator accepts a list
of values, not a string.
MySQL first function
The MySQL first function is used to return the first value of the selected column. Here,
we use limit clause to select first record or more.
Syntax:
1. SELECT column_name
2. FROM table_name
3. LIMIT 1;
1. SELECT officer_name
2. FROM officers
3. LIMIT 1;
Output:
To SELECT FIRST two records
1. SELECT officer_name
2. FROM officers
3. LIMIT 2;
Output:
Syntax:
1. SELECT column_name
2. FROM table_name
3. ORDER BY column_name DESC
4. LIMIT 1;
1. SELECT officer_name
2. FROM officers
3. ORDER BY officer_id DESC
4. LIMIT 1;
Output:
Return the last officer_name ordering by officer_name:
1. SELECT officer_name
2. FROM officers
3. ORDER BY officer_name DESC
4. LIMIT 1;
Output:
Literals: Date and Time
In MySQL programming, Date and Time literals are in the form of strings or numbers.
Following are some more formats in which date and time can be displayed.
EXAMPLE FORMAT
'2018-10-18' 'YYYY-MM-DD'
'20181018' 'YYYYMMDD'
20181018 YYYYMMDD
'18-10-18' 'YY-MM-DD'
181018 YYMMDD
'2018101852520' 'YYYYMMDDHHMMSS'
2018101852520 YYYYMMDDHHMMSS
'18101852520' 'YYMMDDHHMMSS'
18101852520 YYMMDDHHMMSS
Example 1
Example 2