MySQL - Notes (KVS)
MySQL - Notes (KVS)
(Notes)
MySQL
MySQL provides basic and advanced concepts of MySQL. Our MySQL is designed for beginners and professionals.
MySQL is a relational database management system based on the Structured Query Language, which is the popular language
for accessing and managing the records in the database. MySQL is open-source and free software under the GNU license. It is
Our MySQL includes all topics of MySQL database that provides for how to manage database and to manipulate data with the
help of various SQL queries. These queries are: insert records, update records, delete records, select records, create tables, drop
tables, etc. There are also given MySQL interview questions to help you better understand the MySQL database.
What is Database?
It is very important to understand the database before learning MySQL. A database is an application that stores the organized
collection of records. It can be accessed and manage by the user very easily. It allows us to organize data into tables, rows,
columns, and indexes to find the relevant information very quickly. Each database contains distinct API for performing data-
base operations such as creating, managing, accessing, and searching the data it stores. Today, many databases available like
MySQL, Sybase, Oracle, Mongo DB, Postgre SQL, SQL Server, etc. In this section, we are going to fo-
cus on MySQL mainly.
MySQL is one of the most popular relational database management software that is widely used in today's industry. It provides
multi-user access support with various storage engines. It is backed by Oracle Company. In this section, we are going to learn
Prerequisites
The following requirements should be available in your system to work with MySQL:
o RAM 4 GB (6 GB recommended)
o Step 1: Go to the official website of MySQL and download the community server edition software. Here,
you will see the option to choose the Operating System, such as Windows.
o Step 2: Next, there are two options available to download the setup. Choose the version number for the MySQL com-
munity server, which you want. If you have good internet connectivity, then choose the MySQL-installer-web-com-
Step 1: After downloading the setup, unzip it anywhere and double click the MSI installer .exe file. It will give the following
screen:
Step 2: In the next wizard, choose the Setup Type. There are several types available, and you need to choose the appropriate
option to install MySQL product and features. Here, we are going to select the Full option and click on the Next button.
This option will install the following things: MySQL Server, MySQL Shell, MySQL Router, MySQL Workbench, MySQL
Connectors, documentation, samples and examples, and many more.
Step 3: Once we click on the Next button, it may give information about some features that may fail to install on your system
due to a lack of requirements. We can resolve them by clicking on the Execute button that will install all requirements automat-
After clicking on the Yes button, we will see the list of the products which are going to be installed. So, if we need all products,
Step 5: Once we click on the Execute button, it will download and install all the products. After completing the installation, click
because there is no need to use it with MySQL. We are going to show you how to configure the server only. Now, click on the
Next button.
Step 7: As soon as you will click on the Next button, you can see the screen below. Here, we have to configure the MySQL
Server. Now, choose the Standalone MySQL Server/Classic MySQL Replication option and click on Next. Here, you can also
going to select the Config Type as 'Development Machine' and Connectivity as TCP/IP, and Port Number is 3306, then click
on Next.
Step 9: Now, select the Authentication Method and click on Next. Here, I am going to select the first option.
Step 10: The next screen will ask you to mention the MySQL Root Password. After filling the password details, click on the Next
button.
Step 11: The next screen will ask you to configure the Windows Service to start the server. Keep the default setup and click on
Step 12: In the next wizard, the system will ask you to apply the Server Configuration. If you agree with this configuration, click
Step 14: In the next screen, you can see that the Product Configuration is completed. Keep the default setting and click on the
Step 16: In the next wizard, we will see the Connect to Server option. Here, we have to mention the root password, which we
In this screen, it is also required to check about the connection is successful or not by clicking on the Check button. If the
connection is successful, click on the Execute button. Now, the configuration is complete, click on Next.
Step 17: In the next wizard, select the applied configurations and click on the Execute button.
Step 18: After completing the above step, we will get the following screen. Here, click on the Finish button.
Step 19: Now, the MySQL installation is complete. Click on the Finish button.
Once MySQL has been successfully installed, the base tables have been initialized, and the server has been started, you can
Open your MySQL Command Line Client; it should have appeared with a mysql> prompt. If you have set any password, write
your password here. Now, you are connected to the MySQL server, and you can execute all the SQL command at mysql> prompt
as follows:
For example: Check the already created databases with show databases command:
MySQL Connection
A connection is a computer science facility that allows the user to connect with the database server software. A user can con-
nect with the database server, whether on the same machine or remote locations. Therefore, if we want to work with
the database server to send commands and receive answers in the form of a result set, we need connections. In this article, we
are going to learn how we can connect to MySQL Server in various ways.
MySQL provides various ways to connect with the database server. Once we have installed the MySQL server, we can con-
nect it using any of the client programs that are listed below:
1. Command-line client
2. MySQL Workbench
3. PHP Script.
MySQL command-line client program provides interaction with the database server in an interactive and non-interactive mode.
We can see this program in the bin directory of the MySQL's installation folder. We can open the MySQL command prompt
by navigating to the bin directory of the MySQL's installation folder and type:
MySQL :
If we find the MySQL program in the PATH, we can use the below command to connect to the MySQL Server:
mysql -u root -p :
In the syntax, the -u root indicates that we will connect to the MySQL server using the root user account and -p instructs
Next, we need to type the password for the root user account and press Enter. If everything is correct, it should give the screen
as follows:
This screen indicates that we have successfully connected with the MySQL database server, where we can send commands and
Suppose we want to display all databases available in the current server; we can use the command as follows:
If you want to disconnect the opened MySQL database server, you need to use the exit command.
1. mysql> EXIT;
We can connect to the MySQL database server in workbench by using the following steps:
Step 1: Launch the MySQL Workbench. We should get the following screen:
Step 2: Navigate to the menu bar, click on the 'Database' and choose Connect to Database option or press
the CTRL+U command. We can also connect with the database server by just clicking the plus (+) button located next to the
Step 3: After choosing any of the options, we will get the below screen:
Step 4: Fill the box to create a connection, such as connection name and username, whatever you want. By default, the
username is the root, but we can also change it with a different username in the Username textbox. After filling all boxes, click
the Store in Vault ... button to write the password for the given user account.
Step 5: We will get a new window to write the password and click the OK button.
Step 6: After entering all the details, click on the Test Connection to test the database connectivity is successful or not. If the
Step 7: Again, click on the OK button for saving connection setup. After finishing all the setup, we can see this connection
under MySQL Connections for connecting to the MySQL database server. See the below output where we
The simplest way to connect with the MySQL database server using the PHP script is to use the mysql_connect() function.
This function needs five parameters and returns the MySQL link identifier when the connection becomes successful. If the con-
Syntax
The following is the syntax for MySQL connection using PHP Script:
Server: It is the name of a host that runs the database server. By default, its value will be lcalhost:3306.
User: It is the name of a user who accesses the database. If we will not specify this field, it assumes the default value that will
Password: It is the password of a user whose database you are going to access. If we will not specify this field, it assumes the
New_link: If we make a second call with the same arguments in the mysql_connect() function, MySQL does not establish a new
connection. Instead, we will get the identifier of the already opened database connection.
If we want to disconnect from the MySQL database server, we can use another PHP function named mysql_close(). It ac-
cepts only a single parameter that will be a connection returned by the mysql_connect() function. Its syntax is given below:
If we do not specify any resource, MySQL will close the last opened database. This function returns true when the connection is
Example:
The following examples explain how to connect to a MySQL server using PHP Script:
<html>
<head>
</head>
<body>
<?php
$servername = 'localhost:3306';
$username = 'javatpoint';
$dbpass = 'jtp123';
if(! $conn ) {
?>
</body>
</html>
MySQL Workbench
MySQL Workbench is a unified visual database designing or graphical user interface tool used for working with database archi-
tects, developers, and Database Administrators. It is developed and maintained by Oracle. It provides SQL development, data
modelling, data migration, and comprehensive administration tools for server configuration, user administration, backup, and
many more. We can use this Server Administration for creating new physical data models, E-R diagrams, and for SQL develop-
ment (run queries, etc.). It is available for all major operating systems like Mac OS, Windows, and Linux. MySQL Workbench fully
MySQL Workbench covers five main functionalities, which are given below:
SQL Development: This functionality provides the capability that enables you to execute SQL queries, create and manage con-
nections to the database Servers with the help of built-in SQL editor.
Data Modelling (Design): This functionality provides the capability that enables you to create models of the database Schema
graphically, performs reverse and forward engineering between a Schema and a live database, and edit all aspects of the data-
base using the comprehensive Table editor. The Table editor gives the facilities for editing tables, columns, indexes, views, trig -
Server Administration: This functionality enables you to administer MySQL Server instances by administering users, inspect-
ing audit data, viewing database health, performing backup and recovery, and monitoring the performance of MySQL Server.
Data Migration: This functionality allows you to migrate from Microsoft SQL Server, SQLite, Microsoft Access, PostgreSQL, Sy -
base ASE, SQL Anywhere, and other RDBMS tables, objects, and data to MySQL. It also supports migrating from the previous ver-
MySQL Enterprise Supports: This functionality gives the support for Enterprise products such as MySQL firewall, MySQL En-
MySQL Workbench is mainly available in three editions, which are given below:
The Community Edition is an open-source and freely downloadable version of the most popular database system. It came under
Standard Edition
It is the commercial edition that provides the capability to deliver high-performance and scalable Online Transaction Processing
(OLTP) applications. It has made MySQL famous along with industrial-strength, performance, and reliability.
Enterprise Edition
It is the commercial edition that includes a set of advanced features, management tools, and technical support to achieve the
highest scalability, security, reliability, and uptime. This edition also reduces the risk, cost, complexity in the development, de-
Here, we are going to learn how we can download and install MySQL Workbench.
Prerequisites
The following requirements should be available in your system to work with MySQL Workbench:
o RAM 4 GB (6 GB recommended)
Installation
Step 1: Install the MySQL Community Server. To install MySQL Server, double click the MySQL installer .exe file. After clicking
Step 2: Choose the Setup Type and click on the Next button. There are several types available, and you need to choose the
appropriate option to install MySQL product and features. Here, we are going to select a Custom option because there is a need
for only MySQL Server and Workbench. If you need more features, you can choose the Full option.
Step 3: When you click on the Next button, it will give the following screen.
In this screen, go to the MySQL Server section, click the plus (+) icon. Here, you need to choose the MySQL Server and add it
Step 4: When you click on Next, it will give the following screen. This screen checks all the requirements for installing MySQL
Server and Workbench. As soon as you click on the Execute button, it will install all requirements automatically. Now, click on
the Next button.
Step 5: In this screen, click on the Execute button to download and install the MySQL Server and Workbench.
Step 7: As soon as you will click on the Next button, you can see the screen below. Here, we have to configure the MySQL
Server. Now, choose the Standalone MySQL Server/Classic MySQL Replication option and click on Next.
Step 8: In the next screen, the system will ask you to choose the Config Type and other connectivity options. Here, we are
going to select the Config Type as 'Development Machine' and Connectivity as TCP/IP, and Port Number is 3306, then click
on Next.
Next button.
Step 11: The next screen will ask you to configure the Windows Service. Keep the default setup and click on Next.
Step 12: In the next screen, the system will ask you to apply the Server Configuration. For this configuration, click on the
Execute button.
Step 13: Once the configuration has completed, you will get the screen below. Now, click on the Finish button to continue.
Step 14: In the next screen, you can see that the Product Configuration is completed. Keep the default setting and click on the
below.
Step 16: In the above screen, you need to make a connection. To do this, double click the box designated by the red arrow.
Here, you will get the popup screen that asks to enter the password created earlier during the installation. After entering the
Step 17: If you do not have a connection, you can create a new connection. To make a connection, click the plus (+) icon or go
to the menu bar -> Database -> Connect to Database, the following screen appears. Now, you need to fill all the details. Here,
you have to make sure that the entered password should be the same as you have created earlier.
Step 18: After entering all the details, click on the Test Connection to test the database connectivity. If the connection is
successful, you will get the following screen. Now, click on OK->OK button to finish the setup.
Step 19: Once you have finished all the setup, it will open the MySQL Workbench screen. Now, double click on the newly
created connection, you will get the following screen where the SQL command can be executed.
MySQL Workbench Administration Tool
The Administration Tool plays an important role in securing the data of the company. Here, we are going to discuss the user's
management, Server configuration, Database backup and restorations, Server logs, and many more.
User Administration
It is a visual utility that allows for managing the user that relate to an active MySQL Server instance. Here, you can add and
manage user accounts, grant and drop privileges, view user-profiles, and expire passwords.
Server Configuration
It allows for advanced configuration of the Server. It provides detailed information about the Server and status variable, a num-
ber of threads, buffer allocation size, fine-tuning for optimal performance, and many more.
It is a visual tool, which is used for importing/exporting MySQL dump files. The dump files contain SQL scripts for creating data -
Server Logs
It displays log information for the MySQL Server by each connection tab. For each connection tab, it includes an additional tab
Performance Dashboard
This tab provides the statistical view of the Server performance. You can open it by navigating to the Navigation tab, and under
In this section, we are going to see how a database is created, altered, and drop by using the MySQL Workbench. Let us see in
Create Database
1. Open the MySQL Workbench and logged in using username and password. Then, go to the Navigation tab and click on
the Schema menu. Here, you can see all the previously created databases.
2. If you want to create a new database, right-click under the Schema menu and select Create Schema or click the database
4. The new Schema window screen open. Enter the new database name (for example, mytestdb) and use default Collation.
Collation is used to store specific data characters, mainly useful for storing foreign languages. Now, click on the Apply button as
5. After the successful creation of the database, you can see this new database in the Schema menu. If you do not see this, click
6. If you want to see more information about the database, select mytestdb database, and click on the 'i' icon. The information
window displays several options, like Table, Column, Functions, Users, and many more.
7. MySQL Workbench does not provide an option to rename the database name, but we can create, update, and delete the table
Drop Database
1. To delete a database, you need to choose the database, right-click on it, and select the Drop Schema option. The following
screen appears:
2. Select Drop Now option in the popup window and the database including table, data rows will be deleted from the database
Server.
In this section, we are going to see how a table is created, altered, and drop by using the MySQL Workbench. Let us see in detail
one by one.
Create Table
1. Open the MySQL Workbench and logged in using username and password. Then, go to the Navigation tab and click on the
Schema menu. Here, you can see all the previously created databases. You can also create a new database.
2. Select the newly created database, double click on it, and you will get the sub-menu under the database. The sub-menu under
the database 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. You can also click on create a new table icon (shown
4. On the new table screen, you need to fill all the details to create a table. Here, we are going to enter the table name (for ex -
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
7. Now, go to the Schema menu and select the database which contains the newly created table, as shown in the screen below.
Alter Table
1. Select the table you want to modify, click on the 'i' icon, and you will get the following screen.
2. In the above screen, you can modify the column name, data type, and other table settings.
Drop a Table
1. To delete a table, you need to choose the table, right-click on it, and select the Drop Table option. The following screen ap-
pears:
2. Select Drop Now option in the popup window to delete the table from the database instantly.
In this section, we are going to see how we can insert, read, update, and delete data rows by using the MySQL Workbench. Let
1. Open the MySQL Workbench and logged in using username and password. Then, go to the Navigation tab and click on the
Schema menu. Here, we have successfully created a database (mystudentdb) and student table using MySQL Workbench.
2. Select the table, and when we hour a mouse pointer over the student table, you can see the table icons appears here. Click
the table, which will open a new window where the upper section shows the MySQL statement, and the lower section shows the
data rows.
3. To enter a data row, select the respected column, and insert the data value. Inserting data value in rows is similar to the
4. After entering the data rows, click on the Apply->Apply>Finish button to save the data rows.
5. Similarly, we can edit or modify the previously saved data rows. After modification, save new value, click on the Apply button
to save changes. It will generate an SQL update statement save the changes to the database.
Delete Row
1. To delete an individual row from the table, you need to select a data row, right-click on the right icon in front of the row and
In this section, we are going to learn how we can export and import the database or table by using the MySQL Workbench.
Export Databases(Tables)
1. To export databases or tables, go to the Menu bar, click on Server, and select the Data Export option, as shown in the follow -
ing screen. It will open a new window of data export settings and options.
3. Select any database, and it will display all the corresponding tables under the selected database. Here, we can also select one or
multiple database checkboxes to include the database in the Export file. Similarly, we can select one or multiple tables from the
3. Let us select two databases, namely (myproductdb and mystudentdb), including all tables under this database. Now, go to the
drop-down setting, we can select 'Dump Structure and Data', 'Dump Data Only', and 'Dump Structure Only' option.
o Dump Data and Structure: It will save both table structure and data rows.
o Dump Data Only: It will save only the inserted rows in the tables.
o Dump Structure Only: It will save only the table structure, which are database columns and data types defined by
us.
4. In the Export option, you can select the export path of your choice. Here, I will keep the default setting. Also, there are two ra-
o Export to Dump Project Folder: It will save all the tables as separate SQL files under one folder. It will be useful
when you import or restore the export file one by one table.
o Export to Self-Contained File: It will store all the databases and tables in a single SQL file. It is a good option when
you want to import all the databases, tables, and data rows using a single SQL file.
5. Click the Start Export button, which displays the progress bar and log. Now, open the Document folder in your system to loc-
1. To import databases or tables, go to the Menu bar, click on Server, and select the Data Import option. It will open a new win-
2. Here, you can see the two radio options to import databases and tables, which are:
3. We are going to select 'Import from Dump Project Folder' and click on 'Load Folder Content' to display all the available data -
4. Select myproductdb database from the Data Import option and also select the corresponding product table.
5. Choose the 'Dump Structure and Data' option and click the Start Import button to import the databases and tables from the
backup file.
5. Now, go to the Schema->myproductdb->table and refresh it to see the currently imported database or table.
Sometimes you want to manage a database in MySQL. In that case, we need to see the list of all user's accounts in a database.
Most times, we assume that there is a SHOW USERS command similar to SHOW DATABASES, SHOW TABLES, etc. for displaying
the list of all users available in the database server. Unfortunately, MySQL database does not have a SHOW USERS command to
display the list of all users in the MySQL server. We can use the following query to see the list of all user in the database server:
After the successful execution of the above statement, we will get the user data from the user table of the MySQL database
server.
Let us see how we can use this query. First, we have to open the MySQL server by using the mysql client tool and log in
as an administrator into the server database. Execute the following query:
Database changed
We will get the following output where we can see the five users in our local database:
If we want to see more information on the user table, execute the command below:
It will give the following output that lists all the available columns of the mysql.user database:
To get the selected information like as hostname, password expiration status, and account locking, execute the query as below:
We can get information of the current user by using the user() or current_user() function, as shown below:
or,
After executing the above command, we will get the following output:
We can see the currently logged user in the database server by using the following query in the MySQL server:
MySQL Database:
MySQL Create Database
A database is used to store the collection of records in an organized form. It allows us to hold the data into tables, rows,
columns, and indexes to find the relevant information frequently. We can access and manage the records through the database
very easily.
MySQL Implements a database as a directory that stores all files in the form of a table. It allows us to create a database
mainly in two ways:
2. MySQL Workbench
We can create a new database in MySQL by using the CREATE DATABASE statement with the below syntax:
[COLLATE collation_name];
Parameter Explanation
Parameter Description
database_name It is the name of a new database that should be unique in the MySQL server instance. The IF
NOT EXIST clause avoids an error when we create a database that already exists.
charset_name It is optional. It is the name of the character set to store every character in a string. MySQL
database server supports many character sets. If we do not provide this in the statement,
Example
Let us understand how to create a database in MySQL with the help of an example. Open the MySQL console and write down the
password, if we have set during installation. Now we are ready to create a database. Here, we are going to create a database
We can review the newly created database using the below query that returns the database name, character set, and collation
of the database:
After executing the above query, we can see all the created databases in the server.
Finally, we can use the below command to access the database that enables us to create a table and other database objects.
NOTE: All the database names, table names, and table field names are case sensitive. We must have to use proper names while giving any SQL
command.
SELECT Database is used in MySQL to select a particular database to work with. This query is used when multiple databases are
Syntax:
USE database_name;
Example:
USE customers;
When we work with the MySQL server, it is a common task to show or list the databases, displaying the table from a particular database, and information of user
accounts and their privileges that reside on the server. In this article, we are going to focus on how to list databases in the MySQL server.
We can list all the databases available on the MySQL server host using the following command, as shown below:
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 host, where you can execute all the SQL statements. Finally,
run the SHOW Databases command to list/show databases.
synonyms of the SHOW DATABASES and gives the same result. We can understand it with the following output:
Show Databases command in MySQL also provides an option that allows us to filter the returned database using different pat-
tern matching with LIKE and WHERE clause. The LIKE clause list the database name that matches the specified pattern. The
WHERE clause provides more flexibility to list the database that matches the given condition in the SQL statement.
Syntax
The following are the syntax to use pattern matching with Show Databases command:
OR,
We can understand it with the example given below where percent (%) sign assumes zero, one, or multiple characters:
the schemata table in the information schema. The information schema in MySQL is an information database so that we can use
This statement will give the same result as the SHOW DATABASES command:
Now, we are going to see how we can use the WHERE clause with the SHOW DATABASES command. This statement returns the
NOTE: It is to be noted that if the MySQL server started with the "--skip-show-database" option, we could not use the SHOW DATABASES command
unless we have the SHOW DATABASES privilege.
The MySQL Drop User statement allows us to remove one or more user accounts and their privileges from the database server. If the account does not ex-
ist in the database server, it gives an error.
If you want to use the Drop User statement, it is required to have a global privilege of Create User statement or the DELETE privilege for the MySQL system
schema.
Syntax
The following syntax is used to delete the user accounts from the database server completely.
1. username@hostname
Here, the username is the name of the account, which you want to delete from the database server and the hostname is the
The following are the step required to delete an existing user from the MySQL server database.
Step 1: Open the MySQL server by using the mysql client tool.
Step 2: Enter the password for the account and press Enter.
Step 3: Execute the following command to show all users in the current MySQL server.
Step 4: To drop a user account, you need to execute the following statement.
Here, we are going to remove the username 'martin' from the MySQL server. After the successful execution of the above com-
mand, you need to execute the show user statement again. You will get the following output where username martin is not
present.
Step 5: The DROP USER statement can also be used to remove more than one user accounts at once. We can drop mul-
tiple user accounts by separating account_name with comma operator. To delete multiple user accounts, execute the following
command.
Here, we are going to remove john and peter accounts from the above image. After the successful execution of the above com-
mand, you need to execute the show user statement again. You will get the following output where username john and peter is
not present.
A table is used to organize data in the form of rows and columns and used for both storing and displaying records in the struc -
ture format. It is similar to worksheets in the spread sheet application. A table creation command requires three things:
o Names of fields
MySQL allows us to create a table into the database mainly in two ways:
2. MySQL Workbench
MySQL Command Line Client
MySQL allows us to create a table into the database by using the CREATE TABLE command. Following is a gen-
eric syntax for creating a MySQL table in the database.
column_definition1,
column_definition2,
........,
table_constraints
);
Parameter Explanation
Parameter Description
database_name It is the name of a new table. It should be unique in the MySQL database that we have
selected. The IF NOT EXIST clause avoids an error when we create a table into the
column_definition It specifies the name of the column along with data types for each column. The columns
in table definition are separated by the comma operator. The syntax of column definition
is as follows:
table_constraints It specifies the table constraints such as PRIMARY KEY, UNIQUE KEY, FOREIGN KEY,
CHECK, etc.
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:
);
NOTE:
1. Here, NOT NULL is a field attribute, and it is used because we don't want this field to be NULL. If we try to create a record with a NULL value, then
MySQL will raise an error.
2. The field attribute AUTO_INCREMENT specifies MySQL to go ahead and add the next available number to the id field. PRIMARY KEY is used to
define a column's uniqueness. We can use multiple columns separated by a comma to define a primary key.
We need to use the following command to see the newly created table:
We can use the following command to see the information or structure of the newly created table:
Create Table Using MySQL Workbench
It is a visual GUI tool used to create databases, tables, indexes, views, and stored procedures quickly and efficiently. To create a
new database using this tool, we first need to launch the MySQL Workbench and log in using the username and
password that you want. 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. Now we are
2. Select the database, double click on it, and we will get the sub-menu under the database. These sub-menus are Tables,
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,
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
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 de -
The ALTER statement is always used with "ADD", "DROP" and "MODIFY" commands according to the situation.
Syntax:
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:
Syntax:
...
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,
AFTER cus_age ;
See the recently added columns:
The MODIFY command is used to change the column definition of the table.
Syntax:
Example:
In this example, we modify the column cus_surname to be a data type of varchar(50) and force the column to allow NULL values.
Use the following query to do this:
Syntax:
Let's take an example to drop the column name "cus_address" from the table "cus_tbl".
Output:
Syntax:
column_definition
[ FIRST | AFTER column_name ]
Example:
Output:
6) RENAME table
Syntax:
RENAME TO new_table_name;
Example:
RENAME TO cus_table;
Output:
The show or list table is very important when we have many databases that contain various tables. Sometimes the table names
are the same in many databases; in that case, this query is very useful. We can get the number of table information of a data-
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:
mysql>SHOW TABLES;
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
If we want to show or list the table name from different databases or database to which you are not connected without switch-
ing, MySQL allows us to use the FROM or IN clause followed by the database name. The following statement explains it more
clearly:
mysql> SHOW TABLES IN database_name;
When we execute the below statements, we will get the same result:
OR,
Output:
Show Tables command in MySQL also provides an option that allows us to filter the returned table using different pattern
Syntax
The following are the syntax to use pattern matching with show table command:
OR,
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
Here, we can also see another example of Show Tables statement with the WHERE clause:
Sometimes our table name is non-meaningful, so it is required to rename or change the name of the table. MySQL provides a
useful syntax that can rename one or more tables in the current database.
Syntax
The following are the syntax used to change the name of the table:
Here, we have to make sure that new_table_name must not exist, and old_table_name should be present in the database.
Otherwise, it will throw an error message. It is to ensure that the table is not locked as well as there are no active transactions
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
new_tab_name1 TO new_tab_name2;
new_tab_name1 TO new_tab_name2;
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:
Let us understand how the RENAME TABLE statement works in MySQL through the various examples. Suppose we have a table
named EMPLOYEE, and due to some reason, there is a need to change it into the table named CUSTOMER.
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
low statement:
If we want to change the table name customer into employee and table name shirts into garments, execute the following state-
ment:
Output
We can see that the table name customer into employee and table name shirts into garments have successfully renamed.
Rename table using ALTER statement
The ALTER TABLE statement can also be used to rename the existing table in the current database. The following are the syntax
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.
A temporary table allows us to keep temporary data, which is visible and accessible in the current session only. So, first, we
mysql> CREATE TEMPORARY TABLE Students( name VARCHAR(40) NOT NULL, total_marks DECIMAL(12,2) NOT NULL DE-
mysql> INSERT INTO Students(name, total_marks, total_subjects) VALUES ('Joseph', 150.75, 2), ('Peter', 180.75, 2);
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:
Output
The TRUNCATE statement in MySQL removes the complete data without removing its structure. It is a part of DDL or data
definition language command. Generally, we use this command when we want to delete an entire data from a table without
The TRUNCATE command works the same as a DELETE command without using a WHERE clause that deletes com-
plete rows from a table. However, the TRUNCATE command is more efficient as compared to the DELETE command be-
cause 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 re -
makes an entry for the deallocating pages instead of rows in transaction logs. This command also locks the pages instead of
The following points must be considered while using the TRUNCATE command:
5M
90
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 per-
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
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.
Let us demonstrate how we can truncate the table with the help of an example. First, we are going to create a table named
);
Next, we will add values to this table using the below statement:
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
This command gives the following output that shows none of the records present in the table:
If we perform the TRUNCATE operation for the table that uses a foreign key constraint, we will get the following error:
ERROR 1217 (23000): Cannot delete or update a parent row: a foreign key constraint fails
In that case, we need to log into the MySQL server and disable foreign key checks before executing the TRUNCATE state-
ment as below:
SET FOREIGN_KEY_CHECKS=0;
Now, we are able to truncate tables. After execution, re-enable foreign key checks as given below:
SET FOREIGN_KEY_CHECKS=1;
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:
FROM INFORMATION_SCHEMA.TABLES
DESCRIBE means to show the information in detail. Since we have tables in MySQL, so we will use the DESCRIBE command to
show the structure of our table, such as column names, constraints on column names, etc. The DESC command is a short
form of the DESCRIBE command. Both DESCRIBE and DESC command are equivalent and case sensitive.
Syntax
We can use the following steps to show all columns of the table:
2.4M
63
Let us understand it with the help of an example that explains how to show columns of the table in the selected database.
The first step is to login to the database server using the username and password. We should see the output as below image:
>mysql -u root -p
mysql>
The next step is to open a particular database from which you want to display the table information using the following query.
It is the last step to display the table information. Before executing the DESCRIBE statement, we can optionally display all the
tables stored in our selected database with the SHOW TABLES statement:
For example, if we want to show a customer table's structure, execute the below statement. After successful execution, it
We can also use the DESC statement for practice, which is a shorthand of the DESCRIBE command. See the below output:
To display the column information of the table in MySQL Workbench, we first need to launch the Workbench tool
and login with the username and password to the MySQL database server. We will get the following screen:
database under the Schema menu, for example, mysqltestdb. It will pop up the multiple options that can be shown in the fol-
lowing 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:
MySQL also allows the SHOW COLUMNS command to display table structure. It is a more flexible way to get columns information
of a table.
Syntax:
For example, if we execute the below query, we will get all columns information of a table in a particular database:
If we want to show the columns information of a table from another database or not available in the current database, we
OR
In the below image, we can see that we had used the mysqltestdb database. But we had displayed the column's information of a
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 ex-
ecutes the queries. It can work withINSERT, SELECT, DELETE, UPDATE, and REPLACE quer-
ies. 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:
MYSQL uses a Drop Table statement to delete the existing table. This statement removes the complete data of a table along
with the whole structure or definition permanently from the database. So, you must be very careful while removing the table be -
Syntax
OR,
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 database.
IF EXISTS It is optional, which is used with the DROP TABLE statement to remove the tables only if it
RESTRICT and CASCADE Both are optional parameters that do not have any impact or effect on this statement.
Example
This example specifies how we can drop an existing table from the database. Suppose our database contains a table "orders" as
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:
1. To delete a table, you need to choose the table, right-click on it, and select the Drop Table option. The following screen ap-
pears:
2. Select Drop Now option in the popup window to delete the table from the database instantly.
Sometimes we want to delete more than one table from the database. In that case, we have to use the table names and separ -
ate them by using the comma operator. The following statement can be used to remove multiple tables:
You can also use the DROP TABLE command to delete the complete table, but it will remove complete table data and structure
both. You need to re-create the table again if you have to store some data. But in the case of TRUNCATE TABLE, it removes only
table data, not structure. You don't need to re-create the table again because the table structure already exists.
MySQL has a feature to create a special table called a Temporary Table that allows us to keep temporary data. We can re-
use this table several times in a particular session. It is available in MySQL for the user from version 3.23, and above so if we
use an older version, this table cannot be used. This table is visible and accessible only for the current session. MySQL deletes
this table automatically as long as the current session is closed or the user terminates the connection. We can also use
the DROP TABLE command for removing this table explicitly when the user is not going to use it.
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
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 cre-
ates 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 connec-
tion 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
In MySQL, the syntax of creating a temporary table is the same as the syntax of creating a normal table statement except the
TEMPORARY keyword. Let us see the following statement which creates the temporary table:
);
If the user wants to create a temporary table whose structure is the same as an existing table in the database, then the above
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:
mysql> CREATE TEMPORARY TABLE Students( student_name VARCHAR(40) NOT NULL, total_marks DECIMAL(12,2) NOT NU
mysql>INSERT INTO Students(student_name, total_marks, total_subjects) VALUES ('Joseph', 150.75, 2), ('Peter', 180.75, 2);
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.
In this example, we are going to create a temporary table whose structure is based on the already available tables in the data-
base.
clause and sorts them based on the price. Write the following statement in the MySQL prompt:
FROM orders o
When we execute the above statement, we will get the following message:
we can also perform queries from the above temporary table "temp_customers" similar to the querying data from a perman-
ent table. The following query explains it more clearly:
NOTE: It is noted that we can use IF NOT EXISTS keyword to avoid the "table already exists" error.
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
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 ex-
ample, if we want to remove the above temporary table "temp_customers", we need to use the following statement:
MySQL copy or clone table is a feature that allows us to create a duplicate table of an existing table, including the table
structure, indexes, constraints, default values, etc. Copying data of an existing table into a new table is very useful in a situation
like backing up data in table failure. It is also advantageous when we need to test or perform something without affecting the
original table, for example, replicating the production data for testing.
We can copy an existing table to a new table using the CREATE TABLE and SELECT statement, as shown below:
FROM existing_table_name;
From the above, first, it creates a new table that indicates in the CREATE TABLE statement. Second, the result set of a SE-
LECT statement defines the structure of a new table. Finally, MySQL fills data getting from the SELECT state-
ment 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:
WHERE condition;
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 ex-
FROM existing_table_name
WHERE condition;
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 de-
pendent 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
Let us demonstrate how we can create a duplicate table with the help of an example. First, we are going to create a table
);
Next, it is required to add values to this table. Execute the below statement:
Now, execute the following statement that copies data from the existing table "original_table" to a new table named
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
This statement creates a duplicate table that contains data for the year 2016 only. We can verify the table using a SELECT
Suppose there a need to copy an existing table along with all dependent objects associated with the table, execute the two
AND,
Suppose there is a situation to copy a table from a different database. In that case, we need to execute the below statements:
LIKE source_db.existing_table_name;
INSERT destination_db.new_table_name
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.
Suppose we have two databases named "mysqltestdb" and "mystudentdb" on the MySQL Server. The mytestdb database
Now, we are going to copy this table into another database named mystudentdb using the following statement:
CREATE TABLE mystudentdb.duplicate_table
LIKE mysqltestdb.original_table;
INSERT mystudentdb.duplicate_table
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 allows us to repair or fix the corrupted table. The repair table in MySQL provides support only for selec-
ted 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 state-
ment.
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
NO_WRITE_TO_BINLOG or LOCAL: It's a place where the server is responsible for writing the REPAIR TABLE statements for the
replication slaves. We can optionally specify the optional NO_WRITE_TO_BINLOG/LOCAL keyword to suppress the logging.
QUICK: The quick option allows the REPAIR TABLE statement for repairing only the index file. It does not allow repairing 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 have mentioned earlier that the repair table does not work for all storage engines. It supports only MyISAM, ARCHIVE, and
CSV tables. The repair table statement does not support views.
We can also use the repair table statement for partitioned tables. But, here, we cannot use the USE_FRM option with this state -
ment. If we want to repair multiple partitions, we can use the ALTER TABLE ... REPAIR PARTITION statement.
Let us understand the working of the repair table statement in MySQL through example. First, we need to create a new table
model_name VARCHAR(45),
cost_price DECIMAL(10,2 ),
sell_price DECIMAL(10,2)
);
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:
FROM information_schema.tables
Here we can see that the storage engine of the vehicle table is InnoDB. Therefore, if we create the repair table using the below
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 supports or not
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 In-
noDB.
) ENGINE = MyISAM;
We will insert some data into this table with the below statement:
Since we have created the MyISAM storage engine table, the repair table statement does not issue any error. See the below
statement:
If we use the REPAIR TABLE statement with the table that does not exist in our selected database, MySQL gives an error mes -
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.
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.
How can we add a column in MySQL table?
MySQL allows the ALTER TABLE ADD COLUMN command to add a new column to an existing table. The following are the
syntax to do this:
In the above,
o Next, after the ADD COLUMN clause, we have to specify the name of a new column along with its definition.
o Finally, we need to specify the FIRST or AFTER keyword. The FIRST Keyword is used to add the column as the first col-
umn of the table. The AFTER keyword is used to add a new column after the existing column. If we have not provided these key-
words, MySQL adds the new column as the last column in the table by default.
Sometimes it is required to add multiple columns into the existing table. Then, we can use the syntax as follows:
Let us understand it with the help of various examples. Here, we will create a table named "Test" using the following state-
ments:
);
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 fol-
lows:
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.
We can verify the record in the Test table as below:
If we accidentally add a new column with the existing column name, MySQL will throw an error. For example, execute the be-
MySQL allows the ALTER TABLE CHANGE COLUMN statement to change the old column with a new name. The following are
In the above,
o Next, after the CHANGE COLUMN clause, we have to specify the old column name and new column name along with
its definition. We must have to specify the column definition even it will not change.
o Finally, we need to specify the FIRST or AFTER keyword. It is optional that specified when we need to change the col -
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
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 cre-
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 effect 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.
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.
SHOW COLUMNS statement in MySQL is a more flexible way to display the column information in a given table. It can also sup-
port views. Using this statement, we will get only that column information for which we have some privilege.
Syntax
The EXTENDED is an optional keyword to display the information, including hidden columns. MySQL uses hidden columns in-
The FULL is also an optional keyword to display the column information, including collation, comments, and the privileges we
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.
We can also use the alternative of table_name FROM db_name syntax as db_name.tbl_name. Therefore, the below
OR,
Let us understand how this statement works in MySQL through various examples.
Suppose we have a table named student_info in a sample database that contains the data as follows:
Next, if we want to get the columns information of this table, we can use the statement as follows:
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:
If we want to display hidden column information, we need to add the FULL keyword to the SHOW COLUMNS statement as fol-
lows:
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:
Collation: It is used to sequence the order of a specific character set. Here it indicates the string column for non-binary values
and NULL for other columns. We will see this column only when we use the FULL keyword.
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
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 PRI-
MARY 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
Default: It indicates the default value to the column. If the column includes no DEFAULT clause or has an explicit NULL default,
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
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.
DESCRIBE statement in MySQL is also provides information similar to the SHOW COLUMNS command.
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.
We first launch the tool and log in with the username and password to display the given table's column information in MySQL
Workbench. Now, we need to do the following steps to show the column information:
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.
Sometimes our column name is non-meaningful, so it is required to rename or change the column's name. MySQL provides a
useful syntax that can rename one or more columns in the table. Few privileges are essential before renaming the column, such
The following are the syntax that illustrates the column rename using the CHANGE statement:
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. Sup-
pose we have a table named balance that contains the data 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
To remove the drawback of a CHANGE statement, MySQL proposed the following syntax that illustrates the changing of the
Example
Let us understand how the RENAME statement works in MySQL to change the column name through the various examples. Sup-
pose we have a table named customer that contains the following data:
Suppose we want to change the column name account with account_no without changing its data types. We can do this by ex-
After executing the above command, we can verify it by using the SELECT statement again. In the below image, the
column name account has changed successfully.
MySQL also allows us to change the multiple column names within a single statement. If we want to rename multiple column
...
...
OR
...
...
Example
Suppose we want to change column names id and customer_name from the customer table. To change multiple column
After executing the above command, we can verify it by using the SELECT statement again. In the below image, the column
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
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 defini-
tions built on top of other tables (or views). If any changes occur in the underlying table, the same changes reflected in the View
also.
2. MySQL Workbench
Syntax
SELECT columns
FROM tables
[WHERE conditions];
Parameters:
OR REPLACE: It is optional. It is used when a VIEW already exists. If you do not specify this clause and the VIEW already exists,
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 courses;
Once the execution of the CREATE VIEW statement becomes successful, MySQL will create a view and stores it in the database..
In MYSQL, the ALTER VIEW statement is used to modify or update the already created VIEW without dropping it.
Syntax:
SELECT columns
FROM table
WHERE conditions;
Example:
The following example will alter the already created VIEW name "trainer" by adding a new column.
FROM courses;
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:
MySQL Drop VIEW
We can drop the existing VIEW by using the DROP VIEW statement.
Syntax:
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 er-
ror.
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:
Here, we will see the complex example of view creation that involves multiple tables and uses a join clause.
Suppose we have two sample tables as shown 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:
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:
Now do the following steps for database deletion:
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:
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
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
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 Queries
A list of commonly used MySQL queries to create database, use database, create table, insert record, update record, delete re -
cord, select record, truncate table and drop table are given below.
use db1;
MySQL create query is used to create a table, view, procedure and function. For example:
(id int(10),
name varchar(50),
city varchar(50),
);
MySQL alter query is used to add, modify, delete or drop colums of a table. Let's see a query to add column in customers table:
MySQL insert query is used to insert records into table. For example:
MySQL update query is used to delete records of a table from database. For example:
Oracle select query is used to fetch records from database. For example:
MySQL update query is used to truncate or remove records of a table. It doesn't remove structure. For example:
MySQL drop query is used to drop a table, view or database. It removes structure and data of a table if you drop table. For ex -
ample:
MySQL Constraints
The constraint in MySQL is used to specify the rule that allows or restricts what values/data will be stored in the table. They
provide a suitable method to ensure data accuracy and integrity inside the table. It also helps to limit the type of data that will
be inserted inside the table. If any interruption occurs between the constraint and data action, the action is failed.
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.
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
);
The following are the most common constraints used in the MySQL:
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.
mysql> CREATE TABLE Student(Id INTEGER, LastName TEXT NOT NULL, FirstName TEXT NOT NULL, City VARCHAR(35));
Output
In the above image, we can see that the first INSERT query executes correctly, but the second statement fails and gives an error
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:
mysql> CREATE TABLE ShirtBrands(Id INTEGER, BrandName VARCHAR(40) UNIQUE, Size VARCHAR(30));
mysql> INSERT INTO ShirtBrands(Id, BrandName, Size) VALUES(1, 'Pantaloons', 38), (2, 'Cantabil', 40);
mysql> INSERT INTO ShirtBrands(Id, BrandName, Size) VALUES(1, 'Raymond', 38), (2, 'Cantabil', 40);
Output
In the below output, we can see that the first INSERT query executes correctly, but the second statement fails and gives an error
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 condi -
tion. 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:
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 sat-
isfied 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
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
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:
Age int,
);
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:
We can see that it works perfectly. It means default value "New York" stored automatically in the City column.
PRIMARY KEY Constraint
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:
Age int,
City varchar(25));
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
This constraint automatically generates a unique number whenever we insert a new record into the table. Generally, we use this
We can understand it with the following example where the id column going to be auto-incremented in the Animal table:
('Tiger'),('Dog'),('Penguin'),
('Camel'),('Cat'),('Ostrich');
Output
In the output, we can see that I have not specified any value for the auto-increment column, so MySQL automatically generates
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.
name VARCHAR(35),
);
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:
Output
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.
name VARCHAR(35),
);
Next, we need to insert the values into the "Shirts" table using the below statements:
We can use the query below to retrieve the data using the index column:
Output
This constraint is used to link two tables together. It is also known as the referencing key. A foreign key column matches the
primary key field of another table. It means a foreign key field in one table refers to the primary key field of another table.
Table: Persons
CREATE TABLE Persons (
Age int,
City varchar(25)
);
Table: Orders
Person_ID int,
);
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
MySQL INSERT statement is used to store or add data in MySQL table within the database. We can perform insertion of records
The below is generic syntax of SQL INSERT INTO command to insert a single record in MySQL table:
VALUES
( value1, value2,...valueN );
In the above syntax, we first have to specify the table name and list of comma-separated columns. Second, we provide the list of
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:
( value1, value2,...valueN )
( value1, value2,...valueN )
...........
( value1, value2,...valueN );
In the above syntax, all rows should be separated by commas in the value fields.
Let us understand how INSERT statements work in MySQL with the help of multiple examples. First, create a table
"People" in the database using the following command:
age int,
);
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.
INSERT INTO People VALUES
3. If we want to store records without giving all fields, we use the following partial field statements. In such case, it is mandat-
In the below output, we can see that all INSERT statements have successfully executed and stored the value in a table correctly.
We can use the below syntax to show the records of the People table:
We can also use the INSERT STATEMENT to add the date in MySQL table. MySQL provides several data types for storing dates
such as DATE, TIMESTAMP, DATETIME, and YEAR. The default format of the date in MySQL is YYYY-MM-DD.
o MM: It represents the two-digit month, like 01, 02, 03, and 12.
o DD: It represents the two-digit day, like 01, 02, 03, and 31.
INSERT INTO table_name (column_name, column_date) VALUES ('DATE: Manual Date', '2008-7-04');
If we want to insert a date in the mm/dd/yyyy format, it is required to use the below statement:
MySQL UPDATE query is a DML statement used to modify the data of the MySQL table within the database. In a real-life scenario,
records are changed over a period of time. So, we need to make changes in the values of the tables also. To do so, it is required
The UPDATE statement is used with the SET and WHERE clauses. The SET clause is used to change the values of the spe-
cified 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:
UPDATE table_name
column_name2=new-value2, ...
[WHERE Clause]
Parameter Explanation
The description of parameters used in the syntax of the UPDATE statement is given below:
Skip Ad
Parameter Descriptions
table_name It is the name of a table in which we want to perform updation.
column_name It is the name of a column in which we want to perform updation with the new value using the
SET clause. If there is a need to update multiple columns, separate the columns with a comma
WHERE Clause It is optional. It is used to specify the row name in which we are going to perform updation. If
Note:
o WHERE clause is very important because sometimes we want to update only a single row, and if we omit this clause, it
LOW_PRIORITY: This modifier instructs the statement to delay the UPDATE command's execution until no other clients reading
from the table. It takes effects only for the storage engines that use only table-level locking.
IGNORE: This modifier allows the statement to do not abort the execution even if errors occurred. If it finds duplicate-key con-
SET column_assignment_list
[WHERE condition]
Example:
Let us understand the UPDATE statement with the help of various examples. Suppose we have a table "trainer" within
the "testdb" database. We are going to update the data within the "trainer" table.
UPDATE trainer
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.
The UPDATE statement can also be used to update multiple columns by specifying a comma-separated list of columns. Suppose
This statement explains will update the name and occupation whose id = 105 in the People table as follows:
UPDATE People
WHERE id = 105;
We can verify the output below:
We can also use the UPDATE statement in MySQL to change the string name in the particular column. The following example up-
UPDATE Trainer_table
MySQL DELETE statement is used to remove records from the MySQL table that is no longer required in the database. This
query in MySQL deletes a full row from the table and produces the count of deleted rows. It also allows us to delete
more than one record from the table within a single query, which is beneficial while removing large numbers of records from a
table. By using the delete statement, we can also remove data based on conditions.
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
Syntax:
The following are the syntax that illustrates how to use the DELETE statement:
5.4M
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 state-
ment, 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 DE-
LETE statement.
If we want to delete all records from a table without knowing the count of deleted rows, we must use the TRUNCATE
Let us understand how the DELETE statement works in MySQL through various examples.
Here, we are going to use the "Employees" and "Payment" tables for the demonstration of the DELETE statement. Suppose
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
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
MySQL Limit clause is used to restrict the count of rows returns from the result set, rather than fetching the whole records in the
table. Sometimes we want to limit the number of rows to be deleted from the table; in that case, we will use the LIMIT clause
as follows:
2. WHERE condition
4. LIMIT row_count;
It is to note that the order of rows in a MySQL table is unspecified. Therefore, we should always use the ORDER BY clause while
For example, the following query first sorts the employees according to their names alphabetically and deletes the first three
The JOIN clause is used to add the two or more tables in MySQL. We will add the JOIN clause with the DELETE statement
whenever we want to delete records from multiple tables within a single query. See the below query:
mysql> DELETE Employees, Payment FROM Employees
ON Employees.emp_id = Payment.emp_id
Output:
To read more information about the DELETE statement with the JOIN clause
The SELECT statement in MySQL is used to fetch data from one or more tables. We can retrieve records of all fields or spe-
cified fields that match specified criteria using this statement. It can also work with various scripting languages such
It is the most commonly used SQL query. The general syntax of this statement to fetch data from tables is as follows:
[WHERE condition]
[GROUP BY field_name(s)]
[HAVING condition]
[ORDER BY field_name(s)]
[GROUP BY fieldName(s)]
[HAVING condition]
[ORDER BY fieldName(s)]
Parameter Explanation
field_name(s) or * It is used to specify one or more columns to returns in the result set. The asterisk (*) returns
WHERE It is an optional clause. It specifies the condition that returned the matched records in the
result set.
GROUP BY It is optional. It collects data from multiple records and grouped them by one or more
columns.
HAVING It is optional. It works with the GROUP BY clause and returns only those rows whose
condition is TRUE.
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 zero.
LIMIT It is optional. It is used to limit the number of returned records in the result set.
NOTE: It is to note that MySQL always evaluates the FROM clause first, and then the SELECT clause will be evaluated.
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:
151
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. Spe-
cifying all column names is not convenient to the user, so MySQL uses an asterisk (*) to retrieve all column data as follows:
We will get the below output where we can see all columns of the table.
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.
SELECT Name, City, SUM(working_hours) AS "Total working hours"
FROM employee_detail
GROUP BY Name
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:
ON customer.cust_id = orders.order_id
ORDER BY cust_name;
After successful execution of the query, we will get the output as follows:
An index is a data structure that allows us to add indexes in the existing table. It enables you to improve the faster retrieval of
records on a database table. It creates an entry for each value of the indexed columns. We use it to quickly find the record
without searching each row in a database table whenever the table is accessed. We can create an index by using one or
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.
Suppose we have a contact book that contains names and mobile numbers of the user. In this contact book, we want to find the
mobile number of Martin Williamson. If the contact book is an unordered format means the name of the contact book is not sor-
ted alphabetically, we need to go over all pages and read every name until we will not find the desired name that we are looking
To find the name and contact of the user from table contactbooks, generally, we used to execute the following query:
5.5M
120
HTML Tutorial
mysql> SELECT mobile_number FROM contactbooks WHERE first_name = 'Martin' AND last_name = 'Taybu';
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
Generally, we create an index at the time of table creation in the database. The following statement creates a table with an in -
col4 VARCHAR(20),
INDEX (col2,col3)
);
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
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 dif-
ferent types of an index based on the storage engine of the table.
1. InnoDB BTREE
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:
mysql> SELECT studentid, firstname, lastname FROM student WHERE class = 'CS';
This statement will give the following output:
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:
mysql> EXPLAIN SELECT studentid, firstname, lastname FROM student WHERE class = 'CS';
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.
After executing the above statement, the index is created successfully. Now, run the below statement to see how MySQL intern-
mysql> EXPLAIN SELECT studentid, firstname, lastname FROM student WHERE class = 'CS';
In this output, MySQL finds four rows from the class index without scanning the whole table. Hence, it increases the speed of re-
If you want to show the indexes of a table, execute the following statement:
MySQL allows a DROP INDEX statement to remove the existing index from the table. To delete an index from a table, we can use
o First, we have to specify the name of the index that we want to remove.
The Drop Index syntax contains two optional options, which are Algorithm and Lock for reading and writing the tables during the
Algorithm Option
The algorithm_option enables us to specify the specific algorithm for removing the index in a table. The syntax
2.2M
54
History of Java
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 op-
erations 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_op-
In the syntax, we can see that the lock_option contains four modes that are DEFAULT, NONE, SHARED, and EXCLUSIVE. Now,
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
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 in-
Again, execute the SHOW INDEXES statement to verify the index is removed or not. After performing this statement, we will get
The following statement drops the age index form the student table using an algorithm and a lock option.
In some cases, the table contains a PRIMARY index that was created whenever you create a table with a primary key or unique
key. In that case, we need to execute the following command because the PRIMARY is a reserved word.
To remove the primary key index from the student table, execute the following statement:
We can get the index information of a table using the Show Indexes statement. This statement can be written as:
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.
If we want to get the index information of a table in a different database or database to which you are not connec -
ted, MySQL allows us to specify the database name with the Show Indexes statement. The following statement explains it
more clearly:
Note: It is noted that Index and Keys both are synonyms of Indexes, and IN is the synonyms of FROM keyword. Therefore, we can also write the Show
Indexes statement with these synonyms as below:
OR,
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
Collation: It gives information about how the column is sorted in the index. It contains values where A represents ascend-
Cardinality: It gives an estimated number of unique values in the index table where the higher cardinality represents a greater
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 in -
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 dis -
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.
Expression: MySQL 8.0 supports functional key parts that affect both expression and column_name columns. We can
understand it more clearly with the below points:
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.
Here, we are going to create a table student_info that contains the student id, name, age, mobile number, and email details.
Now, execute the following command that returns the all index information from the student_info table:
We can filter the index information using where clause. The following statement can be used to filter the index in-
formation:
Example
If you want to get only invisible indexes of the student_info table, execute the following command:
MYSQL CLAUSE
MySQL WHERE Clause is used with SELECT, INSERT, UPDATE and DELETE clause to filter the results. It specifies a specific posi-
Syntax:
WHERE conditions;
Parameter:
conditions: It specifies the conditions that must be fulfilled for records to be selected.
Table structure:
Execute this query:
SELECT *
FROM officers
Output:
In this example, we are retrieving data from the table "officers" with AND condition.
SELECT *
FROM officers
Output:
SELECT *
FROM officers
OR address = 'Mau';
Output:
MySQL WHERE Clause with combination of AND & OR conditions
You can also use the AND & OR conditions altogether with the WHERE clause.
SELECT *
FROM officers
Output:
MySQL Distinct Clause
MySQL DISTINCT clause is used to remove duplicate records from the table and fetch only the unique records. The DISTINCT
Syntax:
FROM tables
[WHERE conditions];
Parameters
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 ex-
pressions listed.
o In MySQL, the DISTINCT clause doesn't ignore NULL values. So if you are using the DISTINCT clause in your SQL state-
If you use a single expression then the MySQL DISTINCT clause will return a single field with unique records (no duplicate re -
cord).
FROM officers;
If you use multiple expressions with DISTINCT Clause then MySQL DISTINCT clause will remove duplicates from more than one
FROM officers;
The MySQL FROM Clause is used to select some records from a table. It can also be used to retrieve records from multiple tables
Syntax:
FROM table1
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.
SELECT *
FROM officers
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.
FROM students
ON students.student_id = officers.officer_id;
MySQL FROM Clause: Retrieve data from two tables using outer join
FROM officers
LEFT OUTER JOIN students
ON officers.officer_id = students.student_id;
The MYSQL ORDER BY Clause is used to sort the records in ascending or descending order.
Syntax:
SELECT expressions
FROM tables
[WHERE conditions]
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.
5.9M
113
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 as-
cending order.
SELECT *
FROM officers
ORDER BY officer_name;
Output:
SELECT *
FROM officers
Output:
MySQL ORDER BY: with DESC attribute
SELECT *
FROM officers
2. FROM officers
The MYSQL GROUP BY Clause is used to collect data from multiple records and group the result by one or more column. It is gen-
You can also use some aggregate functions like COUNT, SUM, MIN, MAX, AVG etc. on the grouped column.
Syntax:
aggregate_function (expression)
FROM tables
[WHERE conditions]
Parameters
expression1, expression2, ... expression_n: It specifies the expressions that are not encapsulated within an aggregate func-
aggregate_function: It specifies a function such as SUM, COUNT, MIN, MAX, or AVG etc. tables: It specifies the tables, from
where you want to retrieve the 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.
FROM officers
GROUP BY address;
Output:
of each employee.
FROM employees
GROUP BY emp_name;
Output:
The following example specifies the minimum working hours of the employees form the table "employees".
Execute the following query:
FROM employees
GROUP BY emp_name;
Output:
The following example specifies the maximum working hours of the employees form the table "employees".
FROM employees
GROUP BY emp_name;
Output:
(v) MySQL GROUP BY Clause with AVG function
The following example specifies the average working hours of the employees form the table "employees".
FROM employees
GROUP BY emp_name;
Output:
MySQL HAVING Clause is used with GROUP BY clause. It always returns the rows where condition is TRUE.
Syntax:
aggregate_function (expression)
FROM tables
[WHERE conditions]
HAVING condition;
Parameters
aggregate_function: It specifies any one of the aggregate function such as SUM, COUNT, MIN, MAX, or AVG.
expression1, expression2, ... expression_n: It specifies the expressions that are not encapsulated within an aggregate func-
WHERE conditions: It is optional. It specifies the conditions for the records to be selected.
5.5M
120
HTML Tutorial
HAVING condition: It is used to restrict the groups of returned rows. It shows only those groups in result set whose conditions
are TRUE.
Here, we use the SUM function with the HAVING Clause to return the emp_name and sum of their working hours.
GROUP BY emp_name
Simply, it can also be used with COUNT, MIN, MAX and AVG functions.
MYSQL CONDITION
The MySQL AND condition is used with SELECT, INSERT, UPDATE or DELETE statements to test two or more conditions in an indi -
vidual query.
Syntax:
WHERE condition1
AND condition2
...
AND condition_n;
Parameter explanation:
condition1, condition2, ... condition_n: Specifies all conditions that must be fulfilled for the records to be selected.
The following example specifies how to use the AND condition in MySQL with SELECT statement.
SELECT *
FROM cus_tbl
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:
WHERE condition1
OR condition2
...
OR condition_n;
Parameter explanation
condition1, condition2, ... condition_n: Specifies all conditions that must be fulfilled for the records to be selected.
MySQL OR Example
The following example specifies how to use the OR condition in MySQL with SELECT statement.
SELECT *
FROM cus_tbl
Output:
Note: In the above example you can see that the second condition "cus_id" is wrong but the query is displaying the correct res -
In MySQL, you can use AND & OR condition both together with the SELECT, INSERT, UPDATE and DELETE statement. While com -
bine these conditions, you must be aware where to use round brackets so that the database know the order to evaluate each
condition.
Syntax:
WHERE condition1
AND condition2
...
OR condition_n;
Parameter
condition1, condition2, ... condition_n: It specifies the conditions that are evaluated to determine if the records will be se -
lected.
SELECT *
FROM students
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 con-
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:
We can store a Boolean value in the MySQL table as an integer data type. Let us create a table student that demonstrates the
age VARCHAR(3),
pass BOOLEAN
);
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 TI-
NIINT 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 follow-
ing 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 se -
Mysql> SELECT studentid, name, IF(pass, 'true', 'false') completed FROM student1;
MySQL also allows us to use operators with the Boolean data type. Execute the following query to get all the pass result of table
student.
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:
SELECT studentid, name, pass FROM student1 WHERE pass IS NOT TRUE;
In MySQL, LIKE condition is used to perform pattern matching to find the correct result. It is used in SELECT, INSERT, UPDATE
Syntax:
Parameters
escape_character: It is optional. It allows you to test for literal instances of a wildcard character such as % or _. If you do not
SELECT officer_name
FROM officers
Output:
SELECT officer_name
FROM officers
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.
SELECT officer_name
FROM officers
Output:
Note: In the above example, you can see that the addresses NOT LIKE 'Luck%' are only shown.
MySQL IN Condition
The MySQL IN condition is used to reduce the use of multiple OR conditions in a SELECT, INSERT, UPDATE and DELETE state -
ment.
Syntax:
Parameters
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
SELECT *
FROM officers
Output:
Let's see why it is preferred over OR condition:
SELECT *
FROM officers
OR officer_name = 'Vimal'
OR officer_name = 'Deepika';
Output:
It also produces the same result. So IN condition is preferred over OR condition because it has minimum number of codes.
MySQL ANY
The ANY keyword is a MySQL operator that returns the Boolean value TRUE if the comparison is TRUE for ANY of the sub-
query condition. In other words, this keyword returns true if any of the subquery condition is fulfilled when the SQL query is ex-
ecuted. The ANY keyword must follow the comparison operator. It is noted that ALL SQL operator works related to ANY op-
erator, but it returns true when all the subquery values are satisfied by the condition in MySQL.
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:
HTML Tutorial
SELECT column_lists FROM table_name1 WHERE column_name Operator ANY (SELECT column_name FROM table_name2 WH
ERE condition);
We can understand how ANY works in MySQL through the below statement:
SELECT colm1 FROM table1 WHERE colm1 > ANY (SELECT colm1 FROM table2);
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:
num_value INT
);
num_val int
);
After successful execution of the above statement, we can verify it by using the SELECT statement as follows:
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
The IN keyword in MySQL is an alias for = ANY when used with a subquery in the statement. Hence, the below two state-
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
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:
SELECT colm1 FROM table1 WHERE colm1 <>ANY (SELECT colm1 FROM table2);
SELECT colm1 FROM table1 WHERE colm1 <> SOME (SELECT colm1 FROM table2);
o ANY is a logical operator that returns the Boolean value. It allows us to select any or some rows of the SELECT state -
ment.
o Since comparison operators precede this operator, it always returns TRUE if any subqueries satisfy the specified con-
dition.
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
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
Syntax
The following are the syntax to use the EXISTS operator in MySQL:
SELECT col_names
FROM tab_name
SELECT col_names
FROM tab_name
WHERE condition
);
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 perform-
Parameter Explanation
tab_name It is the name of the table from which we are going to perform the EXISTS operator.
condition It specifies for searching the specific value from the table.
subquery It is usually the SELECT statement that begins with SELECT *, but MySQL ignores it in a
subquery.
Let us understand how the EXISTS operator works in MySQL. Here, we are going to first create two tables named "customer"
name varchar(35),
occupation varchar(25),
age int
);
cust_id int,
prod_name varchar(45),
order_date date
);
Next, we need to insert values into both tables. Execute the below statements:
AND,
In this example, we are going to use EXISTS operator to find the name and occupation of the customer who has placed at least
one order:
Again, if we want to get the name of the customer who has not placed an order, then use the NOT EXISTS operator:
Suppose we want to delete a record from the Orders table whose order_id = 3, execute the following query that deletes the re -
WHERE order_id=3);
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:
SN IN EXISTS
1. It is used to minimize the multiple OR conditions in It is used to check the existence of data in a subquery.
MySQL.
3. It compares all values inside the IN operator. It stops for further execution as soon as it finds the first
true occurrence.
4. It can use for comparing NULL values. It cannot use for comparing NULL values.
5. It executes faster when the subquery result is less. It executes faster when the subquery result is large.
6. It performs a comparison between parent query It does not perform a comparison between parent query
The MySQL NOT condition is opposite of MySQL IN condition. It is used to negate a condition in a SELECT, INSERT, UPDATE or DE -
LETE statement.
Syntax:
1. NOT condition
Parameter
Singleton pattern | Build a CMS using OOP PHP tutorial MVC [2020]
SELECT *
FROM officers
Output:
SELECT *
FROM officers
We are taking the same table "officer" for this operation also:
SELECT *
FROM officers
Output:
MySQL NOT Operator with BETWEEN condition:
We are taking the same table "officer" for this operation also:
SELECT *
FROM officers
Output:
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 (! =).
The Not Equal operator 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
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 du-
GROUP BY income;
Example 3
In this example, we are going to understand how Not Equal operator works with a JOIN statement. Let us create a table "con-
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
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. Ex-
After the successful execution of the above statement, we will get the following output.
MySQL IS NULL condition is used to check if there is a NULL value in the expression. It is used with SELECT, INSERT, UPDATE and
DELETE statement.
Syntax:
expression IS NULL
Parameter
SELECT *
FROM officers
Output:
Note: Here, you are getting the empty result because there is no NULL value in officer_name column.
MySQL IS NOT NULL condition is used to check the NOT NULL value in the expression. It is used with SELECT, INSERT, UPDATE
Syntax:
Parameter
5.9M
113
SELECT *
FROM officers
Output:
Note: Here, you are getting the complete "officers" table as result because every value is NOT NULL in the table.
The MYSQL BETWEEN condition specifies how to retrieve values from an expression within a specific range. It is used with SE -
Parameters
value1 and value2: These values define an inclusive range that expression is compared to.
SELECT *
FROM officers
Output:
Note: In the above example, you can see that only three rows are returned between 1 and 3.
MySQL BETWEEN condition also facilitates you to retrieve records according to date.
SELECT *
FROM employees
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.
MySQL JOINS
MySQL JOINS are used with SELECT statement. It is used to retrieve data from multiple tables. It is performed whenever you
The MySQL INNER JOIN is used to return all rows from multiple tables where the join condition is satisfied. It is the
most common type of join.
Syntax:
SELECT columns
FROM table1
ON table1.column = table2.column;
Image representation:
Consider two tables "officers" and "students", having the following data.
FROM officers
ON officers.officer_id = students.student_id;
Output:
MySQL Left Outer Join
The LEFT OUTER JOIN returns all rows from the left hand table specified in the ON condition and only those rows from the other
Syntax:
SELECT columns
FROM table1
ON table1.column = table2.column;
Image representation:
Consider two tables "officers" and "students", having the following data.
Execute the following query:
FROM officers
ON officers.officer_id = students.student_id;
Output:
The MySQL Right Outer Join returns all rows from the RIGHT-hand table specified in the ON condition and only those rows from
Syntax:
SELECT columns
FROM table1
ON table1.column = table2.column;
Image representation:
Consider two tables "officers" and "students", having the following data.
FROM officers
ON officers.officer_id = students.student_id;
Output:
MySQL Inner Join
The MySQL Inner Join is used to returns only those results from the tables that match the specified condition and hides other
rows and columns. MySQL assumes it as a default Join, so it is optional to use the Inner Join keyword with the query.
We can understand it with the following visual representation where Inner Joins returns only the matching results from table1
and table2:
The Inner Join keyword is used with the SELECT statement and must be written after the FROM clause. The follow-
ing syntax explains it more clearly:
SELECT columns
FROM table1
...;
In this syntax, we first have to select the column list, then specify the table name that will be joined to the main table, appears
in the Inner Join (table1, table2), and finally, provide the condition after the ON keyword. The Join condition returns the matching
Let us first create two tables "students" and "technologies" that contains the following data:
Table: student
Table: technologies
FROM students
ON students.student_id = technologies.tech_id;
After successful execution of the query, it will give the following output:
The Inner Join can also be used with the GROUP BY clause. The following statement returns student id, technology name, city,
and institute name using the Inner Join clause with the GROUP BY clause.
FROM students
Sometimes, the name of the columns is the same in both the tables. In that case, we can use a USING keyword to access the re-
FROM students
USING (student_id);
The WHERE clause enables you to return the filter result. The following example illustrates this clause with Inner Join:
FROM students
We have already created two tables named students and technologies. Let us create one more table and name it as a con-
tact.
Execute the following statement to join the three table students, technologies, and contact:
FROM students
After successful execution of the above query, it will give the following output:
MySQL allows many operators that can be used with Inner Join, such as greater than (>), less than (<), equal (=), not equal
(=), etc. The following query returns the result whose income is in the range of 20000 to 80000:
FROM employee
The Left Join in MySQL is used to query records from multiple tables. This clause is similar to the Inner Join clause that can be
used with a SELECT statement immediately after the FROM keyword. When we use the Left Join clause, it will return all the re -
cords from the first (left-side) table, even no matching records found from the second (right side) table. If it will not find any
matches record from the right side table, then returns null.
In other words, the Left Join clause returns all the rows from the left table and matched records from the right table or returns
Null if no matching record found. This Join can also be called a Left Outer Join clause. So, Outer is the optional keyword to use
We can understand it with the following visual representation where Left Joins returns all records from the left-hand table and
The following syntax explains the Left Join clause to join the two or more tables:
SELECT columns
FROM table1
ON Join_Condition;
In the above syntax, table1 is the left-hand table, and table2 is the right-hand table. This clause returns all records from table1
and matched records from table2 based on the specified join condition.
Let us take some examples to understand the working of Left Join or Left Outer Join clause:
Here, we are going to create two tables "customers" and "orders" that contains the following data:
Table: customers
Table: orders
FROM customers
After successful execution of the query, it will give the following output:
The table customers and orders have the same column name, which is customer_id. In that case, MySQL Left Join can also be
used with the USING clause to access the records. The following statement returns customer id, customer name, occupation,
price, and date using the Left Join clause with the USING keyword.
The Left Join can also be used with the GROUP BY clause. The following statement returns customer id, customer name, qualific-
ation, price, and date using the Left Join clause with the GROUP BY clause.
FROM customers
GROUP BY price;
The WHERE clause is used to return the filter result from the table. The following example illustrates this with the Left Join
clause:
FROM customers
We have already created two tables named "customers" and "orders". Let us create one more table and name it as "con-
Execute the following statement to join the three table customers, orders, and contacts:
FROM customers
After successful execution of the above query, it will give the following output:
The LEFT JOIN clause is also useful in such a case when we want to get records in the table that does not contain any matching
We can understand it with the following example that uses the LEFT JOIN clause to find a customer who has no cellphone num-
ber:
FROM customers
In the LEFT Join, the condition WHERE and ON gives a different result. We can see the following queries to understand their dif-
ferences:
WHERE Clause
FROM customers
ON Clause
NOTE: The WHERE and ON condition in the Inner Join clause always returns equivalent results.
The Right Join is used to joins two or more tables and returns all rows from the right-hand table, and only those results from the
other table that fulfilled the join condition. If it finds unmatched records from the left side table, it returns Null value. It is similar
to the Left Join, except it gives the reverse result of the join tables. It is also known as Right Outer Join. So, Outer is the optional
We can understand it with the following visual representation where Right Outer Join returns all records from the left-hand table
The following are the syntax of Right Join that joins tables Table1 and Table2:
SELECT column_list
FROM Table1
ON join_condition;
NOTE: In the Right Join, if the tables contain the same column name, then ON and USING clause give the equivalent results.
This Join starts selecting the columns from the right-hand table and matches each record of this table form the left table. If both
records fulfil the given join condition, it combines all columns in a new row set that will be returned as output. If the rows of the
right-side table do not find any matching rows form the left table, it combines those rows from the right-side table with Null val-
ues. It means, the Right Join returns all data from the right-side table weather it matches the rows form the left table or not.
Let us take some examples to understand the working of Right Join clause:
Here, we are going to create two tables "customers" and "orders" that contains the following data:
Table: customers
Table: orders
To select records from both tables using RIGHT JOIN, execute the following query:
FROM customers
ORDER BY customer_id;
OR,
FROM customers
ORDER BY customer_id;
After successful execution of the above queries, it will give the equivalent output:
MySQL uses the WHERE clause to provide the filter result from the table. The following example illustrates this
with the Right Join clause:
We have already created two tables, named "customers" and "orders". Let us create one more table and name it as a "con-
Execute the following statement to join the three table customers, orders, and contacts:
FROM customers
After successful execution of the above query, it will give the following output:
The Right Join clause is also useful in such a case when we want to get records in the table that does not contain any matching
We can understand it with the following example that uses the RIGHT JOIN clause to find a customer who has no cell-
phone number:
FROM customers
ORDER BY cellphone;
A unique key in MySQL is a single field or combination of fields that ensure all values going to store into the column will be
unique. It means a column cannot stores duplicate values. For example, the email addresses and roll numbers of students in
the "student_info" table or contact number of employees in the "Employee" table should be unique.
MySQL allows us to use more than one column with UNIQUE constraint in a table. It can accept a null value, but MySQL allowed
only one null value per column. It ensures the integrity of the column or group of columns to store different values into a table.
o It is useful in preventing the two records from storing identical values into the column.
o It stores only distinct values that maintain the integrity and reliability of the database for accessing the information in
an organized way.
Syntax
If we want to create only one unique key column into a table, use the syntax as below:
col1 datatype,
...
);
If we want to create more than one unique key column into a table, use the syntax as below:
col1 col_definition,
col2 col_definition,
...
[CONSTRAINT constraint_name]
UNIQUE(column_name(s))
);
If we have not specified the name for a unique constraint, MySQL generates a name for this column automatically. So, it is re -
Parameter Explanation
Name varchar(45),
Email varchar(45),
Age int,
City varchar(25)
);
Next, execute the insert queries listed below to understand how it works:
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 '1' for key Stud_ID.
If you want to define the unique key on multiple columns, use the query as below:
Stud_ID int,
Roll_No int,
Email varchar(45),
Age int,
City varchar(25),
);
In the output, we can see that the unique key value contains two columns that are Roll_No and Email.
Here, we can see that the unique constraint has successfully added into the table:
DROP Unique Key
The ALTER TABLE statement also allows us to drop the unique key from the table. The following syntax is used to drop the
unique key:
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
Example
This statement will remove the uc_rollno_email constraint from the table permanently.
This statement allows us to do the modification into the existing table. Sometimes we want to add a unique key to the column of
an existing table; then, this statement is used to add the unique key for that column.
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.
Stud_ID int,
Roll_No int,
Email varchar(45),
Age int,
City varchar(25)
);
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 con-
tain 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.
4. MySQL does not allow us to insert a new row with the existing primary key.
5. It is recommended to use INT or BIGINT data type for the primary key column.
History of Java
In this section, we are going to see how a primary key is created using the CREATE TABLE statement.
Syntax
The following are the syntax used to create a primary key in MySQL.
If we want to create only one primary key column into the table, use the below syntax:
col2 datatype,
...
);
If we want to create more than one primary key column into the table, use the below syntax:
col1 col_definition,
col2 col_definition,
...
CONSTRAINT [constraint_name]
);
Parameter Explanation
This statement creates a table named "Login" whose "login_id" column contains the primary key:
username VARCHAR(40),
password VARCHAR(55),
email VARCHAR(55)
);
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:
Student_ID int,
Roll_No int,
Age int,
City varchar(25),
);
In the output, we can see that the primary key value contains two columns that are Student_ID and Roll_No.
This statement allows us to do the modification into the existing table. When the table does not have a primary key, this state -
ment 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.
Name varchar(45),
Age int,
City varchar(25)
);
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
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 is used to It also determines each row of the table uniquely
2. It does not allow to store a NULL value into the primary It can accept only one NULL value into the
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 is also known as the referencing key. A foreign key
matches the primary key field of another table. 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.
A foreign key makes it possible to create a parent-child relationship with the tables. In this relationship, the parent table holds
the initial column values, and column values of child table reference the parent column values. MySQL allows us to define a for -
Syntax
Following are the basic syntax used for defining a foreign key using CRE-
ATE TABLE OR ALTER TABLE statement in the MySQL:
[CONSTRAINT constraint_name]
ON DELETE referenceOption
ON UPDATE referenceOption
col_name: It is the names of the column that we are going to make foreign key.
parent_tbl_name: It specifies the name of a parent table followed by column names that reference the foreign key
columns.
Refrence_option: It is used to ensure how foreign key maintains referential integrity using ON DELETE and ON UP-
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
SET NULL: It is used when we delete or update any row from the parent table, the values of the foreign key columns
RESTRICT: It is used when we delete or update any row from the parent table that has a matching row in the refer -
ence(child) table, MySQL does not allow to delete or update rows in the parent table.
NO ACTION: It is similar to RESTRICT. But it has one difference that it checks referential integrity after trying to
SET DEFAULT: The MySQL parser recognizes this action. However, the InnoDB and NDB tables both rejected this ac-
tion.
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.
Let us understand how foreign key works in MySQL. So first, we are going to create a database named " mysqltestdb" and start
Next, we need to create two tables named "customer" and "contact" using the below statement:
Table: customer
);
Table: contact
ID INT,
Customer_Id INT,
REFERENCES customer(ID)
ON DELETE CASCADE
ON UPDATE CASCADE
);
Here, we are going to see how our database structure looks like using the following queries:
value. Next, the MUL in the key column of the contact value tells that the Customer_Id field can store multiple rows with the
same value.
Now, we have to insert the records into both tables. Execute this statement to insert data into table customer:
('Joseph', 'California'),
('Mary', 'NewYork'),
('John', 'Alaska');
After insertion, execute the SELECT TABLE command to check the customer table data as below:
Execute the below insert statement to add data into a table contact:
Now, let's see how foreign keys in MySQL preserve data integrity.
So here, we are going to delete the referential data that removes records from both tables. We have defined the foreign key in
ON DELETE CASCADE
ON UPDATE CASCADE.
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
Now, test the ON UPDATE CASCADE. Here, we are going to update the Customer_Id of Mary in the contact table as:
Again, if we look at our tables, we can see that both tables were changed with Customer_Id of Mary=3.
Foreign Key example using SET NULL action
Here, we are going to understand how the SET NULL action works with a foreign key. First, we have to create two table
Table: Persons
);
Table: Customers
ID INT,
Person_Id INT,
REFERENCES Persons(ID)
Next, we need to insert the data into both tables using the following statement:
('Joseph', 'Texas'),
('Mary', 'Arizona'),
('Peter', 'Alaska');
Finally, verify the update using the SELECT statement given below:
If we look at our tables, we can see that both tables were changed. The rows with a Person_Id=3 in the Contacts table auto-
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:
ON DELETE referenceOption
ON UPDATE referenceOption
When we add a foreign key using the ALTER TABLE statement, it is recommended to first create an index on the column(s),
Example
The following statement creates two tables, "Person" and "Contact", without having a foreign key column into the table defini-
tion.
Table: Person
);
Table: Contact
ID INT,
Person_Id INT,
);
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:
MySQL has a special variable foreign_key_cheks to control the foreign key checking into the tables. By default, it is enabled to
enforce the referential integrity during the normal operation on the tables. This variable is dynamic in nature so that it supports
Sometimes there is a need for disabling the foreign key checking, which is very useful when:
o We drop a table that is a reference by the foreign key.
o We import data from a CSV file into a table. It speeds up the import operation.
o We use ALTER TABLE statement on that table which has a foreign key.
o We can execute load data operation into a table in any order to avoid foreign key checking.
SET foreign_key_checks = 0;
SET foreign_key_checks = 1;
A composite key in MySQL is a combination of two or more than two columns in a table that allows us to identify each row of the
table uniquely. It is a type of candidate key which is formed by more than one column. MySQL guaranteed the uniqueness of
the column only when they are combined. If they have taken individually, the uniqueness cannot maintain.
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
5.4M144
C++ vs Java
Here, we are going to understand how composite key works in MySQL. Let us first create a table "Product", using the following
statement:
Name varchar(45),
Manufacturer varchar(45),
);
In the above statement, we have created a composite primary with the column names Name and Manufacturer.
We can verify the same using the command as below:
1. DESCRIBE Product;
After the successful execution, we can see that the Key column has two PRI. It means we have successfully added the compos-
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:
If we execute the 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.
ALTER statement always used to do the modification into the existing table. Sometimes it is required to add the composite key
to uniquely identify each record of the table with more than one attribute. In that case, we use an ALTER TABLE
statement.
stud_code varchar(15),
stud_name varchar(35),
subject varchar(25),
marks int
);
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:
DESCRIBE Student;
In the output, we can see that the key column has PRI, which means we have successfully added the composite primary key
is invoked automatically in response to an event. Each trigger is associated with a table, which is activated on any DML
A trigger is called a special procedure because it cannot be called directly like a stored procedure. The main difference between
the trigger and procedure is that a trigger is called automatically when a data modification event is made against a table. In con-
Generally, triggers are of two types according to the SQL standard: row-level triggers and statement-level triggers.
Row-Level Trigger: It is a trigger, which is activated for each row by a triggering statement such as insert, update, or delete.
For example, if a table has inserted, updated, or deleted multiple rows, the row trigger is fired automatically for each row af-
Statement-Level Trigger: It is a trigger, which is fired once for each event that occurs on a table regardless of how many rows
are inserted, updated, or deleted.
NOTE: We should know that MySQL doesn't support statement-level triggers. It provides supports for row-level triggers only.
o Triggers help us to validate data even before they are inserted or updated.
o Triggers help us to keep a log of records like maintaining audit trails in tables.
cuted.
o Triggers reduce the client-side code that saves time and effort.
o MySQL triggers do not allow to use of all validations; they only provide extended validations. For example, we can
use the NOT NULL, UNIQUE, CHECK and FOREIGN KEY constraints for simple validations.
o Triggers are invoked and executed invisibly from the client application. Therefore, it isn't easy to troubleshoot what
We can define the maximum six types of actions or events in the form of triggers:
1. Before Insert: It is activated before the insertion of data into the table.
2. After Insert: It is activated after the insertion of data into the table.
4. After Update: It is activated after the update of the data in the table.
5. Before Delete: It is activated before the data is removed from the table.
6. After Delete: It is activated after the deletion of data from the table.
When we use a statement that does not use INSERT, UPDATE or DELETE query to change the data in a table, the triggers associ-
ated with the trigger will not be invoked.
Naming Conventions
Naming conventions are the set of rules that we follow to give appropriate unique names. It saves our time to keep the work or -
ganize and understandable. Therefore, we must use a unique name for each trigger associated with a table. However, it
is a good practice to have the same trigger name defined for different tables.
The following naming convention should be used to name the trigger in MySQL:
Thus,
We can use the CREATE TRIGGER statement for creating a new trigger in MySQL. Below is the syntax of creating a trigger in
MySQL:
BEGIN
--variable declarations
--trigger code
END;
In this article, we are going to learn how to create the first trigger in MySQL. We can create a new trigger in MySQL by using the
CREATE TRIGGER statement. It is to ensure that we have trigger privileges while using the CREATE TRIGGER command. The fol -
BEGIN
--variable declarations
--trigger code
END;
Parameter Explanation
trigger_name: It is the name of the trigger that we want to create. It must be written after the CREATE TRIGGER
statement. It is to make sure that the trigger name should be unique within the schema.
trigger_time: It is the trigger action time, which should be either BEFORE or AFTER. It is the required parameter while defining
a trigger. It indicates that the trigger will be invoked before or after each row modification occurs on the table.
LETE operation. The trigger can invoke only one event at one time. If we want to define a trigger which is invoked by multiple
events, it is required to define multiple triggers, and one for each event.
table_name: It is the name of the table to which the trigger is associated. It must be written after the ON keyword. If we did not
BEGIN END Block: Finally, we will specify the statement for execution when the trigger is activated. If we want to execute mul-
tiple statements, we will use the BEGIN END block that contains a set of queries to define the logic for the trigger.
The trigger body can access the column's values, which are affected by the DML statement. The NEW and OLD modifiers are
used to distinguish the column values BEFORE and AFTER the execution of the DML statement. We can use the column name
with NEW and OLD modifiers as OLD.col_name and NEW.col_name. The OLD.column_name indicates the column of an exist-
ing row before the updation or deletion occurs. NEW.col_name indicates the column of a new row that will be inserted or an ex -
For example, suppose we want to update the column name message_info using the trigger. In the trigger body, we can ac-
cess the column value before the update as OLD.message_info and the new value NEW.message_info.
We can understand the availability of OLD and NEW modifiers with the below table:
INSERT No Yes
ELETE Yes No
Let us start creating a trigger in MySQL that makes modifications in the employee table. First, we will create a new table
named employee by executing the below statement:
working_date date,
working_hours varchar(10)
);
Next, execute the below statement to fill the records into the employee table:
mysql> DELIMITER //
BEGIN
END IF;
END //
After execution of the above statement, we will get the output as follows:
In this output, we can see that on inserting the negative values into the working_hours column of the table will automatically fill
The show or list trigger is much needed when we have many databases that contain various tables. Sometimes we have the
same trigger names in many databases; this query plays an important role in that case. We can get the trigger information in
the database server using the below statement. This statement returns all triggers in all databases:
The following steps are necessary to get the list of all triggers:
MySQL Command prompt and logged into the database server using the password that you have created
Step 1: Open the
during MySQL's installation. After a successful connection, we 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 "mysqltestdb" that contains many
2. mysql>SHOW TRIGGERS;
lows us to use the FROM or IN clause, followed by the database name. The following statement explains it more clearly:
When we execute the above statements, we will get the same result.
MySQL also provides a LIKE clause option that enables us to filter the trigger name using different pattern matching. The follow -
ing is the syntax to use pattern matching with show trigger command:
OR,
If we want to list/show trigger names based on specific search condition, we can use the WHERE clause as follows:
OR,
Suppose we want to show all triggers that belongs to the employee table, execute the statement as follows:
NOTE: It is to note that we must have a SUPER privilege to execute the SHOW TRIGGERS statement.
The show trigger statement contains several columns in the result set. Let us explain each column in detail.
o Trigger: It is the name of the trigger that we want to create and must be unique within the schema.
o Event: It is the type of operation name that invokes the trigger. It can be either INSERT, UPDATE, or DELETE opera -
tion.
o Statement: It is the body of the trigger that contains logic for the trigger when it activates.
o Timing: It is the activation time of the trigger, either BEFORE or AFTER. It indicates that the trigger will be invoked be-
o Created: It represents the time and date when the trigger is created.
o Definer: It is the name of a user account that created the trigger and should be in the 'user_name'@'host_name' for -
mat.
o character_set_client: It was the session value of the character_set_client system variable when the trigger was cre-
ated.
o collation_connection: It was the session value of the character_set_client system variable when the trigger was cre -
ated.
o Database Collation: It determines the rules that compare and order the character string. It is the collation of the
It is a visual GUI tool used to create databases, tables, indexes, views, and stored procedures quickly and efficiently. To show a
trigger using this tool, we first need to launch the MySQL Workbench and log in using the username and password that we have
1. Go to the Navigation tab and click on the Schema menu that contains all the databases available in the MySQL server.
2. Select the database (for example, mysqltestdb), double click on it, and show the sub-menu containing Tables, Views, Func-
3. Click on the Tables sub-menu and select the table on which you have created a trigger. See the below image:
4. Clicking on the Triggers sub-menu, we can see all triggers associated with the selected table. See the below image.
We can drop/delete/remove a trigger in MySQL using the DROP TRIGGER statement. You must be very careful while removing a
trigger from the table. Because once we have deleted the trigger, it cannot be recovered. If a trigger is not found, the DROP
2. MySQL Workbench
We can drop an existing trigger from the database by using the DROP TRIGGER statement with the below syntax:
Parameter Explanation
The parameters used in the drop trigger syntax are explained as follows: 2.4M
65
Parameter Descriptions
Trigger_name It is the name of a trigger that we want to remove from the database server. It is a required
parameter.
Schema_name It is the database name to which the trigger belongs. If we skip this parameter, the statement
IF_EXISTS It is an optional parameter that conditionally removes triggers only if they exist on the
database server.
If we remove the trigger that does not exist, we will get an error. However, if we have specified the IF EXISTS
It is to note that we must have TRIGGER privileges before executing the DROP TRIGGER statement for the table associated with
the trigger. Also, removing a table will automatically delete all triggers associated with the table.
Let us see how we can drop the trigger associated with the table through an example. So first, we will display all trig-
After executing the statement, we can see that there are two triggers named before_update_salaries and sales_info_be-
It will successfully delete a trigger from the database. If we execute the above statement again, it will return an error message.
If we execute the above statement again with an IF EXISTS clause, it will return the warning message instead of producing an
We can execute the SHOW WARNING statement that generates a NOTE for a non-existent trigger when using IF EXISTS. See
the output:
To create an AFTER UPDATE trigger in workbench, we first launch the MySQL Workbench and log in using the
username and password. We will get the UI as follows:
Now do the following steps to delete or destroy a trigger associated with the table:
1. Go to the Navigation tab and click on the Schema menu. It will display all databases available in the MySQL database
server.
2. Select the database (for example, mystudentdb). Then, double click on the selected schema. It displays the sub-menu con-
taining Tables, Views, Functions, and Stored Procedures. See the below screen.
3. Expand the Tables sub-menu and select a table on which a trigger is associated. Again expand the selected Table -> Trig-
5. Now, click on the Trigger tab shown in the previous section's red rectangular box. You will notice that there is a (+)
and (-) icon button to add or delete a trigger:
6. Now, clicking on the (-) button will permanently remove the trigger associated with the table.
Before Insert Trigger in MySQL is invoked automatically whenever an insert operation is executed. In this article, we are going to
learn how to create a before insert trigger with its syntax and example.
Syntax
BEFORE INSERT
Trigger_body ;
o First, we will specify the name of the trigger that we want to create. It should be unique within the schema.
o Second, we will specify the trigger action time, which should be BEFORE INSERT. This trigger will be invoked before
o Third, we will specify the name of a table to which the trigger is associated. It must be written after the ON keyword.
If we did not specify the table name, a trigger would not exist.
o Finally, we will specify the statement for execution when the trigger is activated.
If we want to execute multiple statements, we will use the BEGIN END block that contains a set of queries to define the logic for
History of Java
DELIMITER $$
BEGIN
variable declarations
trigger code
END$$
DELIMITER ;
Restrictions
o We can access and change the NEW values only in a BEFORE INSERT trigger.
o We cannot access the OLD If we try to access the OLD values, we will get an error because OLD values do not exist.
Let us understand how to create a BEFORE INSERT trigger using the CREATE TRIGGER state-
ment in MySQL with an example.
working_date date,
working_hours varchar(10)
);
Next, we will insert some records into the employee table and then execute the SELECT statement to see the table
data as follows:
Next, we will use a CREATE TRIGGER statement to create a BEFORE INSERT trigger. This trigger is invoked automatically that
inserts the occupation = 'Leader' if someone tries to insert the occupation = 'Scientist'.
mysql> DELIMITER //
BEGIN
END IF;
END //
After execution of the above statement, we will get the output as follows:
To create a before insert trigger using this tool, we first need to launch the MySQL Workbench and log in using the
username and password we created earlier. We will get the screen as follows:
1. Go to the Navigation tab and click on the Schema menu that contains all the databases available in the MySQL server.
2. Select the database (for example, mysqltestdb), double click on it. It will show the sub-menu containing Tables, Views,
3. Expand the Tables sub-menu and select the table on which you want to create a trigger. After selecting a table, right-click
on the selected table (for example, employee), and then click on the Alter Table option. See the below image:
SERT. We will notice that there is a (+) icon button to add a trigger. Clicking on that button, we will get a default code on the
6. Now, complete the trigger code, review them once again, and no error found, click on the Apply button.
7. After clicking on the Apply button, click on the Finish button for completion.
8. If we take at the schema menu, we will see employee_BEFORE_INSERT trigger under the employee table as follows:
MySQL AFTER INSERT Trigger
After Insert Trigger in MySQL is invoked automatically whenever an insert event occurs on the table. In this article, we are going
to learn how to create an after insert trigger with its syntax and example.
Syntax
AFTER INSERT
trigger_body ;
o First, we will specify the name of the trigger that we want to create. It should be unique within the schema.
o Second, we will specify the trigger action time, which should be AFTER INSERT clause to invoke the trigger.
o Third, we will specify the name of a table to which the trigger is associated. It must be written after the ON keyword.
If we did not specify the table name, a trigger would not exist.
o Finally, we will specify the trigger body that contains one or more statements for execution when the trigger is acti -
vated.
If we want to execute multiple statements, we will use the BEGIN END block that contains a set of SQL queries to define the lo-
DELIMITER $$
variable declarations
trigger code
END$$
DELIMITER ;
Restrictions
o We can access the NEW values but cannot change them in an AFTER INSERT trigger.
o We cannot access the OLD If we try to access the OLD values, we will get an error because there is no OLD on the IN-
SERT trigger.
Let us understand how to create an AFTER INSERT trigger using the CREATE TRIGGER statement
in MySQL with an example.
Next, we will insert some records into this table and then execute the SELECT statement to see the table data as
follows:
Again, we will create a new table named "student_detail" as follows:
Lasinserted Time,
);
Next, we will use a CREATE TRIGGER statement to create an after_insert_details trigger on the student_info table. This trig-
mysql> DELIMITER //
BEGIN
END //
The table that has been modified after the update query executes is student_detail. We can verify it by using the SELECT state -
ment as follows:
In this output, we can see that on inserting values into the student_info table, the student_detail table will automatically fill the
To create an after insert trigger using this tool, we first need to launch the MySQL Workbench and log in using
the username and password that we have created earlier. We will get the screen as follows:
Now do the following steps for creating an AFTER INSERT trigger:
1. Go to the Navigation tab and click on the Schema menu that contains all the databases available in the MySQL server.
2. Select the database (for example, mystudentdb), double click on it that shows the sub-menu containing Tables, Views, Func-
3. Expand the Tables sub-menu and select the table on which you want to create a trigger. After selecting a table, right-click
on the selected table (for example, mystudentdb), and then click on the Alter Table option. See the below image:
4. Clicking on the Alter Table option gives the screen as below:
5. Now, click on the Trigger tab shown in the red rectangular box of the previous section, then select the Timing/Event AFTER
INSERT. We will notice that there is a (+) icon button to add a trigger. Clicking on that button, we will get a default code on the
7. After clicking on the Apply button, click on the Finish button for completion.
8. If we look at the schema menu, we can see AFTER_INSERT_detail trigger under the student_info table as follows:
like the average of all values, the sum of all values, and maximum & minimum value among certain groups of values. We
mostly use the aggregate functions with SELECT statements in the data query languages.
Syntax:
o Second, we use the DISTINCT modifier when we want to calculate the result based on distinct values or ALL modi-
fiers when we calculate all values, including duplicates. The default is ALL.
o Third, we need to specify the expression that involves columns and arithmetic operators.
There are various aggregate functions available in MySQL. Some of the most commonly used aggregate functions are
count() It returns the number of rows, including rows with NULL values in a group.
We mainly use the aggregate functions in databases, spread sheets and many other data manipulation software packages. In
the context of business, different organization levels need different information such as top levels managers interested in know -
ing whole figures and not the individual details. These functions produce the summarised data from our database. Thus they are
extensively used in economics and finance to represent the economic health or stock and sector performance.
Let us take an example of myflix (video streaming website which has huge collections of the movie) database, where manage-
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
working_date date,
working_hours varchar(10)
);
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
Output:
After execution, we can see that this table has six employees.
um() 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
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
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
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.
Suppose we want to get minimum working hours of an employee available in the table, we need to use the MIN() function as
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.
Suppose we want to get maximum working hours of an employee available in the table, we need to use the MAX() function as
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
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 OR-
DER 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:
MySQL count() function is used to returns the count of an expression. It allows us to count all rows or only some rows of the
table that matches a specified condition. It is a type of aggregate function whose return type is BIGINT. This function returns 0 if
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 res-
ult set contains all Non-Null, Null, and duplicates rows.
6.1M
107
COUNT(expression) Function: This function returns the result set without containing Null rows as the result of an expression.
COUNT(distinct expression) Function: This function returns the count of distinct rows without containing NULL values as the
Syntax
FROM table_name
[WHERE conditions];
Parameter explanation
aggregate_expression: It specifies the column or expression whose NON-NULL values will be counted.
table_name: It specifies the tables from where you want to retrieve records. There must be at least one table listed in
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 avail-
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:
We can also use the count() function with the GROUP BY clause that returns the count of the element in each group. For ex-
ample, the following statement returns the number of employee in each city:
Let us see another clause that uses ORDER BY and Having clause with the count() function. Execute the follow-
ing statement that gives the employee name who has at least two age same and sorts them based on the count result:
GROUP BY emp_age
HAVING COUNT(*)>=2
ORDER BY COUNT(*);
The MySQL sum() function is used to return the total summed value of an expression. It returns NULL if the result set does not
Syntax
SELECT SUM(aggregate_expression)
FROM tables
[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.
MySQL sum() function example
Consider our database has a table named employees, having the following data. Now, we are going to understand this function
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.
mysql> SELECT SUM(working_hours) AS "Total working hours" FROM employees WHERE working_hours>=12;
Output:
This statement will give the output as below:
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
mysql> SELECT emp_id, emp_name, occupation, SUM(working_hours) AS "Total working hours" FROM employees GROUP BY o
ccupation;
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 group with the sum() function in MySQL. Execute the following statement that calculates
the working hours of all employees, grouping them based on their occupation and returns the result whose
Total_working_hours>24.
SUM(working_hours) Total_working_hours
FROM employees
GROUP BY occupation
HAVING SUM(working_hours)>24;
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
FROM employees
GROUP BY occupation;
Output:
The MySQL avg() is an aggregate function used to return the average value of an expression in various records.
Syntax
FROM tables
[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.
Consider our database has a table named employees, having the following data. Now, we are going to understand this function
1. Basic Example
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 calcu-
late 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
mysql> SELECT emp_name, occupation, AVG(working_hours) Avg_working_hours 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.
4. MySQL AVG() function with HAVING clause
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_work-
ing_hours>9.
AVG(working_hours) Avg_working_hours
FROM employees
GROUP BY occupation
HAVING AVG(working_hours)>9;
Output:
MySQL uses the DISTINCT keyword to remove the duplicate rows from the column name. This clause is used with this avg()
function to return the average 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 re-
FROM employees
GROUP BY occupation;
Output:
The MIN() function in MySQL is used to return the minimum value in a set of values from the table. It is an aggregate function
that is useful when we need to find the smallest number, selecting the least expensive product, etc.
Syntax
FROM table_name(s)
[WHERE conditions];
Parameter explanation
aggregate_expression: It is the required expression. It specifies the column or expression name from which the minimum
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.
Let us understand how MIN function works in MySQL with the help of various examples. Consider our database has a table
named "employees" that contains the following data.
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:
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
FROM employees
Output
The GROUP BY clause allows us to collect data from multiple rows and group it based on one or more columns. For example, the
following statement uses the MIN() function with the GROUP BY clause to find the minimum income in all rows from the em-
FROM employees
GROUP BY emp_age;
Output
After the successful execution, we can see that the income of each employee returns by grouping them based on their age:
The HAVING clause is always used with the GROUP BY clause to filter the records from the table. For example, the be-
low statement returns the minimum income of all employees, grouping them based on their city and returns the result whose
MIN(income)>150000.
2. FROM employees
3. GROUP BY city
Output
This statement will return the output as below:
MySQL uses the DISTINCT keyword to remove the duplicate rows from the column name. We can also use this clause with
MIN() function to return the minimum income value of a unique number of records present in the table.
Execute the following query that removes the duplicate records in the income column of the employee table, group by city, and
FROM employees
GROUP BY city;
Output
The MySQL MAX() function is used to return the maximum value in a set of values of an expression. This aggregate function is
useful when we need to find the maximum number, selecting the most expensive product, or getting the largest payment to the
FROM table_name(s)
[WHERE conditions];
Parameter Explanation
Aggregate_expression: It is the required expression. It specifies the column, expression, or formula from which the maximum
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 maximum of the distinct values in the expression. However, it does not affect the MAX()
function and produces the same result without using this keyword.
Let us understand how the MAX function works in MySQL with the help of various examples. Consider our database has a
table named "employees" that contains the following data.
1. Basic Example
Execute the following query that uses the MAX function to find the maximum income of the employee available in the table:
Output
The above query produces the result of maximum values in all rows. After execution, we will get the output as below:
The WHERE clause allows us to filter the result from the selected records. The following statement finds the maximum
income in all rows from the employee table. The WHERE clause specifies all those rows whose emp_age column is greater than
35.
FROM employees
Output
The GROUP BY clause allows us to collect data from multiple rows and group it based on one or more columns. For
example, the following statement uses the MAX() function with the GROUP BY clause to find the maximum income in all rows
2. FROM employees
3. GROUP BY emp_age;
Output
After the successful execution, we can see that the maximum income of the employee returns by grouping them based on their
age:
3. MySQL MAX() 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 fol-
lowing statement returns the maximum income among all employees, grouping them based on their city and returns the result
FROM employees
GROUP BY city
Output
MySQL uses the DISTINCT keyword to remove the duplicate rows from the column name. We can also use this clause with
MAX() function to return the maximum income value of a unique number of records present in the table.
Execute the following query that removes the duplicate records in the employee table's income column, group by city, and then
GROUP BY city;
Output
Sometimes it is required to use the subquery for returning the maximum value in the table. In that case, we use the following
query:
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
MYSQL MISC
MySQL Subquery
A subquery in MySQL is a query, which is nested into another SQL query and embedded with SELECT, INSERT, UPDATE or DE -
LETE statement along with the various operators. We can also nest the subquery with another subquery. A subquery is known as
the inner query, and the query that contains subquery is known as the outer query. The inner query executed first gives the
result to the outer query, and then the main/outer query will be performed. MySQL allows us to use subquery anywhere,
but it must be closed within parenthesis. All subquery forms and operations supported by the SQL standard will be supported in
MySQL also.
o If the main query does not have multiple columns for subquery, then a subquery can have only one column in the SE-
LECT command.
o We can use various comparison operators with the subquery, such as >, <, =, IN, ANY, SOME, and ALL. A multiple-row
operator is very useful when the subquery returns more than one row.
o We cannot use the ORDER BY clause in a subquery, although it can be used inside the main query.
o The subqueries make the queries in a structured form that allows us to isolate each part of a statement.
o The subqueries provide alternative ways to query the data from the table; otherwise, we need to use complex joins
and unions.
o The subqueries are more readable than complex join or union statements.
The following is the basic syntax to use the subquery in MySQL: History of Java
Let us understand it with the help of an example. Suppose we have a table named "employees" that contains the following
data:
Table: employees
Following is a simple SQL statement that returns the employee detail whose id matches in a subquery:
A comparison operator is an operator used to compare values and returns the result, either true or false. The following compar -
ison operators are used in MySQL <, >, =, <>, <=>, etc. We can use the subquery before or after the comparison operators
that return a single value. The returned value can be the arithmetic expression or a column function. After that, SQL compares
the subquery results with the value on the other side of the comparison operator. The below example explains it more clearly:
Following is a simple SQL statement that returns the employee detail whose income is more than 350000 with the help
of subquery:
SELECT * FROM employees
This query first executes the subquery that returns the employee id whose income > 350000. Second, the main query will
return the employees all details whose employee id are in the result set returned by the subquery.
After executing the statement, we will get the below output, where we can see the employee detail whose income>350000.
Let us see an example of another comparison operator, such as equality (=) to find employee details with maximum in-
It will give the output where we can see two employees detail who have maximum income.
If the subquery produces more than one value, we need to use the IN or NOT IN operator with the WHERE clause. Sup-
pose we have a table named "Student" and "Student2" that contains the following data:
Table: Student
Table: Student2
The following subquery with NOT IN operator returns the student detail who does not belong to Los Angeles City from
After execution, we can see that the result contains the student details not belonging to Los Angeles City.
If we use a subquery in the FROM clause, MySQL will return the output from a subquery is used as a temporary table. We called
The following subquery returns the maximum, minimum, and average number of items in the order table:
FROM
A correlated subquery in MySQL is a subquery that depends on the outer query. It uses the data from the outer query or con -
tains a reference to a parent query that also appears in the outer query. MySQL evaluates it once from each row in the outer
query.
In the above query, we select an employee name and city whose income is higher than the average income of all employees
in each city.
The subquery executes for every city of the specified table because it will change for every row. Therefore, the average income
will also be changed. Then, the main query filters employee detail whose income is higher than the average income from the
subquery.
The EXISTS operator is a Boolean operator that returns either true or false result. It is used with a subquery and
checks the existence of data in a subquery. If a subquery returns any record at all, this operator returns true. Otherwise, it will
return false. The NOT EXISTS operator used for negation that gives true value when the subquery does not return any row. Oth -
Both EXISTS and NOT EXISTS used with correlated subqueries. The following example illustrates it more clearly. Suppose we
have a table customer and order that contains the data as follows:
The below SQL statements uses EXISTS operator to find the name, occupation, and age of the customer who has placed at least
one order.
This statement uses NOT EXISTS operator that returns the customer details who have not placed an order.
We can see the below output to understand the above queries result.
MySQL ROW Subqueries
It is a subquery that returns a single row where we can get more than one column values. We can use the following operators for
comparing row subqueries =, >, <, >=, <=, <>, !=, <=>. Let us see the following example:
If given row has cust_id, occupation values equal to the order_id, order_date values of any rows in the first table, the WHERE ex -
pression is TRUE, and each query returns those first table rows. Otherwise, the expression is FALSE, and the query produces an
We can use a subquery which is followed by the keyword ALL, ANY, or SOME after a comparison operator. The following are the
for ALL of the values returned by a subquery. The ANY keyword returns TRUE if the comparison is TRUE for ANY of the values re-
turned by a subquery. The ANY and SOME keywords are the same because they are the alias of each other. The following ex -
If we use ALL in place of ANY, it will return TRUE when the comparison is TRUE for ALL values in the column returned by a sub -