0% found this document useful (0 votes)
17 views300 pages

MySQL - Notes (KVS)

Uploaded by

ANIKET LOHKARE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views300 pages

MySQL - Notes (KVS)

Uploaded by

ANIKET LOHKARE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 300

MySQL

(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

supported by Oracle Company.

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.

How to install MySQL

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

how we can download and install MySQL for beginners.

Prerequisites

The following requirements should be available in your system to work with MySQL:

o MySQL Setup Software

o Microsoft .NET Framework 4.5.2

o Microsoft Visual C++ Redistributable for Visual Studio 2019

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-

munity. Otherwise, choose the other one.


Installing MySQL on Windows

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-

ically or can skip them. Now, click on the Next button.


Step 4: In the next wizard, we will see a dialog box that asks for our confirmation of a few products not getting installed. Here,

we have to click on the Yes button.

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,

click on the Execute button.

Step 5: Once we click on the Execute button, it will download and install all the products. After completing the installation, click

on the Next button.


Step 6: In the next wizard, we need to configure the MySQL Server and Router. Here, I am not going to configure the Router

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

choose the InnoDB Cluster based on your needs.


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

the Next button.

Step 12: In the next wizard, the system will ask you to apply the Server Configuration. If you agree with 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

Next-> Finish button to complete the MySQL package installation.


Step 15: In the next wizard, we can choose to configure the Router. So click on Next->Finish and then click the Next button.

Step 16: In the next wizard, we will see the Connect to Server option. Here, we have to mention the root password, which we

had set in the previous steps.

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.

Verify MySQL installation

Once MySQL has been successfully installed, the base tables have been initialized, and the server has been started, you can

verify its working via some simple tests.

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 Connection Types

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 Server Connection Using command-line client

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

MySQL to ask for a password.

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

receive answers in the form of a result set.

Suppose we want to display all databases available in the current server; we can use the command as follows:

1. mysql> SHOW DATABASES;

It will give the below output:

If you want to disconnect the opened MySQL database server, you need to use the exit command.

1. mysql> EXIT;

Connect to Database Server Using MySQL Workbench

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

MySQL Connections. See the below image:

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

connection is successful, click on the OK button.

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

have Localhost3 connection name:


Step 8: Now, we can click this newly created connection that displays the current schemas and a pane for entering queries:

Connect to MySQL Server Using PHP Script

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-

nection is failed, it returns FALSE.

Syntax

The following is the syntax for MySQL connection using PHP Script:

1. connection mysql_connect(server, user, passwordd, new_link, client_flag);


Let us explain the mysql_connect() function parameters:

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

be the name of a user that owns the server process.

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

default value that will be an empty password.

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.

Client_flags: This parameter contains a combination of the below constants:

o MYSQL_CLIENT_SSL: It uses SSL encryption.

o MYSQL_CLIENT_COMPRESS: It uses a compression protocol.

o MYSQL_CLIENT_IGNORE_SPACE: It provides space after function names.

o MYSQL_CLIENT_INTERACTIVE: It provides a timeout before closing the 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:

1. bool mysql_close ( resource $link_identifier );

If we do not specify any resource, MySQL will close the last opened database. This function returns true when the connection is

closed successfully. Otherwise returns a FALSE value.

Example:

The following examples explain how to connect to a MySQL server using PHP Script:

<html>

<head>

<title>MySQL Server Connection</title>

</head>

<body>

<?php

$servername = 'localhost:3306';

$username = 'javatpoint';

$dbpass = 'jtp123';

$conn = mysql_connect($servername, $username, $password);

if(! $conn ) {

die('Connection failed: ' . mysql_error());

echo 'Connection is successful';


mysql_close($conn);

?>

</body>

</html>

MySQL Workbench

(Download and Installation)

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

supports MySQL Server version v5.6 and higher.

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 -

gers, partitioning, etc.

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-

sions of MySQL to the latest releases.

MySQL Enterprise Supports: This functionality gives the support for Enterprise products such as MySQL firewall, MySQL En-

terprise Backup, and MySQL Audit.

MySQL Workbench Editions

MySQL Workbench is mainly available in three editions, which are given below:

1. Community Edition (Open Source, GPL)

2. Standard Edition (Commercial)

3. Enterprise Edition (Commercial)


Community Edition

The Community Edition is an open-source and freely downloadable version of the most popular database system. It came under

the GPL license and is supported by a huge community of developers.

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-

ployment, and managing MySQL applications.

Let us understand it with the following comparison chart:


MySQL Workbench Environment Setup

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 MySQL Server: You can download it from here.


o MySQL Workbench: You can download it from here.
o Microsoft .NET Framework 4.5.2

o Microsoft Visual C++ Redistributable for Visual Studio 2019

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

the .exe file, you can see the following screen:

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

to the right side box by clicking on the right arrow symbol.


Now, in the Application section, you need to do the same thing that you had to perform with MySQL Server and click on the

Next button. The following screen explains it more clearly.

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.

When the downloading and installation is complete, click on Next button.


Step 6: In the next screen, we need to configure the MySQL Server and click on 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.
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.

Step 9: Now, select the Authentication Method and click on Next.


Step 10: The next screen will ask you to choose the account, username, and password. After filling all the details, click on the

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

Next-> Finish button to complete the MySQL package installation.


Step 15: Once you click the Finish button, the MySQL Workbench should be open on your system, as shown in the screen

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

password, you are able to connect with the Server.

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.

Database backup and restorations

It is a visual tool, which is used for importing/exporting MySQL dump files. The dump files contain SQL scripts for creating data -

bases, tables, views, and stored procedures.

Server Logs

It displays log information for the MySQL Server by each connection tab. For each connection tab, it includes an additional tab

for the general error logs.

Performance Dashboard

This tab provides the statistical view of the Server performance. You can open it by navigating to the Navigation tab, and under

the Performance section, choose Dashboard.


MySQL Workbench Create, Alter, Drop Database

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

detail one by one.

Create Database

To create a database, do the following steps:

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

icon (red rectangle), as shown in the following screen.

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

shown in the screen below:


4. A new popup window appears, click Apply->Finish button to create a new database.

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

on the refresh icon into the Schema menu.

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

and data rows from the database.

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.

MySQL Workbench Create, Alter, Drop Table

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

To create a table, do the following steps:

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

in red rectangle) to create a table.

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 -

ample, student) and use default collation and engine.

5. Click inside the middle window and fill the column details. Here, the column name contains many attributes such as Primary

Key(PK), Not Null (NN), Unique Index (UI), Binary(B), Unsigned Data type(UN), Auto Incremental (AI), etc. The following screen

explains it more clearly. After filling all the details, click on the Apply button.
6. As soon as you click on the Apply button, it will open the SQL statement window. Again, click on the Apply button to execute

the statement and Finish button to save the changes.

7. Now, go to the Schema menu and select the database which contains the newly created table, as shown in the screen below.

Alter Table

To alter a table, do the following steps:

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.

MySQL Workbench Insert, Read, Update, Delete Data Rows

In this section, we are going to see how we can insert, read, update, and delete data rows by using the MySQL Workbench. Let

us see in detail one by one.

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

Microsoft Excel Worksheet.

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

select Delete Row(s) option.

2. Now, click Apply->Apply->Finish button to save changes to the database.

MySQL Workbench Export and Import Database(Table)

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

left section of the window.

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-

dio buttons that are explained below.

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-

ate the export files.

Import Databases (Tables)

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-

dow of data import settings and options.

2. Here, you can see the two radio options to import databases and tables, which are:

o Import from Dump Project Folder

o Import by using Self-Contained File

3. We are going to select 'Import from Dump Project Folder' and click on 'Load Folder Content' to display all the available data -

bases in the project folder.

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.

MySQL Show Users/List All Users

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:

1. mysql> Select user from mysql.user;

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:

> mysql -u root -p

Enter password: *********

mysql> use mysql;

Database changed

mysql> SELECT user FROM user;

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:

1. mysql> DESC user;

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:

1. mysql> SELECT user, host, account_locked, password_expired FROM user;

After the successful execution, it will give the following output:


Show Current User

We can get information of the current user by using the user() or current_user() function, as shown below:

mysql> Select user();

or,

mysql> Select current_user();

After executing the above command, we will get the following output:

Show Current Logged User

We can see the currently logged user in the database server by using the following query in the MySQL server:

1. mysql> SELECT user, host, db, command FROM information_schema.processlist;

The above command gives the output, as shown below:


In this output, we can see that there are currently four users logged in the database, where one is executing a Query, and

others show in Sleep or Daemon status.

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:

1. MySQL Command Line Client

2. MySQL Workbench

MySQL Command Line Client

We can create a new database in MySQL by using the CREATE DATABASE statement with the below syntax:

CREATE DATABASE [IF NOT EXISTS] database_name

[CHARACTER SET charset_name]

[COLLATE collation_name];

Parameter Explanation

The parameter descriptions of the above syntax are as follows:

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,

MySQL takes the default character set.

collation_name It is optional that compares characters in a particular character set.

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

name "employeedb" using the following statement:

mysql> CREATE DATABASE employeesdb;


It will look like the below output:

We can review the newly created database using the below query that returns the database name, character set, and collation

of the database:

mysql> SHOW CREATE DATABASE employeedb;

We can check the created database using the following query:

1. mysql> SHOW DATABASES;

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.

mysql> USE emplyeedb;

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.

MySQL SELECT Database

SELECT Database is used in MySQL to select a particular database to work with. This query is used when multiple databases are

available with MySQL Server.

You can use SQL command USE to select a particular database.

Syntax:

USE database_name;

Example:

Let's take an example to use a database name "customers".

USE customers;

It will look like this:


Note: All the database names, table names and table fields name are case sensitive. You must have to use proper names while giving any SQL
command.

MySQL Show/List Databases

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:

mysql> SHOW DATABASES;

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.

We can see the following output that explains it more clearly:


MySQL also allows us another command to list the databases, which is a SHOW SCHEMAS statement. This command is the

synonyms of the SHOW DATABASES and gives the same result. We can understand it with the following output:

List Databases Using Pattern Matching

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:

mysql> SHOW DATABASES LIKE pattern;

OR,

mysql> SHOW DATABASES WHERE expression;

We can understand it with the example given below where percent (%) sign assumes zero, one, or multiple characters:

mysql> SHOW DATABASES LIKE "%schema";

The above statement will give the following output:


Sometimes the LIKE clause is not sufficient; then, we can make a more complex search to query the database information from

the schemata table in the information schema. The information schema in MySQL is an information database so that we can use

it to get the output using the SHOW DATABASES command.

1. mysql> SELECT schema_name FROM information_schema.schemata;

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

database whose schema name starts with "s":

1. mysql>SELECT schema_name FROM information_schema.schemata WHERE schema_name LIKE 's%';

It will give the following output:

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.

MySQL Drop User

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.

DROP USER 'account_name';

The account_name can be identified with the following syntax:

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

server name of the user account.

MySQL Drop USER Example

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.

Enter Password: ********

Step 3: Execute the following command to show all users in the current MySQL server.

mysql> select user from mysql.user;

We will get the output as below:

Step 4: To drop a user account, you need to execute the following statement.

DROP USER martin@localhost;

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.

1. DROP USER john@localhost, peter@localhost;

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.

TABLE AND VIEWS


MySQL CREATE TABLE

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 Name of the table

o Names of fields

o Definitions for each field

MySQL allows us to create a table into the database mainly in two ways:

1. MySQL Command Line Client

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.

CREATE TABLE [IF NOT EXISTS] table_name(

column_definition1,

column_definition2,

........,

table_constraints

);

Parameter Explanation

The parameter descriptions of the above syntax are as follows:

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

selected database that already exists.

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:

column_name1 data_type(size) [NULL | NOT NULL]

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:

mysql> CREATE TABLE employee_table(

id int NOT NULL AUTO_INCREMENT,

name varchar(45) NOT NULL,

occupation varchar(35) NOT NULL,

age int NOT NULL,

PRIMARY KEY (id)

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

Visual representation of creating a MySQL table:

We need to use the following command to see the newly created table:

mysql> SHOW TABLES;

It will look like the below output:

See the table structure:

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:

Now do the following steps for table creation:

1. Go to the Navigation tab and click on the Schema menu. Here, we can see all the previously created databases. Now we are

ready to select the database in which a table is created.

2. Select the database, double click on it, and we will get the sub-menu under the database. These sub-menus are Tables,

Views, Functions, and Stored Procedures, as shown in the below screen.


3. Select Tables sub-menu, right-click on it, and select Create Table option. We can also click on create a new table icon

(shown in red rectangle) to create a table.

4. On the new table screen, we need to fill all the details to create a table. Here, we will enter the table name (for example,

employee_table) and use default collation and engine.

5. Click inside the middle window and fill the column details. Here, the column name contains many attributes such as Primary

Key(PK), Not Null (NN), Unique Index (UI), Binary(B), Unsigned Data type(UN), Auto Incremental (AI), etc. The following screen

explains it more clearly. After filling all the details, click on the Apply button.

6. As soon as you click on the Apply button, it will open the SQL statement window. Again, click on the Apply button to execute

the statement and Finish button to save the changes.


7. Now, go to the Schema menu and select the database which contains the newly created table, as shown in

the screen below.

MySQL ALTER Table

MySQL ALTER statement is used when you want to change the name of your table or any table field. It is also used to add or de -

lete an existing column in a table.

The ALTER statement is always used with "ADD", "DROP" and "MODIFY" commands according to the situation.

1) ADD a column in the table

Syntax:

1. ALTER TABLE table_name

2. ADD new_column_name column_definition

3. [ FIRST | AFTER column_name ];


Parameters

table_name: It specifies the name of the table that you want to modify.

new_column_name: It specifies the name of the new column that you want to add to the table.

column_definition: It specifies the data type and definition of the column (NULL or NOT NULL, etc).

FIRST | AFTER column_name: It is optional. It tells MySQL where in the table to create the column. If this parameter is not

specified, the new column will be added to the end of the table.

Example:

In this example, we add a new column "cus_age" in the existing table "cus_tbl".

Use the following query to do this:

ALTER TABLE cus_tbl

ADD cus_age varchar(40) NOT NULL;

Output:

See the recently added column:

SELECT* FROM cus_tbl;


Output:

2) Add multiple columns in the table

Syntax:

ALTER TABLE table_name

ADD new_column_name column_definition

[ FIRST | AFTER column_name ],

ADD new_column_name column_definition

[ FIRST | AFTER column_name ],

...

Example:

In this example, we add two new columns "cus_address", and cus_salary in the existing table "cus_tbl". cus_address is added

after cus_surname column and cus_salary is added after cus_age column.

Use the following query to do this:

ALTER TABLE cus_tbl

ADD cus_address varchar(100) NOT NULL

AFTER cus_surname,

ADD cus_salary int(100) NOT NULL

AFTER cus_age ;
See the recently added columns:

SELECT* FROM cus_tbl;

3) MODIFY column in the table

The MODIFY command is used to change the column definition of the table.

Syntax:

ALTER TABLE table_name

MODIFY column_name column_definition

[ FIRST | AFTER column_name ];

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:

See the table structure:

4) DROP column in table

Syntax:

ALTER TABLE table_name

DROP COLUMN column_name;

Let's take an example to drop the column name "cus_address" from the table "cus_tbl".

Use the following query to do this:


ALTER TABLE cus_tbl

DROP COLUMN cus_address;

Output:

See the table structure:

5) RENAME column in table

Syntax:

ALTER TABLE table_name

CHANGE COLUMN old_name new_name

column_definition
[ FIRST | AFTER column_name ]

Example:

In this example, we will change the column name "cus_surname" to "cus_title".

Use the following query to do this:

ALTER TABLE cus_tbl

CHANGE COLUMN cus_surname cus_title

varchar(20) NOT NULL;

Output:

6) RENAME table

Syntax:

ALTER TABLE table_name

RENAME TO new_table_name;

Example:

In this example, the table name cus_tbl is renamed as cus_table.

ALTER TABLE cus_tbl

RENAME TO cus_table;
Output:

See the renamed table:

MySQL Show/List Tables

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-

base using the following statement:

1. mysql> SHOW TABLES;

The following steps are necessary to get the list of tables:

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:

mysql> USE database_name;

Step 3: Finally, execute the SHOW TABLES command.

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> USE mystudentdb;

mysql>SHOW TABLES;

The following output explains it more clearly:

We can also use the FULL modifier with the SHOW TABLES query to get the type of table (Base or View) that appears in a

second output column.

mysql> SHOW FULL TABLES;

This statement will give the following output:

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;

The above statement can also be written as:

mysql> SHOW TABLES FROM database_name;

When we execute the below statements, we will get the same result:

mysql> SHOW TABLES FROM mystudentdb;

OR,

mysql> SHOW TABLES IN mystudentdb;

Output:

Show Tables Using Pattern Matching

Show Tables command in MySQL also provides an option that allows us to filter the returned table using different pattern

matching with LIKE and WHERE clause.

Syntax

The following are the syntax to use pattern matching with show table command:

mysql> SHOW TABLES LIKE pattern;

OR,

mysql> SHOW TABLES WHERE expression;

We can understand it with the example given below where percent (%) sign assumes zero, one, or multiple characters:

mysql> SHOW TABLES FROM mystudentdb LIKE "stud%";


The above statement will give the following output:

Let us see another statement that returned the table names starting with "time":

1. mysql> SHOW TABLES IN mysql LIKE "time%";

The above query will give the following output:

Now, we are going to see how we can use the WHERE clause with the SHOW TABLES command to list different types of tables

(either Base or View type) in the selected database:

1. mysql> SHOW TABLES FROM sakila WHERE table_type= "VIEW";

This statement gives the below output:


It is noted that if MySQL does not provide the privileges for accessing a Base table or view, then we cannot get the tables in the

result set of the SHOW TABLES command.

Here, we can also see another example of Show Tables statement with the WHERE clause:

1. mysql> SHOW TABLES In mystudentdb WHERE Tables_in_mystudentdb= "employees";

It will give the following output:

MySQL Rename Table

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:

1. mysql> RENAME old_table TO new_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

before executing this statement.

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:

RENAME TABLE old_tab1 TO new_tab1,

old_tab2 TO new_tab2, old_tab3 TO new_tab3;

From the MySQL 8.0.13 version, we can change the old table name locked with a LOCK statement and also uses the WRITE

LOCK clause. For example, following are the valid statement:


mysql> LOCK TABLE old_tab_name1 WRITE;

RENAME TABLE old_tab_name1 TO new_tab_name1,

new_tab_name1 TO new_tab_name2;

Following statement are not permitted:

mysql> LOCK TABLE old_tab_name1 READ;

RENAME TABLE old_tab_name1 TO new_tab_name1,

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:

mysql> RENAME TABLE current_db.tablel_name TO other_db.tablel_name;

MySQL RENAME TABLE Example

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.

Table Name: employee

Next, execute the following syntax to change the table name:

mysql> RENAME employee TO 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

throw an error message.

How to RENAME Multiple Tables


RENAME TABLE statement in MySQL also allows us to change more than one table name within a single statement. See the be-

low statement:

Suppose our database "myemployeedb" having the following tables:

If we want to change the table name customer into employee and table name shirts into garments, execute the following state-

ment:

mysql> RENAME TABLE customer TO employee, shirts TO garments;

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

of the ALTER TABLE statement:

ALTER TABLE old_table_name RENAME TO new_table_name;

See the following query that changes the existing table name garments into new table name shirts:

mysql> ALTER TABLE garments RENAME TO shirts:

Output

Here, we can see that the table name garments renamed into table name shirts.

How to RENAME Temporary Table

A temporary table allows us to keep temporary data, which is visible and accessible in the current session only. So, first, we

need to create a temporary table using the following statement:

mysql> CREATE TEMPORARY TABLE Students( name VARCHAR(40) NOT NULL, total_marks DECIMAL(12,2) NOT NULL DE-

FAULT 0.00, total_subjects INT UNSIGNED NOT NULL DEFAULT 0);


Next, insert values into this table:

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:

mysql> SELECT * FROM Students;

Now, run the following command to change the name of the temporary table:

mysql> RENAME TABLE Students TO student_info;

It will throw an error message, as shown below:

Thus, MySQL allows ALTER table statement to rename the temporary table:

mysql> ALTER TABLE Students RENAME TO student_info;

Output

MySQL TRUNCATE Table

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

removing the table structure.

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 -

turns the number of deleted rows.


This command does not maintain the transaction log during the execution. It deallocates the data pages instead of rows and

makes an entry for the deallocating pages instead of rows in transaction logs. This command also locks the pages instead of

rows; thus, it requires fewer locks and resources.

The following points must be considered while using the TRUNCATE command:

5M

90

Triggers in SQL (Hindi)

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-

forming this operation.

o We cannot use the truncate statement when a table is referenced by a foreign key or participates in an indexed

view.

o The TRUNCATE command doesn't fire DELETE triggers associated with the table that is being truncated because it

does not operate on individual rows.

Syntax

The following syntax explains the TRUNCATE command to remove data from the table:

1. TRUNCATE [TABLE] table_name;

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.

MySQL Truncate Table Example

Let us demonstrate how we can truncate the table with the help of an example. First, we are going to create a table named

"customer" using the below statement:

CREATE TABLE customer (

Id int PRIMARY KEY NOT NULL,

Name varchar(45) NOT NULL,

Product varchar(45) DEFAULT NULL,

Country varchar(25) DEFAULT NULL,

Year int NOT NULL

);

Next, we will add values to this table using the below statement:

INSERT INTO customer ( Id, Name, Product, Country, Year)

VALUES (1, 'Stephen', 'Computer', 'USA', 2015),

(2, 'Joseph', 'Laptop', 'India', 2016),

(3, 'John', 'TV', 'USA', 2016),


(4, 'Donald', 'Laptop', 'England', 2015),

(5, 'Joseph', 'Mobile', 'India', 2015),

(6, 'Peter', 'Mouse', 'England', 2016);

Now, verify the table by executing the SELECT statement whether the records inserted or not:

mysql> SELECT * FROM customer;

We will get the output, as shown below:

Now, execute the following statement that truncates the table customer using the TRUNCATE syntax discussed above:

mysql> TRUNCATE TABLE customer;

After the successful execution, we will get the following output:

As we can see, this query returns 0 rows are affected even if all the table records are deleted. We can verify the deletion of

the data by executing the SELECT statement again.

This command gives the following output that shows none of the records present in the table:

How to Truncate Table with Foreign key?

If we perform the TRUNCATE operation for the table that uses a foreign key constraint, we will get the following error:

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;

How to truncate all tables in MySQL?

The TRUNCATE statement in MySQL will delete only one table at a time. If we want to delete more than one table, we need to

execute the separate TRUNCATE statement. The below example shows how to truncate multiple tables in MySQL:

TRUNCATE TABLE table_name1;

TRUNCATE TABLE table_name2;

TRUNCATE TABLE table_name3;

We can also use the below SQL query that generates several TRUNCATE TABLE commands at once using the table names in our

database:

SELECT Concat('TRUNCATE TABLE ', TABLE_NAME)

FROM INFORMATION_SCHEMA.TABLES

WHERE table_schema = 'database_name';

MySQL DESCRIBE TABLE

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

The following are the syntax to display the table structure:

{DESCRIBE | DESC} table_name;

We can use the following steps to show all columns of the table:

Step 1: Login into the MySQL database server.

2.4M

63

OOPs Concepts in Java

Step 2: Switch to a specific database.

Step 3: Execute the DESCRIBE statement.

Let us understand it with the help of an example that explains how to show columns of the table in the selected database.

Login to the MySQL 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

Enter password: **********

mysql>

Switch to a Specific Database

The next step is to open a particular database from which you want to display the table information using the following query.

After the execution of a query, we should see the below output:

mysql> USE mysqltestdb;

Execute DESCRIBE Statement

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:

mysql> SHOW TABLES;

For example, if we want to show a customer table's structure, execute the below statement. After successful execution, it

will give the output as below image:


mysql> DESCRIBE customer;

We can also use the DESC statement for practice, which is a shorthand of the DESCRIBE command. See the below output:

How to display table information in MySQL Workbench?

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:

Now do the following steps to show the table information:


1. Go to the Navigation tab and click on the Schema menu. Here, we can see all the previously created databases. Select any

database under the Schema menu, for example, mysqltestdb. It will pop up the multiple options that can be shown in the 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:

Finally, click on the "Columns" menu to display the table structure.


MySQL SHOW COLUMNS Command

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:

The following are the syntax of the SHOW COLUMNS command:

mysql> SHOW COLUMNS FROM table_name;

For example, if we execute the below query, we will get all columns information of a table in a particular database:

mysql> SHOW COLUMNS FROM customer;

If we want to show the columns information of a table from another database or not available in the current database, we

can use the following query:

mysql> SHOW COLUMNS FROM database_name.table_name;

OR

mysql> SHOW COLUMNS FROM table_name IN database_name;

In the below image, we can see that we had used the mysqltestdb database. But we had displayed the column's information of a

table from another database without switching to the current database.


If we want to display the more column information, we need to add FULL keyword with the SHOW TABLES statement as follows:

mysql> SHOW FULL COLUMNS FROM table_name;

For example, the below SQL query lists all columns of the student_info table in the mystudentdb database:

mysql> SHOW FULL COLUMNS FROM student_info;

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> EXPLAIN SELECT * FROM customer;


Output:

MySQL DROP Table

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 -

cause we cannot recover the lost data after deleting it.

Syntax

The following are the syntax to remove the table in MySQL:

mysql> DROP TABLE table_name;

OR,

mysql> DROP TABLE schema_name.table_name;

The full syntax of DROP TABLE statement in MySQL is:

DROP [ TEMPORARY ] TABLE [ IF EXISTS ] table_name [ RESTRICT | CASCADE ];

The above syntax used many parameters or arguments. Let us discuss each in detail:

Parameter Name Description

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

exists in the database.

RESTRICT and CASCADE Both are optional parameters that do not have any impact or effect on this statement.

They are included in the syntax for future versions of MySQL.


NOTE: It is to be noted that you must have a DROP privileges to execute the DROP TABLE statement in the MySQL.

Example

This example specifies how we can drop an existing table from the database. Suppose our database contains a table "orders" as

shown in the image below:

To delete the above table, we need to run the following statement:

mysql> DROP TABLE orders;

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:

How to DROP table in Workbench

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.

MySQL DROP Multiple Table

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:

DROP TABLE IF EXISTS table_name1, table_name2, table, ......., table_nameN;

MySQL TRUNCATE Table vs. DROP Table

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 Temporary Table

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

program or terminates the connection or removed the table manually.

A temporary table provides a very useful and flexible feature that allows us to achieve complex tasks quickly, such as when we

query data that requires a single SELECT statement with JOIN clauses. Here, the user can use this table to keep
the output and performs another query to process it.

A temporary table in MySQL has many features, which are given below:

o MySQL uses the CREATE TEMPORARY TABLE statement to create a temporary table.
o This statement can only be used when the MySQL server has the CREATE TEMPORARY TABLES privilege.

o It can be visible and accessible to the client who creates it, which means two different clients can use the temporary

tables with the same name without conflicting with each other. It is because this table can only be seen by that client who 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

temporary table, the permanent student table becomes accessible again.

Syntax of Creating Temporary Table

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:

mysql> CREATE TEMPORARY TABLE table_name (

column_1, column_2, ..., table_constraints

);

If the user wants to create a temporary table whose structure is the same as an existing table in the database, then the above

statement cannot be used. Instead, we use the syntax as given below:

Mysql> CREATE TEMPORARY TABLE temporary_table_name SELECT * FROM original_table_name LIMIT 0;

MySQL Temporary Table Example

Let us understand how we can create a temporary table in MySQL. Execute the following statement that creates a temporary
table in the selected database:

mysql> CREATE TEMPORARY TABLE Students( student_name VARCHAR(40) NOT NULL, total_marks DECIMAL(12,2) NOT NU

LL DEFAULT 0.00, total_subjects INT UNSIGNED NOT NULL DEFAULT 0);

We can see the below image:


Next, we need to insert values in the temporary table:

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:

Now, run the following query to get the result:

mysql> SELECT * FROM Students;

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.

A Temporary Table whose structure is based on a normal table

In this example, we are going to create a temporary table whose structure is based on the already available tables in the data-

base.

Suppose our database has the following table as permanent:


Here, the structure of a temporary table is created by using the SELECT statement and merge two tables using the INNER JOIN

clause and sorts them based on the price. Write the following statement in the MySQL prompt:

CREATE TEMPORARY TABLE temp_customers

SELECT c.cust_name, c.city, o.prod_name, o.price

FROM orders o

INNER JOIN customer c ON c.cust_id = o.order_id

ORDER BY o.price DESC;

When we execute the above statement, we will get the following message:

Now, run the below command to see the temporary table:

mysql> SELECT * FROM temp_customers;

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:

Mysql> SELECT cust_name, prod_name, price FROM temp_customers;


After executing the above statement, it will give the output as below:

NOTE: It is noted that we can use IF NOT EXISTS keyword to avoid the "table already exists" error.

How to Drop Temporary Table in MySQL

MySQL allows us to remove the temporary table using the DROP TABLE statement. But, it’s a good practice to use
the TEMPORARY keyword with the DROP TABLE statement. This keyword helps us to avoid the mistake of deleting a permanent

table when the temporary table and permanent table have the same name in the current session. So, it is recommended to use

the following query for removing the temporary table:

mysql> DROP TEMPORARY TABLE table_name;

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> DROP TEMPORARY TABLE top_customers;

MySQL Copy/Clone/Duplicate Table

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:

CREATE TABLE new_table_name

SELECT column1, column2, column3

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:

CREATE TABLE new_table_name

SELECT column1, column2, column3


FROM existing_table_name

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-

plains it more clearly:

CREATE TABLE IF NOT EXISTS new_table_name

SELECT column1, column2, column3

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:

CREATE TABLE IF NOT EXISTS new_table_name LIKE existing_table_name;

INSERT new_table_name SELECT * FROM existing_table_name;

In the above, we can see that we need to execute two statements for copying data along with structure and constraints. The

first command creates a new table new_table_name that duplicates the existing_table_name, and the second command

adds data from the existing table to the new_table_name.

MySQL Copy/Clone Table Example

Let us demonstrate how we can create a duplicate table with the help of an example. First, we are going to create a table

named "original_table" using the below statement:

CREATE TABLE original_table (

Id int PRIMARY KEY NOT NULL,

Name varchar(45) NOT NULL,

Product varchar(45) DEFAULT NULL,

Country varchar(25) DEFAULT NULL,

Year int NOT NULL

);

Next, it is required to add values to this table. Execute the below statement:

INSERT INTO original_table( Id, Name, Product, Country, Year)

VALUES (1, 'Stephen', 'Computer', 'USA', 2015),

(2, 'Joseph', 'Laptop', 'India', 2016),

(3, 'John', 'TV', 'USA', 2016),

(4, 'Donald', 'Laptop', 'England', 2015),

(5, 'Joseph', 'Mobile', 'India', 2015),


(6, 'Peter', 'Mouse', 'England', 2016);

Next, execute the SELECT statement to display the records:

mysql> SELECT * FROM original_table;

We will get the output, as shown below:

Now, execute the following statement that copies data from the existing table "original_table" to a new table named

"duplicate_table" in the selected database.

CREATE TABLE IF NOT EXISTS duplicate_table

SELECT * FROM original_table;

After the successful execution, we can verify the table data using the SELECT statement. See the below output:
Sometimes there is a need to copy only partial data from an existing table to a new table. In that case, we can use the WHERE

clause with the SELECT statement as follows:

CREATE TABLE IF NOT EXISTS duplicate_table

SELECT * FROM original_table WHERE Year = '2016';

This statement creates a duplicate table that contains data for the year 2016 only. We can verify the table using a SELECT

statement, as shown below:

Suppose there a need to copy an existing table along with all dependent objects associated with the table, execute the two

statements that are given below:

mysql> CREATE TABLE duplicate_table LIKE original_table;

AND,

mysql> INSERT duplicate_table SELECT * FROM original_table;


Let us see how we can copy a table to a different database through an example.

Suppose there is a situation to copy a table from a different database. In that case, we need to execute the below statements:

CREATE TABLE destination_db.new_table_name

LIKE source_db.existing_table_name;

INSERT destination_db.new_table_name

SELECT * FROM source_db.existing_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.

The following demonstration explains it more clearly.

Suppose we have two databases named "mysqltestdb" and "mystudentdb" on the MySQL Server. The mytestdb database

contains a table named "original_table" that have the following data:

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

SELECT * FROM mysqltestdb.original_table;

After successful execution, we can verify the table in mystudentdb database using the below command:

mysql> SELECT * FROM mystudentdb.duplicate_table;

In the below output, we can see that the table is successfully copied into one database to another database.

MySQL REPAIR TABLE


How to Fix a Corrupted Table in MySQL?

MySQL Repair Table allows us to repair or fix the corrupted table. The repair table in MySQL provides support only for 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

The following is the syntax to repair a corrupted table in MySQL:

REPAIR [NO_WRITE_TO_BINLOG | LOCAL]


TABLE tbl_name [, tbl_name] ...

[QUICK] [EXTENDED] [USE_FRM]

Let us discuss the use of each option in detail.

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.

Storage Engine and Partitioning Support with Repair Table

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.

MySQL REPAIR TABLE Example

Let us understand the working of the repair table statement in MySQL through example. First, we need to create a new table

named vehicle in the selected database as follows:

CREATE TABLE vehicle (

vehicle_no VARCHAR(18) PRIMARY KEY,

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:

mysql> INSERT INTO vehicle (vehicle_no, model_name, cost_price, sell_price)

VALUES('S2001', 'Scorpio', 950000, 1000000),

('M3000', 'Mercedes', 2500000, 3000000),

('R0001', 'Rolls Royas', 75000000, 85000000);

Next, execute the below statement to verify the data:

mysql> SELECT * FROM vehicle;


We should get the below result:

Next, we will execute the below statement to check the storage engine of the vehicle table:

mysql> SELECT table_name, engine

FROM information_schema.tables

WHERE table_name = 'vehicle';

After executing the statement, we should get the below output:

Here we can see that the storage engine of the vehicle table is InnoDB. Therefore, if we create the repair table using the below

query for this storage engine, MySQL issued an error:

mysql> REPAIR TABLE vehicle;

See the below output:

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.

mysql> ALTER TABLE vehicle ENGINE = 'MyISAM';

//Now, use the repair table query


mysql> REPAIR TABLE vehicle;

We will get the below output:

In this output, we can see that the REPAIR TABLE statement contains the following columns in the result set:

SN Column Name Descriptions

1. Table This column indicates the name of the table.

2. Op This column always contains repair word whether the storage engine supports or not

with the statement.

3. Msg_type This column can be either status, error, info, note, or warning.

4. Msg_text This column consists of the informational message.

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.

CREATE TABLE memberships (

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(55) NOT NULL,

email VARCHAR(55) NOT NULL,

plan VARCHAR(45) NOT NULL,

validity_date DATE NOT NULL

) ENGINE = MyISAM;

We will insert some data into this table with the below statement:

mysql> INSERT INTO memberships (name, email, plan, validity_date)

VALUES('Stephen', '[email protected]', 'Gold', '2020-06-13'),

('Jenifer', '[email protected]', 'Platinum', '2020-06-10'),

('david', '[email protected]', 'Silver', '2020-06-15');


Next, execute the SELECT statement to verify the data. We will get the below result:

Since we have created the MyISAM storage engine table, the repair table statement does not issue any error. See the below

statement:

mysql> REPAIR TABLE memberships QUICK EXTENDED;

We should get the output as follows:

If we use the REPAIR TABLE statement with the table that does not exist in our selected database, MySQL gives an error mes -

sage. See the below statement:

mysql> REPAIR TABLE service_memberships QUICK EXTENDED;

After execution, we will get the following output:

In this article, we have learned how to repair the corrupted table in MySQL using the Repair Table statement. This statement

works only for certain storage engines. Thus, before using this query, we first check the table storage engine supports it or not.

If it is not supported, we need to change it into MyISAM, ARCHIVE, or CSV. It is always good to keep our table's backup before

performing the "table repair" query because it might cause a loss of our data.

MySQL Add/Delete Column

A column is a series of cells in a table that may contain text, numbers, and images. Every column stores one value for each row

in a table. In this section, we are going to discuss how to add or delete columns in an existing table.
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:

ALTER TABLE table_name

ADD COLUMN column_name column_definition [FIRST|AFTER existing_column];

In the above,

o First, we need to specify the table name.

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:

ALTER TABLE table_name

ADD COLUMN column_name1 column_definition [FIRST|AFTER existing_column],

ADD COLUMN column_name2 column_definition [FIRST|AFTER existing_column];

MySQL ADD COLUMN Example

Let us understand it with the help of various examples. Here, we will create a table named "Test" using the following state-

ments:

CREATE TABLE Test (

Stude_id int AUTO_INCREMENT PRIMARY KEY,

Name varchar(55) NOT NULL

);

The table structure looks like the below image:


After creating a table, we want to add a new column named City to the Test table. Since we have not specified the new column

position explicitly after the column name, MySQL will add it as the last column.

ALTER TABLE Test

ADD COLUMN City VARCHAR(30) NOT NULL;

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.

ALTER TABLE Test

ADD COLUMN Phone_number VARCHAR (20) NOT NULL AFTER Name;

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:

INSERT INTO Test( Name, Phone_number, City)

VALUES ('Peter', '34556745362', 'California'),

('Mike', '983635674562', 'Texas');

It will look like this.

Suppose we want to add more than one column ,(Branch, Email) in the Test table. In that case, execute the statement as fol-

lows:

ALTER TABLE Test

ADD COLUMN Branch VARCHAR(30) DEFAULT NULL After Name,

ADD COLUMN Email VARCHAR(20) DEFAULT NULL AFTER Phone_number;

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-

low statement that issues an error:

ALTER TABLE Test

ADD COLUMN City VARCHAR(30) NOT NULL;

We will get the following error message.

How can we rename a column in MySQL table?

MySQL allows the ALTER TABLE CHANGE COLUMN statement to change the old column with a new name. The following are

the syntax to do this:

ALTER TABLE table_name

CHANGE COLUMN old_column_name new_column_name column_definition [FIRST|AFTER existing_column];

In the above,

o First, we need to specify the table name.

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 -

umn name at the specific position.

MySQL RENAME COLUMN Example

This example shows how we can change the column name in the MySQL table:

ALTER TABLE Test


CHANGE COLUMN Phone_number Mobile_number

varchar(20) NOT NULL;

This statement will change the column name Phone_number with the new name Mobile_number in the Test table. The below

output explains it more clearly.

How can we drop a column from MySQL table?

Sometimes, we want to remove single or multiple columns from the table. MySQL allows the ALTER TABLE DROP

COLUMN statement to delete the column from the table. The following are the syntax to do this:

ALTER TABLE table_name DROP COLUMN column_name;

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:

ALTER TABLE table_name

DROP COLUMN column_1,

DROP COLUMN column_2,

......;

MySQL DROP COLUMN Example

This example explains how we can delete a column from the MySQL table. Here, we will take a table "Test" that we have cre-

ated earlier and look like the below image:


Suppose we want to delete a column name "Branch" from the Test table. To do this, execute the below statement:

ALTER TABLE Test DROP COLUMN Branch;

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:

ALTER TABLE Test

DROP COLUMN Mobile_number,

DROP COLUMN Email;

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.

MySQL Show Columns

Columns in the table are a series of cells that can stores text, numbers, and images. Every column stores one value for each row

in a table. When we work with the MySQL server, it is common to display the column information from a particular table. In this

section, we are going to discuss how to display or list columns in an existing table.

MySQL provides two ways for displaying the column information:

1. MySQL SHOW COLUMNS Statement

2. MySQL DESCRIBE Statement

Let us discuss both in detail.

MySQL SHOW COLUMNS Statement

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 following is a syntax to display the column information in a specified table:

SHOW [EXTENDED] [FULL] {COLUMNS | FIELDS}

{FROM | IN} table_name

[{FROM | IN} db_name]

[LIKE 'pattern' | WHERE expr]

Let's discuss the syntax parameters in detail.

The EXTENDED is an optional keyword to display the information, including hidden columns. MySQL uses hidden columns in-

ternally that are not accessible by users.

The FULL is also an optional keyword to display the column information, including collation, comments, and the privileges we

have for each column.

The table_name is the name of a table from which we are going to show column information.
The db_name is the name of a database containing a table from which we will show column information.

The LIKE or WHERE clause is used to display only the matched column information in a given table.

We can also use the alternative of table_name FROM db_name syntax as db_name.tbl_name. Therefore, the below

statements are equivalent:

SHOW COLUMNS FROM mytable_name FROM mydb_name;

OR,

SHOW COLUMNS FROM mydb_name.mytable_name;

SHOW COLUMNS Statement Example

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:

mysql> SHOW COLUMNS FROM student_info;

We will see the below output:

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:

mysql> SHOW COLUMNS FROM student_info LIKE 's%';


This query shows the column information that starts with the letter S only. See the below output:

If we want to display hidden column information, we need to add the FULL keyword to the SHOW COLUMNS statement as fol-

lows:

mysql> SHOW FULL COLUMNS FROM student_info;

It returns the below output that displays all columns information of the student_info table in the sample database.

The SHOW COLUMNS statement provides the below information for each column in a given table:

Field: It indicates the name of the column in a given table.

Type: It indicates the data type of each column.

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

value, it contains NO value.

Key: It indicates the indexing of the columns as PRI, UNI, and MUL. Let us understand this field in detail.

o If we have not specified any key, it means the column is not indexed. Otherwise, index as a secondary column in a

multiple-column.

o If the column is specified as a PRI, it means the column is a PRIMARY KEY or one of the fields in a multiple-column 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

given value multiple times.


o If the column is specified by more than one key-value, this field displays the key which has the highest priority (the

key priority is in the order of PRI, UNI, and MUL).

Default: It indicates the default value to the column. If the column includes no DEFAULT clause or has an explicit NULL default,

it contains a NULL value.

Extra: It indicates the additional information related to a given column. This field is non-empty in the following cases:

o If the column is specified with the AUTO_INCREMENT attribute, its value is filled with auto_increment.

o If the column is specified with TIMESTAMP or DATETIME that have the ON UPDATE CURRENT_TIMESTAMP attribute, its

value is filled with on update CURRENT_TIMESTAMP.

o For the generated columns, its value filled with VIRTUAL GENERATED or VIRTUAL STORED.

o If the column contains an expression default value, its value is filled with DEFAULT_GENERATED.

Privileges: It indicates the privileges that we have for the column. We will see this column only when we use the FULL keyword.

Comment: It indicates the comment that we have included in the column definition. We will see this column only when we use
the FULL keyword.

MySQL DESCRIBE Statement

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:

{DESCRIBE | DESC} table_name;

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.

mysql> DESCRIBE students_info;

After successful execution, it will give the output as below image:


How to display column information in MySQL Workbench?

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.

MySQL Rename Column

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

as ALTER and DROP statement privileges.

MySQL can rename the column name in two ways:

1. Using the CHANGE statement

2. Using the RENAME statement

Using the CHANGE Statement:

The following are the syntax that illustrates the column rename using the CHANGE statement:

ALTER TABLE table_name

CHANGE COLUMN old_column_name new_column_name Data Type;

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:

mysql> ALTER TABLE balance

CHANGE COLUMN account_num account_no VARCHAR(25);

After executing the above command, we can verify it by using the DESCRIBE statement again. In the below image, the column

name account_num and its data type have changed successfully.


Using the RENAME Statement:

To remove the drawback of a CHANGE statement, MySQL proposed the following syntax that illustrates the changing of the

column name using a RENAME statement:

ALTER TABLE table_name

RENAME COLUMN old_column_name TO new_column_name;

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-

ecuting the below statement:

1. mysql> ALTER TABLE customer RENAME COLUMN account to account_no;

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.

Renaming Multiple Columns

MySQL also allows us to change the multiple column names within a single statement. If we want to rename multiple column

names, we might use the below syntax:

ALTER TABLE table_name


CHANGE old_column_name1 new_column_name1 Data Type,

CHANGE old_column_name2 new_column_name2 Data Type,

...

...

CHANGE old_column_nameN new_column_nameN Data Type;

OR

ALTER TABLE table_name

RENAME COLUMN old_column_name1 TO new_column_name1,

RENAME COLUMN old_column_name2 TO new_column_name2,

...

...

RENAME COLUMN old_column_nameN TO new_column_nameN;

Example

Suppose we want to change column names id and customer_name from the customer table. To change multiple column

names within a single statement, we can use the statement as follows:

mysql> ALTER TABLE customer

CHANGE id cust_id int,

CHANGE customer_name cust_name varchar(45);

After executing the above command, we can verify it by using the SELECT statement again. In the below image, the column

name id and customer_name have changed successfully:

Let us again change the currently modifying column name through the RENAME COLUMN statement as follows:

mysql> ALTER TABLE customer

RENAME COLUMN cust_id TO id,

RENAME COLUMN cust_name TO customer_name;

After executing the above command, we can verify it by using the DESCRIBE statement again. In the below image, the column

name cust_id and cust_name have changed successfully:


In this article, we have learned an introduction of the MySQL RENAME column and how to change the column name in a specified

table, along with a query example for better understanding.

MySQL View

A view is a database object that has no values. Its contents are based on the base table. It contains rows and columns similar to
the real table. In MySQL, the View is a virtual table created by a query by joining one or more tables. It is operated similarly to

the base table but does not contain any data of its own. The View and table have one main difference that the views are 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.

MySQL allows us to create a view in mainly two ways:

1. MySQL Command line client

2. MySQL Workbench

Let us discuss both in detail.

MySQL Command Line Client


We can create a new view by using the CREATE VIEW and SELECT statement. SELECT statements are used to take data from

the source table to make a VIEW.

Syntax

Following is the syntax to create a view in MySQL:

CREATE [OR REPLACE] VIEW view_name AS

SELECT columns

FROM tables

[WHERE conditions];

Parameters:

The view syntax contains the following 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,

the CREATE VIEW statement will return an error.


view_name: It specifies the name of the VIEW that you want to create in MySQL.

WHERE conditions: It is also optional. It specifies the conditions that must be met for the records to be included in the VIEW.

Example

Let us understand it with the help of an example. Suppose our database has a table course, and we are going to create a view

based on this table. Thus, the below example will create a VIEW name "trainer" that creates a virtual table made by taking data

from the table courses.

CREATE VIEW trainer AS

SELECT course_name, trainer

FROM courses;

Once the execution of the CREATE VIEW statement becomes successful, MySQL will create a view and stores it in the database..

To see the created VIEW

We can see the created view by using the following syntax:

SELECT * FROM view_name;

Let's see how it looks the created VIEW:

SELECT * FROM trainer;


NOTE: It is essential to know that a view does not store the data physically. When we execute the SELECT statement for the view, MySQL uses the
query specified in the view's definition and produces the output. Due to this feature, it is sometimes referred to as a virtual table.

MySQL Update VIEW

In MYSQL, the ALTER VIEW statement is used to modify or update the already created VIEW without dropping it.

Syntax:

Following is the syntax used to update the existing view in MySQL:

ALTER VIEW view_name AS

SELECT columns

FROM table

WHERE conditions;

Example:

The following example will alter the already created VIEW name "trainer" by adding a new column.

ALTER VIEW trainer AS

SELECT id, course_name, trainer

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:

The following is the syntax used to delete the view:

DROP VIEW [IF EXISTS] view_name;

Parameters:

view_name: It specifies the name of the VIEW that we want to drop.

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:

DROP VIEW trainer;

After successful execution, it is required to verify the view is available or not as below:

MySQL Create View with JOIN Clause

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:

CREATE VIEW Trainer

AS SELECT c.course_name, c.trainer, t.email

FROM courses c, contact t

WHERE c.id = t.id;

We can verify the view using the SELECT statement shown in the below image:

Create View using MySQL Workbench

To create a view in the database using this tool, we first need to launch the MySQL Workbench and log in with
the username and password to the MySQL server. It will show the following screen:
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:

Why we use View?

MySQL view provides the following advantages to the user:

Simplify complex query

It allows the user to simplify complex queries. If we are using the complex query, we can create a view based on it to use a

simple SELECT statement instead of typing the complex query again.

Increases the Re-usability

We know that View simplifies the complex queries and converts them into a single line of code to use VIEWS. Such type of code

makes it easier to integrate with our application. This will eliminate the chances of repeatedly writing the same formula in every

query, making the code reusable and more readable.

Help in Data Security

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.

Enable Backward Compatibility

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.

1) MySQL Create Database

MySQL create database is used to create database. For example


create database db1;

2) MySQL Select/Use Database

MySQL use database is used to select database. For example

use db1;

3) MySQL Create Query

MySQL create query is used to create a table, view, procedure and function. For example:

CREATE TABLE customers

(id int(10),

name varchar(50),

city varchar(50),

PRIMARY KEY (id )

);

4) MySQL Alter Query

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:

ALTER TABLE customers

ADD age varchar(50);

5) MySQL Insert Query

MySQL insert query is used to insert records into table. For example:

insert into customers values(101,'rahul','delhi');

6) MySQL Update Query

MySQL update query is used to update records of a table. For example:

update customers set name='bob', city='london' where id=101;

7) MySQL Delete Query

MySQL update query is used to delete records of a table from database. For example:

delete from customers where id=101;


8) MySQL Select Query

Oracle select query is used to fetch records from database. For example:

SELECT * from customers;

9) MySQL Truncate Table Query

MySQL update query is used to truncate or remove records of a table. It doesn't remove structure. For example:

truncate table customers;

10) MySQL Drop Query

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:

drop table customers;

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.

Types of MySQL Constraints

Constraints in MySQL is classified into two types:

1. Column Level Constraints: These constraints are applied only to the single column that limits the type of particular

column data.

2. Table Level Constraints: These constraints are applied to the entire table that limits the type of data for the whole

table.

How to create constraints in MySQL

We can define the constraints during a table created by using the CREATE TABLE statement. MySQL also uses the ALTER TABLE

statement to specify the constraints in the case of the existing table schema.

Syntax

The following are the syntax to create a constraints in table:

CREATE TABLE new_table_name (

col_name1 datatype constraint,

col_name2 datatype constraint,

col_name3 datatype constraint,


.........

);

Constraints used in MySQL

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

Let us discuss each of these constraints in detail.

NOT NULL Constraint

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

Execute the queries listed below to understand how it works:

mysql> INSERT INTO Student VALUES(1, 'Hanks', 'Peter', 'New York');

mysql> INSERT INTO Student VALUES(2, NULL, 'Amanda', 'Florida');

Output

In the above image, we can see that the first INSERT query executes correctly, but the second statement fails and gives an error

that says column LastName cannot be null.


UNIQUE Constraint

This constraint ensures that all values inserted into the column will be unique. It means a column cannot stores duplicate values.

MySQL allows us to use more than one column with UNIQUE constraint in a table. The below statement creates a table with a

UNIQUE constraint:

mysql> CREATE TABLE ShirtBrands(Id INTEGER, BrandName VARCHAR(40) UNIQUE, Size VARCHAR(30));

Execute the queries listed below to understand how it works:

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

that says: Duplicate entry 'Cantabil' for key BrandName.

CHECK Constraint

It controls the value in a particular column. It ensures that the inserted value in a column must be satisfied with the given 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:

[CONSTRAINT [symbol]] CHECK (expr) [[NOT] ENFORCED]

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:

mysql> CREATE TABLE Persons (

ID int NOT NULL,


Name varchar(45) NOT NULL,

Age int CHECK (Age>=18)

);

Execute the listed queries to insert the values into the table:

mysql> INSERT INTO Persons(Id, Name, Age)

VALUES (1,'Robert', 28), (2, 'Joseph', 35), (3, 'Peter', 40);

mysql> INSERT INTO Persons(Id, Name, Age) VALUES (1,'Robert', 15);

Output

In the below output, we can see that the first INSERT query executes successfully, but the second statement fails and gives an

error that says: CHECK constraint is violated for key Age.

DEFAULT Constraint

This constraint is used to set the default value for the particular column where we have not specified any value. It means the

column must contain a value, including NULL.

For example, the following statement creates a table "Persons" that contains DEFAULT constraint on the "City" column. If we

have not specified any value to the City column, it inserts the default value:

mysql> CREATE TABLE Persons (

ID int NOT NULL,

Name varchar(45) NOT NULL,

Age int,

City varchar(25) DEFAULT 'New York'

);
Execute the listed queries to insert the values into the table:

mysql> INSERT INTO Persons(Id, Name, Age, City)

VALUES (1,'Robert', 15, 'Florida'),

(2, 'Joseph', 35, 'California'),

(3, 'Peter', 40, 'Alaska');

mysql> INSERT INTO Persons(Id, Name, Age) VALUES (1,'Brayan', 15);

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:

mysql> SELECT * FROM Persons;

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:

CREATE TABLE Persons (

ID int NOT NULL PRIMARY KEY,

Name varchar(45) NOT NULL,

Age int,

City varchar(25));

Next, use the insert query to store data into a table:

INSERT INTO Persons(Id, Name, Age, City)

VALUES (1,'Robert', 15, 'Florida') ,

(2, 'Joseph', 35, 'California'),

(3, 'Peter', 40, 'Alaska');

INSERT INTO Persons(Id, Name, Age, City)

VALUES (1,'Stephen', 15, 'Florida');

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

constraint for the primary key field in a table.

We can understand it with the following example where the id column going to be auto-incremented in the Animal table:

mysql> CREATE TABLE Animals(

id int NOT NULL AUTO_INCREMENT,

name CHAR(30) NOT NULL,

PRIMARY KEY (id));

Next, we need to insert the values into the "Animals" table:

mysql> INSERT INTO Animals (name) VALUES

('Tiger'),('Dog'),('Penguin'),

('Camel'),('Cat'),('Ostrich');

Now, execute the below statement to get the table data:

mysql> SELECT * FROM Animals;

Output

In the output, we can see that I have not specified any value for the auto-increment column, so MySQL automatically generates

a unique number in the sequence order for this field.


ENUM Constraint

The ENUM data type in MySQL is a string object. It allows us to limit the value chosen from a list of permitted values in the

column specification at the time of table creation. It is short for enumeration, which means that each column may have one of

the specified possible values. It uses numeric indexes (1, 2, 3…) to represent string values.

The following illustration creates a table named "shirts" that contains three columns: id, name, and size. The column name

"size" uses the ENUM data type that contains small, medium, large, and x-large sizes.

mysql> CREATE TABLE Shirts (

id INT PRIMARY KEY AUTO_INCREMENT,

name VARCHAR(35),

size ENUM('small', 'medium', 'large', 'x-large')

);

Next, we need to insert the values into the "Shirts" table using the below statements:

mysql> INSERT INTO Shirts(id, name, size)

VALUES (1,'t-shirt', 'medium'),

(2, 'casual-shirt', 'small'),

(3, 'formal-shirt', 'large');

Now, execute the SELECT statement to see the inserted values into the table:

mysql> SELECT * FROM Shirts;

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.

mysql> CREATE TABLE Shirts (

id INT PRIMARY KEY AUTO_INCREMENT,

name VARCHAR(35),

size ENUM('small', 'medium', 'large', 'x-large')

);

Next, we need to insert the values into the "Shirts" table using the below statements:

mysql> INSERT INTO Shirts(id, name, size)

VALUES (1,'t-shirt', 'medium'),

(2, 'casual-shirt', 'small'),

(3, 'formal-shirt', 'large');

Now, execute this statement for creating index:

mysql> CREATE INDEX idx_name ON Shirts(name);

We can use the query below to retrieve the data using the index column:

mysql> SELECT * FROM Shirts USE INDEX(idx_name);

Output

The following output appears:

Foreign Key Constraint

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.

Let us consider the structure of these tables: Persons and Orders.

Table: Persons
CREATE TABLE Persons (

Person_ID int NOT NULL PRIMARY KEY,

Name varchar(45) NOT NULL,

Age int,

City varchar(25)

);

Table: Orders

CREATE TABLE Orders (

Order_ID int NOT NULL PRIMARY KEY,

Order_Num int NOT NULL,

Person_ID int,

FOREIGN KEY (Person_ID) REFERENCES Persons(Person_ID)

);

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

MySQL INSERT statement is used to store or add data in MySQL table within the database. We can perform insertion of records

in two ways using a single query in MySQL:

1. Insert record in a single row

2. Insert record in multiple rows


Syntax:

The below is generic syntax of SQL INSERT INTO command to insert a single record in MySQL table:

INSERT INTO table_name ( field1, field2,...fieldN )

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

values corresponding to columns name after the VALUES clause.

NOTE: Field name is optional. If we want to specify partial values, the field name is mandatory. It also ensures that the column name and values should
be the same. Also, the position of columns and corresponding values must be the same.

If we want to insert multiple records within a single command, use the following statement:

ion Handling in Java - Javatpoint

INSERT INTO table_name VALUES

( value1, value2,...valueN )

( value1, value2,...valueN )

...........

( value1, value2,...valueN );

In the above syntax, all rows should be separated by commas in the value fields.

MySQL INSERT Example

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:

CREATE TABLE People(

id int NOT NULL AUTO_INCREMENT,

name varchar(45) NOT NULL,

occupation varchar(35) NOT NULL,

age int,

PRIMARY KEY (id)

);

1. If we want to store single records for all fields, use the syntax as follows:

INSERT INTO People (id, name, occupation, age)

VALUES (101, 'Peter', 'Engineer', 32);

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

(102, 'Joseph', 'Developer', 30),

(103, 'Mike', 'Leader', 28),

(104, 'Stephen', 'Scientist', 45);

3. If we want to store records without giving all fields, we use the following partial field statements. In such case, it is mandat-

ory to specify field names.

INSERT INTO People (name, occupation)

VALUES ('Stephen', 'Scientist'), ('Bob', 'Actor');

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:

mysql> SELECT * FROM People;

We will get the output as follows:


Inserting Date in MySQL 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.

This format has the below descriptions:

o YYYY: It represents the four-digit year, like 2020.

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.

Following is the basic syntax to insert date in MySQL table:

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:

INSERT INTO table_name VALUES (STR_TO_DATE(date_value, format_specifier));

MySQL UPDATE Query

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

to use the UPDATE query.

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

SET column_name1 = new-value1,

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

operator by specifying the value in each column.

WHERE Clause It is optional. It is used to specify the row name in which we are going to perform updation. If

we omit this clause, MySQL updates all rows.

Note:

o This statement can update values in a single table at a time.

o We can update single or multiple columns altogether with this statement.

o Any condition can be specified by using the WHERE clause.

o WHERE clause is very important because sometimes we want to update only a single row, and if we omit this clause, it

accidentally updates all rows of the table.

The UPDATE command supports these modifiers in MySQL:

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-

flicts, the rows are not updated.

Therefore, the full syntax of UPDATE statement is given below:

UPDATE [LOW_PRIORITY] [IGNORE] table_name

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 Single Column


This query will update the email id of Java course with the new id as follows:

UPDATE trainer

SET email = '[email protected]'

WHERE course_name = 'Java';

After successful execution, we will verify the table using the below statement:

SELECT * FROM trainer;

In the output, we can see that our table is updated as per our conditions.

Update Multiple Columns

The UPDATE statement can also be used to update multiple columns by specifying a comma-separated list of columns. Suppose

we have a table as below:

This statement explains will update the name and occupation whose id = 105 in the People table as follows:

UPDATE People

SET name = 'Mary', occupation = 'Content Writer'

WHERE id = 105;
We can verify the output below:

UPDATE Statement to Replace String

We can also use the UPDATE statement in MySQL to change the string name in the particular column. The following example up-

dates the domain parts of emails of Android course:

UPDATE Trainer_table

SET email = REPLACE(email,'@javatpoint.com','@tutorialandexample.com')

WHERE course_name = 'Testing';

It will give the following output:


MySQL DELETE Statement

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

need it in the future.

Syntax:

The following are the syntax that illustrates how to use the DELETE statement:

5.4M

DELETE FROM table_name WHERE condition;

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

TABLE statement that gives better performance.

Let us understand how the DELETE statement works in MySQL through various examples.

MySQL DELETE Statement Examples

Here, we are going to use the "Employees" and "Payment" tables for the demonstration of the DELETE statement. Suppose

the Employees and Payment tables contain the following data:


If we want to delete an employee whose emp_id is 107, we should use the DELETE statement with the WHERE clause. See the

below query:

mysql> DELETE FROM Employees WHERE emp_id=107;

After the execution of the query, it will return the output as below image. Once the record is deleted, verify the table using

the SELECT statement:

If we want to delete all records from the table, there is no need to use the WHERE clause with the DELETE statement. See the

below code and output:


In the above output, we can see that after removing all rows, the Employees table will be empty. It means no records available

in the selected table.

MySQL DELETE and LIMIT Clause

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:

1. DELETE FROM table_name

2. WHERE condition

3. ORDER BY colm1, colm2, ...

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

using the LIMIT clause.

For example, the following query first sorts the employees according to their names alphabetically and deletes the first three

employees from the table:

1. mysql> DELETE FROM Employees ORDER BY name LIMIT 3;

It will give the below output:

MySQL DELETE and JOIN Clause

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

INNER JOIN Payment

ON Employees.emp_id = Payment.emp_id

WHERE Employees.emp_id = 102;

Output:

After execution, we will see the output as below image:

To read more information about the DELETE statement with the JOIN clause

MySQL SELECT Statement

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

as PHP, Ruby, and many more.

SELECT Statement Syntax

It is the most commonly used SQL query. The general syntax of this statement to fetch data from tables is as follows:

SELECT field_name1, field_name 2,... field_nameN

FROM table_name1, table_name2...

[WHERE condition]

[GROUP BY field_name(s)]

[HAVING condition]

[ORDER BY field_name(s)]

[OFFSET M ][LIMIT N];

Syntax for all fields:

SELECT * FROM tables [WHERE conditions]

[GROUP BY fieldName(s)]

[HAVING condition]

[ORDER BY fieldName(s)]

[OFFSET M ][LIMIT N];

Parameter Explanation

The SELECT statement uses the following parameters:


Parameter Name Descriptions

field_name(s) or * It is used to specify one or more columns to returns in the result set. The asterisk (*) returns

all fields of a table.

table_name(s) It is the name of tables from which we want to fetch data.

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.

MySQL SELECT Statement Example:

Let us understand how SELECT command works in MySQL with the help of various examples. Suppose we have a table
named employee_detail that contains the following data:

151

1. If we want to retrieve a single column from the table, we need to execute the below query:

mysql> SELECT Name FROM employee_detail;

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:

mysql> SELECT Name, Email, City FROM employee_detail;

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:

mysql> SELECT * FROM employee_detail;

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

HAVING SUM(working_hours) > 5;

It will give the below output:

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:

SELECT cust_name, city, order_num, order_date

FROM customer INNER JOIN orders

ON customer.cust_id = orders.order_id

WHERE order_date < '2020-04-30'

ORDER BY cust_name;
After successful execution of the query, we will get the output as follows:

How to Create Index in MySQL

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

more columns of the table for efficient access to the records.

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.

Need for Indexing in MySQL

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

for. This type of searching name is known as sequential searching.

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

performance of the query.

MySQL CREATE INDEX Statement

Generally, we create an index at the time of table creation in the database. The following statement creates a table with an in -

dex that contains two columns col2 and col3.


mysql> CREATE TABLE t_index(

col1 INT PRIMARY KEY,

col2 INT NOT NULL,

col3 INT NOT NULL,

col4 VARCHAR(20),

INDEX (col2,col3)

);

If we want to add index in table, we will use the CREATE INDEX statement as follows:

1. mysql> CREATE INDEX [index_name] ON [table_name] (column names)

In this statement, index_name is the name of the index, table_name is the name of the table to which the index belongs, and

the column_names is the list of columns.

Let us add the new index for the column col4, we use the following statement:

1. mysql> CREATE INDEX ind_1 ON t_index(col4);

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.

SN Storage Engine Index Type

1. InnoDB BTREE

2. Memory/Heap HASH, 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.

Table Name: student

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.

mysql> CREATE INDEX class ON student (class);

After executing the above statement, the index is created successfully. Now, run the below statement to see how MySQL intern-

ally performs this query.

mysql> EXPLAIN SELECT studentid, firstname, lastname FROM student WHERE class = 'CS';

The above statement gives output, as shown below:

In this output, MySQL finds four rows from the class index without scanning the whole table. Hence, it increases the speed of re-

trieval of records on a database table.

If you want to show the indexes of a table, execute the following statement:

mysql> SHOW INDEXES FROM student;

It will give the following output.


MySQL Drop Index

MySQL allows a DROP INDEX statement to remove the existing index from the table. To delete an index from a table, we can use

the following query:

mysql>DROP INDEX index_name ON table_name [algorithm_option | lock_option];

If we want to delete an index, it requires two things:

o First, we have to specify the name of the index that we want to remove.

o Second, name of the table from which your index belongs.

The Drop Index syntax contains two optional options, which are Algorithm and Lock for reading and writing the tables during the

index modifications. Let us explain both in detail:

Algorithm Option

The algorithm_option enables us to specify the specific algorithm for removing the index in a table. The syntax

of algorithm_option are as follows:

2.2M

54

History of Java

1. Algorithm [=] {DEFAULT | INPLACE | COPY}

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-

tion are as follows:

LOCK [=] {DEFAULT|NONE|SHARED|EXCLUSIVE}

In the syntax, we can see that the lock_option contains four modes that are DEFAULT, NONE, SHARED, and EXCLUSIVE. Now,

we are going to discuss all the modes in detail:

SHARED: This mode supports only concurrent reads, not concurrent writes. When the concurrent reads are not supported, it

gives an error.
DEFAULT: This mode can have the maximum level of concurrency for a specified algorithm. It will enable concurrent reads and

writes if supported otherwise enforces exclusive mode.

NONE: You have concurrent read and write if this mode is supported. Otherwise, it gives an error.

EXCLUSIVE: This mode enforces exclusive access.

Example

First, execute the following command to show the indexes available in the table.

mysql> SHOW INDEXES FROM student;

It will give the following output.

In the output, we can see that there are three indexes available. Now, execute the following statement to removes the class in-

dex from table student.

mysql> DROP INDEX class ON student;

Again, execute the SHOW INDEXES statement to verify the index is removed or not. After performing this statement, we will get

the following output, where only two indexes are available.

Example using Algorithm and Lock

The following statement drops the age index form the student table using an algorithm and a lock option.

mysql> DROP INDEX age ON student ALGORITHM = INPLACE LOCK = DEFAULT;

MySQL Drop PRIMARY Key Index

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.

mysql> DROP INDEX PRIMARY ON table_name;

To remove the primary key index from the student table, execute the following statement:

mysql> DROP INDEX PRIMARY ON student;


MySQL Show Indexes

We can get the index information of a table using the Show Indexes statement. This statement can be written as:

mysql> SHOW INDEXES FROM table_name;

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:

mysql> SHOW INDEXES FROM table_name IN database_name;

The above statement can also be written as:

mysql> SHOW INDEXES FROM database_name.table_name;

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:

mysql> SHOW INDEXES IN table_name FROM database_name;

OR,

mysql> SHOW KEYS FROM table_name IN database_name;

The SHOW INDEX query returns the following fields/information:

Table: It contains the name of the table.

Non_unique: It returns 1 if the index contains duplicates. Otherwise, it returns 0.

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

Column_name: It contains the name of a column.

Collation: It gives information about how the column is sorted in the index. It contains values where A represents ascend-

ing, D represents descending, and Null represents not sorted.

Cardinality: It gives an estimated number of unique values in the index table where the higher cardinality represents a greater

chance of using indexes by MySQL.

Sub_part: It is a prefix of the index. It has a NULL value if all the column of the table is indexed. When the column is partially in -

dexed, it will return the number of indexed characters.


Packed: It tells how the key is packed. Otherwise, it returns NULL.

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 -

abled, it returns disabled.

Index_column: When you create an index with comment attributes, it contains the comment for the specified index.

Visible: It contains YES if the index is visible to the query optimizer, and if not, it contains NO.

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.

MySQL SHOW INDEX Example

Here, we are going to create a table student_info that contains the student id, name, age, mobile number, and email details.

Execute the following command to create a table:

CREATE TABLE `student_info` (

`studentid` int NOT NULL AUTO_INCREMENT,

`name` varchar(45) DEFAULT NULL,

`age` varchar(3) DEFAULT NULL,

`mobile` varchar(20) DEFAULT NULL,

`email` varchar(25) DEFAULT NULL,

PRIMARY KEY (`studentid`),

UNIQUE KEY `email_UNIQUE` (`email`)

Next, we create an index on this table by the following command:

mysql> CREATE INDEX mobile ON student_info (mobile) INVISIBLE;

mysql> CREATE INDEX name ON student_info (name) COMMENT 'Student Name';

Now, execute the following command that returns the all index information from the student_info table:

mysql> SHOW INDEXES FROM student_info;

We will get the output below:


Filter Index Information

We can filter the index information using where clause. The following statement can be used to filter the index in-
formation:

Mysql> SHOW INDEXES FROM table_name where condition;

Example

If you want to get only invisible indexes of the student_info table, execute the following command:

mysql> SHOW INDEXES FROM student_info WHERE visible = 'NO';

It will give the following output:

MYSQL CLAUSE

MySQL WHERE Clause

MySQL WHERE Clause is used with SELECT, INSERT, UPDATE and DELETE clause to filter the results. It specifies a specific posi-

tion where you have to do the operation.

Syntax:

WHERE conditions;

Parameter:

conditions: It specifies the conditions that must be fulfilled for records to be selected.

MySQL WHERE Clause with single condition

Let's take an example to retrieve data from a table "officers".

Table structure:
Execute this query:

SELECT *

FROM officers

WHERE address = 'Mau';

Output:

MySQL WHERE Clause with AND condition

In this example, we are retrieving data from the table "officers" with AND condition.

Execute the following query:

SELECT *
FROM officers

WHERE address = 'Lucknow'

AND officer_id < 5;

Output:

WHERE Clause with OR condition

Execute the following query:

SELECT *

FROM officers

WHERE address = 'Lucknow'

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.

See this example:

Execute the following query:

SELECT *

FROM officers

WHERE (address = 'Mau' AND officer_name = 'Ajeet')

OR (officer_id < 5);

Output:
MySQL Distinct Clause

MySQL DISTINCT clause is used to remove duplicate records from the table and fetch only the unique records. The DISTINCT

clause is only used with the SELECT statement.

Syntax:

SELECT DISTINCT expressions

FROM tables

[WHERE conditions];

Parameters

expressions: specify the columns or calculations that you want to retrieve.

tables: specify the name of the tables from where you retrieve records. There must be at least one table listed in the FROM

clause.

WHERE conditions: It is optional. It specifies the conditions that must be met for the records to be selected.

Note:

o If you put only one expression in the DISTINCT clause, the query will return the unique values for that expression.

o If you put more than one expression in the DISTINCT clause, the query will retrieve unique combinations for the 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-

ment, your result set will include NULL as a distinct value.

MySQL DISTINCT Clause with single expression

If you use a single expression then the MySQL DISTINCT clause will return a single field with unique records (no duplicate re -

cord).

See the table:


Use the following query:

SELECT DISTINCT address

FROM officers;

MySQL DISTINCT Clause with multiple expressions

If you use multiple expressions with DISTINCT Clause then MySQL DISTINCT clause will remove duplicates from more than one

field in your SELECT statement.

Use the following query:


SELECT DISTINCT officer_name, address

FROM officers;

MySQL FROM Clause

The MySQL FROM Clause is used to select some records from a table. It can also be used to retrieve records from multiple tables

using JOIN condition.

Syntax:

FROM table1

[ { INNER JOIN | LEFT [OUTER] JOIN| RIGHT [OUTER] JOIN } table2

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:

OOPs Concepts in Java

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.

Use the following Query:

SELECT *

FROM officers

WHERE officer_id <= 3;

MySQL FROM Clause: Retrieve data from two tables with inner join

Let's take an example to retrieve data from two tables using INNER JOIN.

Here, we have two tables "officers" and "students".


Execute the following query:

SELECT officers.officer_id, students.student_name

FROM students

INNER JOIN officers

ON students.student_id = officers.officer_id;

MySQL FROM Clause: Retrieve data from two tables using outer join

Execute the following query:

SELECT officers.officer_id, students.student_name

FROM officers
LEFT OUTER JOIN students

ON officers.officer_id = students.student_id;

MySQL ORDER BY Clause

The MYSQL ORDER BY Clause is used to sort the records in ascending or descending order.

Syntax:

SELECT expressions

FROM tables

[WHERE conditions]

ORDER BY expression [ ASC | DESC ];

Parameters

expressions: It specifies the columns that you want to retrieve.

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

Difference between JDK, JRE, and JVM

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.

MySQL ORDER BY: without using ASC/DESC attribute

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.

Execute the following query:

SELECT *

FROM officers

WHERE address = 'Lucknow'

ORDER BY officer_name;

Output:

MySQL ORDER BY: with ASC attribute

Let's take an example to retrieve the data in ascending order.

Execute the following query:

SELECT *

FROM officers

WHERE address = 'Lucknow'

ORDER BY officer_name ASC;

Output:
MySQL ORDER BY: with DESC attribute
SELECT *

FROM officers

WHERE address = 'Lucknow'

ORDER BY officer_name DESC;

MySQL ORDER BY: using both ASC and DESC attributes

Execute the following query:

1. SELECT officer_name, address

2. FROM officers

3. WHERE officer_id < 5

4. ORDER BY officer_name DESC, address ASC;


Output:

MySQL GROUP BY Clause

The MYSQL GROUP BY Clause is used to collect data from multiple records and group the result by one or more column. It is gen-

erally used in a SELECT statement.

You can also use some aggregate functions like COUNT, SUM, MIN, MAX, AVG etc. on the grouped column.

Syntax:

SELECT expression1, expression2, ... expression_n,

aggregate_function (expression)

FROM tables

[WHERE conditions]

GROUP BY expression1, expression2, ... expression_n;

Parameters

expression1, expression2, ... expression_n: It specifies the expressions that are not encapsulated within an aggregate func-

tion and must be included in the GROUP BY clause.

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.

(i) MySQL GROUP BY Clause with COUNT function

Consider a table named "officers" table, having the following records.


Now, let's count repetitive number of cities in the column address.

Execute the following query:

SELECT address, COUNT(*)

FROM officers

GROUP BY address;

Output:

(ii) MySQL GROUP BY Clause with SUM function

Let's take a table "employees" table, having the following data.


Now, the following query will GROUP BY the example using the SUM function and return the emp_name and total working hours

of each employee.

Execute the following query:

SELECT emp_name, SUM(working_hours) AS "Total working hours"

FROM employees

GROUP BY emp_name;

Output:

(iii) MySQL GROUP BY Clause with MIN function

The following example specifies the minimum working hours of the employees form the table "employees".
Execute the following query:

SELECT emp_name, MIN(working_hours) AS "Minimum working hour"

FROM employees

GROUP BY emp_name;

Output:

(iv) MySQL GROUP BY Clause with MAX function

The following example specifies the maximum working hours of the employees form the table "employees".

Execute the following query:

SELECT emp_name, MAX (working_hours) AS "Minimum working hour"

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

Execute the following query:

SELECT emp_name, AVG(working_hours) AS "Average working hour"

FROM employees

GROUP BY emp_name;

Output:

MySQL HAVING Clause

MySQL HAVING Clause is used with GROUP BY clause. It always returns the rows where condition is TRUE.
Syntax:

SELECT expression1, expression2, ... expression_n,

aggregate_function (expression)

FROM tables

[WHERE conditions]

GROUP BY expression1, expression2, ... expression_n

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-

tion and must be included in the GROUP BY clause.

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.

HAVING Clause with SUM function

Consider a table "employees" table having the following data.

Here, we use the SUM function with the HAVING Clause to return the emp_name and sum of their working hours.

Execute the following query:

SELECT emp_name, SUM(working_hours) AS "Total working hours"


FROM employees

GROUP BY emp_name

HAVING SUM(working_hours) > 5;

Simply, it can also be used with COUNT, MIN, MAX and AVG functions.

MYSQL CONDITION

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

MySQL AND Example

The following example specifies how to use the AND condition in MySQL with SELECT statement.

Consider a table "cus_tbl", having the following data:


Execute the following query:

SELECT *

FROM cus_tbl

WHERE cus_firstname = 'Ajeet'

AND cus_id > 3;

Output:

MySQL OR Condition

The MySQL OR condition specifies that if you take two or more conditions then one of the conditions must be fulfilled to get the

records as result.

Syntax:

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.

Consider a table "cus_tbl", having the following data:

Execute the following query:

SELECT *

FROM cus_tbl

WHERE cus_firstname = 'Ajeet'

OR cus_id > 100;

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 -

ult because of the OR condition.

MySQL AND & OR condition

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.

MySQL AND OR Example

Consider a table "students", having the following data.

OOPs Concepts in Java


Execute the following query:

SELECT *

FROM students

WHERE (course_name = 'Java' AND student_name = 'Aryan')

OR (student_id < 2);

Output:

MySQL Boolean

A Boolean is the simplest data type that always returns two possible values, either true or false. It can always use to get a con-

firmation in the form of YES or No value.


MySQL does not contain built-in Boolean or Bool data type. They provide a TINYINT data type instead of Boolean or Bool data

types. MySQL considered value zero as false and non-zero value as true. If you want to use Boolean literals, use true or
false that always evaluates to 0 and 1 value. The 0 and 1 represent the integer values.

Execute the following statement to see the integer values of Boolean literals:

Mysql> Select TRUE, FALSE, true, false, True, False;

After successful execution, the following result appears:

MySQL Boolean Example

We can store a Boolean value in the MySQL table as an integer data type. Let us create a table student that demonstrates the

use of Boolean data type in MySQL:

mysql> CREATE TABLE student (

studentid INT PRIMARY KEY AUTO_INCREMENT,

name VARCHAR(40) NOT NULL,

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:

mysql> DESCRIBE student;

Let us add two new rows in the above table with the help of following query:

mysql> INSERT INTO student(name, pass) VALUES('Peter',true), ('John',false);

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:

Mysql> SELECT studentid, name, pass FROM student;

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:

Mysql> INSERT INTO student(name, pass) VALUES('Miller',2);

You will get the following result:

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 -

lect statement as follows:

Mysql> SELECT studentid, name, IF(pass, 'true', 'false') completed FROM student1;

It will give the following output:

MySQL Boolean Operators

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.

SELECT studentid, name, pass FROM student1 WHERE pass = TRUE;

This statement returns the following output:

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:

SELECT studentid, name, pass FROM student1 WHERE pass is TRUE;

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


OR,

SELECT studentid, name, pass FROM student1 WHERE pass IS NOT TRUE;

You will get the following output:

MySQL LIKE condition

In MySQL, LIKE condition is used to perform pattern matching to find the correct result. It is used in SELECT, INSERT, UPDATE

and DELETE statement with the combination of WHERE clause.

Syntax:

expression LIKE pattern [ ESCAPE 'escape_character' ]

Parameters

expression: It specifies a column or field.

pattern: It is a character expression that contains pattern matching.

escape_character: It is optional. It allows you to test for literal instances of a wildcard character such as % or _. If you do not

provide the escape_character, MySQL assumes that "\" is the escape_character.

MySQL LIKE Examples


1) Using % (percent) Wildcard:

Consider a table "officers" having the following data.


Execute the following query:

SELECT officer_name

FROM officers

WHERE address LIKE 'Luck%';

Output:

2) Using _ (Underscore) Wildcard:

We are using the same table "officers" in this example too.

Execute the following query:

SELECT officer_name

FROM officers

WHERE address LIKE 'Luc_now';

Output:
3) Using NOT Operator:

You can also use NOT operator with MySQL LIKE condition. This example shows the use of % wildcard with the NOT Operator.

Consider a table "officers" having the following data.

Execute the following query:

SELECT officer_name

FROM officers

WHERE address NOT LIKE 'Luck%';

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:

expression IN (value1, value2, .... value_n);

Parameters

expression: It specifies a value to test.

value1, value2, ... or value_n: These are the values to test against expression. If any of these values matches expression,

then the IN condition will evaluate to true. This is a quick method to test if any one of the values matches expression.

MySQL IN Example

Consider a table "officers", having the following data.

Triggers in SQL (Hindi)

Execute the following query:

SELECT *

FROM officers

WHERE officer_name IN ('Ajeet', 'Vimal', 'Deepika');

Output:
Let's see why it is preferred over OR condition:

Execute the following query:

SELECT *

FROM officers

WHERE officer_name = 'Ajeet'

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:

operand comparison_operator ANY (subquery)

Where comparison operators can be one of the following:

HTML Tutorial

= > < >= <= <> !=

This syntax can also be written as:

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:

CREATE TABLE table1 (

num_value INT

);

INSERT INTO table1 (num_value)

VALUES(10), (20), (25);


CREATE TABLE table2 (

num_val int

);

INSERT INTO table2 (num_val)

VALUES(20), (7), (10);

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:

SELECT num_value FROM table1

WHERE num_value > ANY (SELECT num_val FROM table2);

This statement returns true and gives the below output because table2 contains (20, 10, and 7) and there is a value 7 in table2

which is less than 10, 20, and 25 of table1.

The IN keyword in MySQL is an alias for = ANY when used with a subquery in the statement. Hence, the below two state-

ments are identical in MySQL:


SELECT colm1 FROM table1 WHERE colm1 = ANY (SELECT colm1 FROM table2);

SELECT colm1 FROM table1 WHERE colm1 IN (SELECT colm1 FROM table2);

But we cannot say that IN and = ANY were synonyms when we used it with an expression list. It is because IN can take a list of

expressions, but = ANY cannot.

Also, NOT IN cannot be an alias for <> ANY operator, but it can be used for <> ALL.

The word SOME in MySQL can be an alias for ANY. Therefore, these two SQL statements are equivalent:

SELECT colm1 FROM table1 WHERE colm1 <>ANY (SELECT colm1 FROM table2);

SELECT colm1 FROM table1 WHERE colm1 <> SOME (SELECT colm1 FROM table2);

Advantages of ANY operator in MySQL

o ANY is a logical operator that returns the Boolean value. It allows us to select any or some rows of the SELECT 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

the values satisfy the condition. Otherwise, it gives a false value.

MySQL Exists

The EXISTS operator in MySQL is a type of Boolean operator which returns the true or false result. It is used in combination

with a subquery and checks the existence of data in a subquery. It means if a subquery returns any record, this operator returns

true. Otherwise, it will return false. The true value is always represented numeric value 1, and the false value represents 0. We

can use it with SELECT, UPDATE, DELETE, INSERT statement.

Syntax

The following are the syntax to use the EXISTS operator in MySQL:

SELECT col_names

FROM tab_name

WHERE [NOT] EXISTS (

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-

ance of the query in MySQL.

Parameter Explanation

The following are parameters used in the EXISTS operator:

Parameter Name Descriptions

col_names It is the name of column(s) that contains in the specified table.

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.

MySQL EXISTS Operator Example

Let us understand how the EXISTS operator works in MySQL. Here, we are going to first create two tables named "customer"

and "orders" using the following statement:

CREATE TABLE customer(

cust_id int NOT NULL,

name varchar(35),

occupation varchar(25),

age int

);

CREATE TABLE orders (

order_id int NOT NULL,

cust_id int,

prod_name varchar(45),

order_date date

);
Next, we need to insert values into both tables. Execute the below statements:

INSERT INTO customer(cust_id, name, occupation, age)

VALUES (101, 'Peter', 'Engineer', 32),

(102, 'Joseph', 'Developer', 30),

(103, 'John', 'Leader', 28),

(104, 'Stephen', 'Scientist', 45),

(105, 'Suzi', 'Carpenter', 26),

(106, 'Bob', 'Actor', 25),

(107, NULL, NULL, NULL);

INSERT INTO orders (order_id, cust_id, prod_name, order_date)

VALUES (1, '101', 'Laptop', '2020-01-10'),

(2, '103', 'Desktop', '2020-02-12'),

(3, '106', 'Iphone', '2020-02-15'),

(4, '104', 'Mobile', '2020-03-05'),

(5, '102', 'TV', '2020-03-20');

To verify the tables, run the SELECT command as below:

msql> SELECT * FROM customer;

AND,

mysql> SELECT * FROM orders;

We will get the below output:


MySQL SELECT EXISTS Example

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:

mysql> SELECT name, occupation FROM customer

WHERE EXISTS (SELECT * FROM Orders

WHERE customer.cust_id = Orders.cust_id);

The following output appears:

Again, if we want to get the name of the customer who has not placed an order, then use the NOT EXISTS operator:

mysql> SELECT name, occupation FROM customer

WHERE NOT EXISTS (SELECT * FROM Orders

WHERE customer.cust_id = Orders.cust_id);

It will give the below output:


MySQL EXISTS With DELETE Statement Example

Suppose we want to delete a record from the Orders table whose order_id = 3, execute the following query that deletes the re -

cord from Orders table permanently:

mysql> DELETE FROM Orders WHERE EXISTS (

SELECT * FROM customer

WHERE order_id=3);

To verify the output, run the below command:

mysql> SELECT * FROM Orders;

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:

mysql> SELECT EXISTS(SELECT * from customer WHERE cust_id=104) AS Result;

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.

2. SELECT col_names FROM tab_name WHERE SELECT col_names


FROM tab_name
col_name IN (subquery);
WHERE [NOT] EXISTS (subquery);

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

and child query or subquery. and child query or subquery.

MySQL NOT Condition

The MySQL NOT condition is opposite of MySQL IN condition. It is used to negate a condition in a SELECT, INSERT, UPDATE or DE -

LETE statement.

Syntax:

1. NOT condition

Parameter

condition: It specifies the conditions that you want to negate.

MySQL NOT Operator with IN condition

Consider a table "officers", having the following data.


Execute the following query:

Singleton pattern | Build a CMS using OOP PHP tutorial MVC [2020]

SELECT *

FROM officers

WHERE officer_name NOT IN ('Ajeet','Vimal','Deepika');

Output:

MySQL NOT Operator with IS NULL condition:

Execute the following query:

SELECT *

FROM officers

WHERE officer_name IS NOT NULL;


Output:

MySQL NOT Operator with LIKE condition:

We are taking the same table "officer" for this operation also:

Execute the following query:

SELECT *

FROM officers

WHERE officer_name NOT LIKE 'A%';

Output:
MySQL NOT Operator with BETWEEN condition:

We are taking the same table "officer" for this operation also:

Execute the following query:

SELECT *

FROM officers

WHERE officer_id NOT BETWEEN 3 AND 5;

Output:

MySQL Not Equal

MySQL Not Equal is an inequality operator that used for returning a set of rows after comparing two expressions that are not

equal. The MySQL contains two types of Not Equal operator, which are (< >) and (! =).

Difference Between (< >) and (! =) Operator

The Not Equal 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

Triggers in SQL (Hindi)


If you want to get the student details who do not belong to England, then you need to execute the following statement:

SELECT * FROM students WHERE city <> "England";

OR,

SELECT * FROM students WHERE city != "England";

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-

plicate income value, execute the following statement:

SELECT * FROM customers

JOIN contacts ON customer_id = contact_id

WHERE cellphone <> "Null"

GROUP BY income;

We will get the following output:

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-

tacts" and "customers" in a database that contains the following data:

Table: contacts
Table: customers

If we want to get all the records from table customers and contacts where the cellphone is Null, execute the following statement

that returns all customers who do not have a cellphone number:

SELECT * FROM customers

JOIN contacts ON customer_id = contact_id

WHERE cellphone != "Null;

After successful execution, it will give the following output:

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-

ecute the following statement to get the result:

SELECT * FROM customers Where income>40000 and occupation<>"Developer";

After the successful execution of the above statement, we will get the following output.

MySQL IS NULL Condition

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

expression: It specifies a value to test if it is NULL value.

Consider a table "officers" having the following data.

Execute the following query:

SELECT *

FROM officers

WHERE officer_name IS NULL;

Output:
Note: Here, you are getting the empty result because there is no NULL value in officer_name column.

MySQL IS NOT NULL Condition

MySQL IS NOT NULL condition is used to check the NOT NULL value in the expression. It is used with SELECT, INSERT, UPDATE

and DELETE statements.

Syntax:

expression IS NOT NULL

Parameter

expression: It specifies a value to test if it is not NULL value.

MySQL IS NOT NULL Example

Consider a table "officers" having the following data.

5.9M

113

Difference between JDK, JRE, and JVM


Execute the following query:

SELECT *

FROM officers

WHERE officer_name IS NOT NULL;

Output:

Note: Here, you are getting the complete "officers" table as result because every value is NOT NULL in the table.

MySQL BETWEEN Condition

The MYSQL BETWEEN condition specifies how to retrieve values from an expression within a specific range. It is used with SE -

LECT, INSERT, UPDATE and DELETE statement.


Syntax:

expression BETWEEN value1 AND value2;

Parameters

expression: It specifies a column.

value1 and value2: These values define an inclusive range that expression is compared to.

Let's take some examples:

(i) MySQL BETWEEN condition with numeric value:

Consider a table "officers" having the following data.

Execute the following query:

SELECT *

FROM officers

WHERE officer_id BETWEEN 1 AND 3;

Output:
Note: In the above example, you can see that only three rows are returned between 1 and 3.

(ii) MySQL BETWEEN condition with date:

MySQL BETWEEN condition also facilitates you to retrieve records according to date.

See this example:

Consider a table "employees", having the following data.

Execute the following query:

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

need to fetch records from two or more tables.

There are three types of MySQL joins:

o MySQL INNER JOIN (or sometimes called simple join)

o MySQL LEFT OUTER JOIN (or sometimes called LEFT JOIN)

o MySQL RIGHT OUTER JOIN (or sometimes called RIGHT JOIN)

MySQL Inner JOIN (Simple Join)

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

INNER JOIN table2

ON table1.column = table2.column;
Image representation:

Let's take an example:

Consider two tables "officers" and "students", having the following data.

Execute the following query:

SELECT officers.officer_name, officers.address, students.course_name

FROM officers

INNER JOIN students

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

table where the join condition is fulfilled.

Syntax:

SELECT columns

FROM table1

LEFT [OUTER] JOIN table2

ON table1.column = table2.column;

Image representation:

Let's take an example:

Consider two tables "officers" and "students", having the following data.
Execute the following query:

SELECT officers.officer_name, officers.address, students.course_name

FROM officers

LEFT JOIN students

ON officers.officer_id = students.student_id;

Output:

MySQL Right Outer Join

The MySQL Right Outer Join returns all rows from the RIGHT-hand table specified in the ON condition and only those rows from

the other table where he join condition is fulfilled.

Syntax:

SELECT columns

FROM table1

RIGHT [OUTER] JOIN table2

ON table1.column = table2.column;
Image representation:

Let's take an example:

Consider two tables "officers" and "students", having the following data.

Execute the following query:

SELECT officers.officer_name, officers.address, students.course_name, students.student_name

FROM officers

RIGHT JOIN students

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:

MySQL Inner Join Syntax:

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

INNER JOIN table2 ON condition1

INNER JOIN table3 ON condition2

...;

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

rows between the tables specifies in the Inner clause.


61. Model & PHP Singleton pattern | Build a CMS using OOP PHP tutorial MVC [2020]

MySQL Inner Join Example

Let us first create two tables "students" and "technologies" that contains the following data:

Table: student

Table: technologies

To select records from both tables, execute the following query:

SELECT students.stud_fname, students.stud_lname, students.city, technologies.technology

FROM students

INNER JOIN technologies

ON students.student_id = technologies.tech_id;

After successful execution of the query, it will give the following output:

MySQL Inner Join with Group By Clause

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.

SELECT students.student_id, technologies.inst_name, students.city, technologies.technology

FROM students

INNER JOIN technologies

ON students.student_id = technologies.tech_id GROUP BY inst_name;

The above statement will give the following output:


MySQL Inner Join with USING clause

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-

cords. The following query explains it more clearly:

SELECT student_id, inst_name, city, technology

FROM students

INNER JOIN technologies

USING (student_id);

It will give the following output:

Inner Join with WHERE Clause

The WHERE clause enables you to return the filter result. The following example illustrates this clause with Inner Join:

SELECT tech_id, inst_name, city, technology

FROM students

INNER JOIN technologies

USING (student_id) WHERE technology = "Java";

This statement gives the below result:

MySQL Inner Join Multiple Tables

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:

SELECT student_id, inst_name, city, technology, cellphone

FROM students

INNER JOIN technologies USING (student_id)

INNER JOIN contact ORDER BY student_id;

After successful execution of the above query, it will give the following output:

MySQL Inner Join using Operators

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:

SELECT emp_id, designation, income, qualification

FROM employee

INNER JOIN customer

WHERE income>20000 and income<80000;

This will give the following output:


MySQL LEFT JOIN

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

with Left Join.

We can understand it with the following visual representation where Left Joins returns all records from the left-hand table and

only the matching records from the right side table:

MySQL LEFT JOIN Syntax

The following syntax explains the Left Join clause to join the two or more tables:

OOPs Concepts in Java

SELECT columns

FROM table1

LEFT [OUTER] JOIN table2

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.

MySQL LEFT JOIN Example

Let us take some examples to understand the working of Left Join or Left Outer Join clause:

LEFT JOIN clause for joining two tables

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, execute the following query:

SELECT customers.customer_id, cust_name, price, date

FROM customers

LEFT JOIN orders ON customers.customer_id = orders.customer_id;

After successful execution of the query, it will give the following output:

MySQL LEFT JOIN with USING Clause

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.

SELECT customer_id, cust_name, occupation, price, date


FROM customers

LEFT JOIN orders USING(customer_id);

The above statement will give the following output:

MySQL LEFT JOIN with Group By Clause

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.

SELECT customers.customer_id, cust_name, qualification, price, date

FROM customers

LEFT JOIN orders ON customers.customer_id = orders.customer_id

GROUP BY price;

The above statement will give the following output:

LEFT JOIN with WHERE Clause

The WHERE clause is used to return the filter result from the table. The following example illustrates this with the Left Join

clause:

SELECT customer_id, cust_name, occupation, price, date

FROM customers

LEFT JOIN orders

USING(customer_id) WHERE price>2500;

This statement gives the below result:


MySQL LEFT JOIN Multiple Tables

We have already created two tables named "customers" and "orders". Let us create one more table and name it as "con-

tacts" that contains the following data:

Execute the following statement to join the three table customers, orders, and contacts:

SELECT customers.customer_id, cust_name, order_id, price, cellphone

FROM customers

LEFT JOIN contacts ON customer_id = contact_id

LEFT JOIN orders ON customers.customer_id = orders.customer_id ORDER BY income;

After successful execution of the above query, it will give the following output:

Use of LEFT JOIN clause to get unmatched records

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

rows of data from another table.

We can understand it with the following example that uses the LEFT JOIN clause to find a customer who has no cellphone num-

ber:

SELECT customer_id, cust_name, cellphone, homephone

FROM customers

LEFT JOIN contacts ON customer_id = contact_id

WHERE cellphone IS NULL ;

The above statement returns the following output:


Difference between WHERE and ON clause in MySQL LEFT JOIN

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

SELECT cust_name, occupation, order_id, price, date

FROM customers

LEFT JOIN orders

USING(customer_id) WHERE price=2500;

It will give the following output that returns:

ON Clause

SELECT cust_name, occupation, order_id, price, date

FROM customers LEFT JOIN orders ON price=2500;

It will give the following output:

NOTE: The WHERE and ON condition in the Inner Join clause always returns equivalent results.

MySQL RIGHT JOIN

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

clause used with the Right Join.

We can understand it with the following visual representation where Right Outer Join returns all records from the left-hand table

and only the matching records from the other table:


RIGHT JOIN Syntax

The following are the syntax of Right Join that joins tables Table1 and Table2:

SELECT column_list

FROM Table1

RIGHT [OUTER] JOIN Table2

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.

Let us see how Right Join works.

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.

MySQL RIGHT JOIN Examples

Let us take some examples to understand the working of Right Join clause:

RIGHT JOIN clause for joining two tables

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:

SELECT customers.customer_id, cust_name, price, date

FROM customers

RIGHT JOIN orders ON customers.customer_id = orders.customer_id

ORDER BY customer_id;

OR,

SELECT customers.customer_id, cust_name, price, date

FROM customers

RIGHT JOIN orders USING(customer_id)

ORDER BY customer_id;

After successful execution of the above queries, it will give the equivalent output:

RIGHT JOIN with WHERE Clause

MySQL uses the WHERE clause to provide the filter result from the table. The following example illustrates this
with the Right Join clause:

SELECT * FROM customers

RIGHT JOIN orders USING(customer_id)

WHERE price>2500 AND price<5000;

This statement gives the below result:


MySQL RIGHT JOIN Multiple Tables

We have already created two tables, named "customers" and "orders". Let us create one more table and name it as a "con-

tacts" that contains the following data:

Execute the following statement to join the three table customers, orders, and contacts:

SELECT customers.customer_id, cust_name, order_id, price, cellphone

FROM customers

RIGHT JOIN contacts ON customer_id = contact_id

RIGHT JOIN orders ON customers.customer_id = orders.customer_id ORDER BY order_id;

After successful execution of the above query, it will give the following output:

Use of RIGHT JOIN clause to get unmatched records

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

rows of data from another table.

We can understand it with the following example that uses the RIGHT JOIN clause to find a customer who has no cell-

phone number:

SELECT customer_id, cust_name, cellphone, homephone

FROM customers

RIGHT JOIN contacts ON customer_id = contact_id

WHERE cellphone IS NULL

ORDER BY cellphone;

The above statement returns the following output:


MySQL Key
MySQL Unique Key

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.

Needs of Unique Key

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.

o It also works with a foreign key in preserving the uniqueness of a table.

o It can contain null value into the table.

Syntax

The following syntax is used to create a unique key in MySQL.

If we want to create only one unique key column into a table, use the syntax as below:

CREATE TABLE table_name(

col1 datatype,

col2 datatype UNIQUE,

...

);

If we want to create more than one unique key column into a table, use the syntax as below:

CREATE TABLE table_name(

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 -

commended to use the constraint name while creating a table.

Parameter Explanation

The following table explains the parameters in detail.

Parameter Name Descriptions

table_name It is the name of the table that we are going to create.

col1, col2 It is the column names that contain in the table.

constraint_name It is the name of the unique key.

column_name(s) It is the column name(s) that is going to be a unique key.

Unique Key Example

The following example explains how a unique key used in MySQL.

This statement creates a table "Student2" with a UNIQUE constraint:

CREATE TABLE Student2 (

Stud_ID int NOT NULL UNIQUE,

Name varchar(45),

Email varchar(45),

Age int,

City varchar(25)

);

Next, execute the insert queries listed below to understand how it works:

mysql> INSERT INTO Student2 (Stud_ID, Name, Email, Age, City)

VALUES (1, 'Peter', '[email protected]', 22, 'Texas'),

(2, 'Suzi', '[email protected]', 24, 'California'),

(3, 'Joseph', '[email protected]', 23, 'Alaska');

mysql> INSERT INTO Student2 (Stud_ID, Name, Email, Age, City)

VALUES (1, 'Stephen', '[email protected]', 22, 'Texas');

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:

CREATE TABLE Student3 (

Stud_ID int,

Roll_No int,

Name varchar(45) NOT NULL,

Email varchar(45),

Age int,

City varchar(25),

CONSTRAINT uc_rollno_email Unique(Roll_No, Email)

);

In the output, we can see that the unique key value contains two columns that are Roll_No and Email.

To verify this, execute the following statement:

mysql> SHOW INDEX FROM Student3;

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:

ALTER TABLE table_name DROP INDEX constraint_name;

In the above syntax, the table_name is the name of the table that we want to modify, and constraint_name is the name of

the unique key we are going to remove.

Example

This statement will remove the uc_rollno_email constraint from the table permanently.

mysql> ALTER TABLE Student3 DROP INDEX uc_rollno_email;

We can execute the SHOW INDEX statement to very this.

Unique Key Using ALTER TABLE Statement

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:

ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE(column_list);

Example

This statement creates a table "Students3" that have no unique key column into the table definition.

CREATE TABLE Student3 (

Stud_ID int,

Roll_No int,

Name varchar(45) NOT NULL,

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:

mysql> ALTER TABLE Student3 ADD CONSTRAINT uc_rollno_email UNIQUE(Roll_No, Email);

We can see the output where both statements executed successfully.

To verify this, execute the following statement:

mysql> SHOW INDEX FROM Student3;

Here, we can see that the unique constraint has successfully added into the table:

MySQL Primary Key

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.

Rules for Primary key

Following are the rules for the primary key:

1. The primary key column value must be unique.

2. Each table can contain only one primary key.


3. The primary key column cannot be null or empty.

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.

We can create a primary key in two ways:

History of Java

o CREATE TABLE Statement

o ALTER TABLE Statement

Let us discuss each one in detail.

Primary Key Using CREATE TABLE Statement

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:

CREATE TABLE table_name(

col1 datatype PRIMARY KEY,

col2 datatype,

...

);

If we want to create more than one primary key column into the table, use the below syntax:

CREATE TABLE table_name

col1 col_definition,

col2 col_definition,

...

CONSTRAINT [constraint_name]

PRIMARY KEY (column_name(s))

);

Parameter Explanation

The following table explains the parameters in detail.


Parameter Name Descriptions

Table_name It is the name of the table that we are going to create.

Col1, col2 It is the column names that contain in the table.

Constraint_name It is the name of the primary key.

Column_name(s) It is the column name(s) that is going to be a primary key.

Primary Key Example

The following example explains how a primary key used in MySQL.

This statement creates a table named "Login" whose "login_id" column contains the primary key:

Mysql> CREATE TABLE Login(

login_id INT AUTO_INCREMENT PRIMARY KEY,

username VARCHAR(40),

password VARCHAR(55),

email VARCHAR(55)

);

Next, use the insert query to store data into a table:

mysql> INSERT INTO Login(login_id, username, password, email)

VALUES (1,'Stephen', 15343434532, '[email protected]'),

(2, 'Joseph', 35435479495, '[email protected]');

mysql> INSERT INTO Login(login_id, username, password, email)

VALUES (1,'Peter', 15343434532, '[email protected]');

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:

mysql> CREATE TABLE Students (

Student_ID int,

Roll_No int,

Name varchar(45) NOT NULL,

Age int,

City varchar(25),

Primary Key(Student_ID, Roll_No)

);

In the output, we can see that the primary key value contains two columns that are Student_ID and Roll_No.

Primary Key Using ALTER TABLE Statement

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:

ALTER TABLE table_name ADD PRIMARY KEY(column_list);

Example

The following statement creates a table "Persons" that have no primary key column into the table definition.

mysql> CREATE TABLE Persons (

Person_ID int NOT NULL,

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:

mysql> ALTER TABLE Persons ADD PRIMARY KEY(Person_ID);

We can see the output where both statements executed successfully.

If the table needs to add the primary key into a table that already has data into the column, then it must be sure to the column

does not contains duplicates or null values.

DROP Primary Key

The ALTER TABLE statement also allows us to drop the primary key from the table. The following syntax is used to drop the

primary key:

ALTER TABLE table_name DROP PRIMARY KEY;

Example

mysql> ALTER TABLE Login DROP PRIMARY KEY;


Primary Key vs. Unique Key

The following comparison chart explains some of the common differences between both of them:

SN Primary Key Unique Key

1. It is a single or combination of the field, which is used to It also determines each row of the table uniquely

identify each record in a table uniquely. in the absence of a primary key.

2. It does not allow to store a NULL value into the primary It can accept only one NULL value into the

key column. unique key column.

3. A table can have only one primary key. A table can have more than one unique key.

4. It creates a clustered index. It creates a non-clustered index.

MySQL Foreign 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 -

eign key constraint on the child table.

MySQL defines the foreign key in two ways:

1. Using CREATE TABLE Statement

2. Using ALTER TABLE Statement

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]

FOREIGN KEY [foreign_key_name] (col_name, ...)

REFERENCES parent_tbl_name (col_name,...)

ON DELETE referenceOption

ON UPDATE referenceOption

In the above syntax, we can see the following parameters:


 constraint_name: It specifies the name of the foreign key constraint. If we have not provided the constraint name,

MySQL generates its name automatically.

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

DATE clause between parent and child table.

MySQL contains five different referential options, which are given below:

 CASCADE: It is used when we delete or update any row from the parent table, the values of the matching rows in the

child table will be deleted or updated automatically.

 SET NULL: It is used when we delete or update any row from the parent table, the values of the foreign key columns

in the child table are set to NULL.

 RESTRICT: It is used when we delete or update any row from the parent table that has a matching row in the 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

modify the table.

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

Foreign Key Example

Let us understand how foreign key works in MySQL. So first, we are going to create a database named " mysqltestdb" and start

using it with the command below:

mysql> CREATE DATABASE mysqltestdb;

mysql> use mysqltestdb;

Next, we need to create two tables named "customer" and "contact" using the below statement:

Table: customer

CREATE TABLE customer (

ID INT NOT NULL AUTO_INCREMENT,

Name varchar(50) NOT NULL,

City varchar(50) NOT NULL,


PRIMARY KEY (ID)

);

Table: contact

CREATE TABLE contact (

ID INT,

Customer_Id INT,

Customer_Info varchar(50) NOT NULL,

Type varchar(50) NOT NULL,

INDEX par_ind (Customer_Id),

CONSTRAINT fk_customer FOREIGN KEY (Customer_Id)

REFERENCES customer(ID)

ON DELETE CASCADE

ON UPDATE CASCADE

);

Table Structure Verification

Here, we are going to see how our database structure looks like using the following queries:

mysql> SHOW TABLES;

mysql> DESCRIBE customer;

mysql> DESCRIBE contact;

We will get the structure as below:


In the above output, we can see that the PRI in the key column of the customer table tells that this field is the primary index

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.

Insert Data to the Table

Now, we have to insert the records into both tables. Execute this statement to insert data into table customer:

INSERT INTO customer(Name, City) VALUES

('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:

INSERT INTO contact (Customer_Id, Customer_Info, Type) VALUES

(1, '[email protected]', 'email'),

(1, '121-121-121', 'work' ),

(1, '123-123-123', 'home'),

(2, '[email protected]', 'email'),

(2, '[email protected]', 'email'),

(2, '212-212-212', 'work'),

(3, '[email protected]', 'email'),

(3, '313-313-313', 'home');

Our contact table looks like as below:

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

the contact table as:

FOREIGN KEY (Customer_Id) REFERENCES customer(ID)

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.

mysql> DELETE FROM customer WHERE Name='John';

Again, if we look at our tables, we can see that both tables were changed. It means the fields with name JOHN will be removed

entirely from both tables.

Now, test the ON UPDATE CASCADE. Here, we are going to update the Customer_Id of Mary in the contact table as:

mysql> UPDATE customer SET id=3 WHERE Name='Mary';

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

named Persons and Contacts, as shown below:

Table: Persons

CREATE TABLE Persons (

ID INT NOT NULL AUTO_INCREMENT,

Name varchar(50) NOT NULL,

City varchar(50) NOT NULL,

PRIMARY KEY (ID)

);

Table: Customers

CREATE TABLE Contacts (

ID INT,

Person_Id INT,

Info varchar(50) NOT NULL,

Type varchar(50) NOT NULL,

INDEX par_ind (Person_Id),

CONSTRAINT fk_person FOREIGN KEY (Person_Id)

REFERENCES Persons(ID)

ON DELETE SET NULL

ON UPDATE SET NULL


);

Next, we need to insert the data into both tables using the following statement:

INSERT INTO Persons(Name, City) VALUES

('Joseph', 'Texas'),

('Mary', 'Arizona'),

('Peter', 'Alaska');

INSERT INTO Contacts (Person_Id, Info, Type) VALUES

(1, '[email protected]', 'email'),

(1, '121-121-121', 'work' ),

(2, '[email protected]', 'email'),

(2, '212-212-212', 'work'),

(3, '[email protected]', 'email'),

(3, '313-313-313', 'home');

Now, update the ID of the "Persons" table:

mysql> UPDATE Persons SET ID=103 WHERE ID=3;

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-

matically set to NULL due to the ON UPDATE SET NULL action.


How to DROP Foreign Key

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:

ALTER TABLE table_name DROP FOREIGN KEY fk_constraint_name;

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:

mysql> SHOW CREATE TABLE contact;

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:

mysql> ALTER TABLE contact DROP FOREIGN KEY fk_customer;

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.

Define Foreign Key Using ALTER TABLE Statement

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:

ALTER TABLE table_name

ADD [CONSTRAINT [symbol]] FOREIGN KEY


[index_name] (column_name, ...)

REFERENCES table_name (column_name,...)

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

which is referenced by the foreign key.

Example

The following statement creates two tables, "Person" and "Contact", without having a foreign key column into the table defini-

tion.

Table: Person

CREATE TABLE Person (

ID INT NOT NULL AUTO_INCREMENT,

Name varchar(50) NOT NULL,

City varchar(50) NOT NULL,

PRIMARY KEY (ID)

);

Table: Contact

CREATE TABLE Contact (

ID INT,

Person_Id INT,

Info varchar(50) NOT NULL,

Type varchar(50) NOT NULL

);

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:

ALTER TABLE Contact ADD INDEX par_ind ( Person_Id );

ALTER TABLE Contact ADD CONSTRAINT fk_person

FOREIGN KEY ( Person_Id ) REFERENCES Person ( ID ) ON DELETE CASCADE ON UPDATE RESTRICT;

Foreign Key Checks

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

global and session scopes both.

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.

The following statement allows us to disable foreign key checks:

SET foreign_key_checks = 0;

The following statement allows us to enable foreign key checks:

SET foreign_key_checks = 1;

MySQL Composite Key

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

the columns to make a composite key in MySQL.

A composite key can be added in two ways:

1. Using CREATE Statement

2. Using ALTER Statement

Let us see both ways in detail.

5.4M144

C++ vs Java

Composite Key Using CREATE Statement

Here, we are going to understand how composite key works in MySQL. Let us first create a table "Product", using the following

statement:

CREATE TABLE Product (

Prod_ID int NOT NULL,

Name varchar(45),

Manufacturer varchar(45),

PRIMARY KEY(Name, Manufacturer)

);

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-

ite primary key on Name and Manufacturer columns.

Next, we need to insert the values into this table as given below:

INSERT INTO Product (Prod_ID, Name, Manufacturer)

VALUES (101, 'Soap', 'Hamam'),

(102, 'Shampoo', 'Teresme'),

(103, 'Oil', 'Daber Almond');

Next, execute the below command to show the table data:

SELECT * FROM Product;

It will give the output below:

Again execute the below insert statement to understand composite key more clearly:

INSERT INTO Product (Prod_ID, Name, Manufacturer)

VALUES (101, 'Soap', 'Hamam');

INSERT INTO Product (Prod_ID, Name, Manufacturer)

VALUES (101, 'Soap', 'LUX');


In the below output, we can see that if we try to add the combination of the same product name and manufacturer, then it will

throw an error saying that: Duplicate entry for product.primary.

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.

Composite Key Using ALTER TABLE Statement

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.

Let us first create a table "Student" using the below statement:

CREATE TABLE Student(

stud_id int NOT NULL,

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:

ALTER TABLE Student add primary key(stud_id, subject);

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

to stud_id and subject columns.


MYSQL TRIGGER
A trigger in MySQL is a set of SQL statements that reside in a system catalog. It is a special type of stored procedure that

is invoked automatically in response to an event. Each trigger is associated with a table, which is activated on any DML

statement such as INSERT, UPDATE, or DELETE.

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-

trast, a stored procedure must be called explicitly.

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-

fected by the insert, update, or delete statement.

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.

Why we need/use triggers in MySQL?

We need/use triggers in MySQL due to the following features:

o Triggers help us to enforce business rules.

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.

o SQL triggers provide an alternative way to check the integrity of data.

o Triggers provide an alternative way to run the scheduled task.


o Triggers increases the performance of SQL queries because it does not need to compile each time the query is exe -

cuted.

o Triggers reduce the client-side code that saves time and effort.

o Triggers help us to scale our application across different platforms.

o Triggers are easy to maintain.

Limitations of Using Triggers in MySQL

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

happens in the database layer.

o Triggers may increase the overhead of the database server.

Types of Triggers in MySQL?

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.

3. Before Update: It is activated before the update of data in 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:

(BEFOR | AFTER) table_name (INSERT | UPDATE | DELETE)

Thus,

Trigger Activation Time: BEFORE | AFTER

Trigger Event: INSERT | UPDATE | DELETE


How to create triggers in MySQL?

We can use the CREATE TRIGGER statement for creating a new trigger in MySQL. Below is the syntax of creating a trigger in

MySQL:

CREATE TRIGGER trigger_name

(AFTER | BEFORE) (INSERT | UPDATE | DELETE)

ON table_name FOR EACH ROW

BEGIN

--variable declarations

--trigger code

END;

MySQL Create Trigger

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 -

lowing is the basic syntax to create a trigger:

CREATE TRIGGER trigger_name trigger_time trigger_event

ON table_name FOR EACH ROW

BEGIN

--variable declarations

--trigger code

END;

Parameter Explanation

The create trigger syntax contains the following parameters:

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.

INSERT, UPDATE, or DE-


trigger_event: It is the type of operation name that activates the trigger. It can be either

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

specify the table name, a trigger would not exist.

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 -

isting row after it is updated.

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:

Trigger Event OLD NEW

INSERT No Yes

UPDATE Yes Yes

ELETE Yes No

MySQL Trigger Example

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:

CREATE TABLE employee(

name varchar(45) NOT NULL,

occupation varchar(35) NOT NULL,

working_date date,

working_hours varchar(10)

);

Next, execute the below statement to fill the records into the employee table:

INSERT INTO employee VALUES

('Robin', 'Scientist', '2020-10-04', 12),

('Warner', 'Engineer', '2020-10-04', 10),

('Peter', 'Actor', '2020-10-04', 13),

('Marco', 'Doctor', '2020-10-04', 14),

('Brayden', 'Teacher', '2020-10-04', 12),

('Antonio', 'Business', '2020-10-04', 11);

Next, execute the SELECT statement to verify the inserted record:


Next, we will create a BEFORE INSERT trigger. This trigger is invoked automatically insert

the working_hours = 0 if someone tries to insert working_hours < 0.

mysql> DELIMITER //

mysql> Create Trigger before_insert_empworkinghours

BEFORE INSERT ON employee FOR EACH ROW

BEGIN

IF NEW.working_hours < 0 THEN SET NEW.working_hours = 0;

END IF;

END //

If the trigger is created successfully, we will get the output as follows:

Now, we can use the following statements to invoke this trigger:

mysql> INSERT INTO employee VALUES

('Markus', 'Former', '2020-10-08', 14);

mysql> INSERT INTO employee VALUES

('Alexander', 'Actor', '2020-10-012', -13);

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 zero value by a trigger.

MySQL Show/List Triggers

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:

mysql> SHOW TRIGGERS;

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:

mysql> USE database_name;

Step 3: Finally, execute the SHOW TRIGGERS command.

Let us understand it with the example given below. Suppose we have a database name "mysqltestdb" that contains many

tables. Then execute the below statement to list the triggers:

1. mysql> USE mysqltestdb;

2. mysql>SHOW TRIGGERS;

The following output explains it more clearly:


If we want to show or list the trigger information in a specific database from the current database without switching, MySQL al -

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

The above statement can also be written as:

mysql> SHOW TABLES FROM database_name;

When we execute the above statements, we will get the same result.

Show Triggers Using Pattern Matching

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:

mysql> SHOW TRIGGERS LIKE pattern;

OR,

mysql> SHOW TRIGGERS FROM database_name LIKE pattern;

If we want to list/show trigger names based on specific search condition, we can use the WHERE clause as follows:

mysql> SHOW TRIGGERS WHERE search_condition;

OR,

mysql> SHOW TRIGGERS FROM database_name WHERE search_condition;


Example

Suppose we want to show all triggers that belongs to the employee table, execute the statement as follows:

mysql> SHOW TRIGGERS FROM mysqltestdb WHERE table = 'employee';

We will get the output 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 Table: It is the name of the table to which the trigger belongs.

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-

fore or after each row of modifications occurs on the table.

o Created: It represents the time and date when the trigger is created.

o sql_mode: It displays the SQL_MODE when the trigger is executed.

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

database with which the trigger belongs.

How to show triggers in MySQL workbench?

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

created earlier. We will get the screen as follows:


Now do the following steps to show triggers:

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-

tions, and Stored Procedures. See the below screen.

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.

MySQL DROP Trigger

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

TRIGGER statement throws an error.

MySQL allows us to drop/delete/remove a trigger mainly in two ways:

1. MySQL Command Line Client

2. MySQL Workbench

MySQL Command Line Client

We can drop an existing trigger from the database by using the DROP TRIGGER statement with the below syntax:

1. DROP TRIGGER [IF EXISTS] [schema_name.]trigger_name;

Parameter Explanation

The parameters used in the drop trigger syntax are explained as follows: 2.4M

65

OOPs Concepts in Java

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

will remove the trigger from the current database.

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

clause, MySQL gives a NOTE instead of an error.

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.

MySQL DROP Trigger Example

Let us see how we can drop the trigger associated with the table through an example. So first, we will display all trig-

gers available in the selected database using the below statement:

mysql> SHOW TRIGGERS IN employeedb;

After executing the statement, we can see that there are two triggers named before_update_salaries and sales_info_be-

fore_update. See the below image:

If we want to remove the before_update_salaries trigger, execute the below statement:

mysql> DROP TRIGGER employeedb.before_update_salaries;

It will successfully delete a trigger from the database. If we execute the above statement again, it will return an error message.

See the output:

If we execute the above statement again with an IF EXISTS clause, it will return the warning message instead of producing an

error. See the output:


mysql> DROP TRIGGER IF EXISTS employeedb.before_update_salaries;

We can execute the SHOW WARNING statement that generates a NOTE for a non-existent trigger when using IF EXISTS. See

the output:

How to Drop trigger in MySQL workbench?

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-

gers; we will get the below image:


4. Now, right-click on the selected table and choose the Alter Table option that gives the screen as below:

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.

MySQL BEFORE INSERT TRIGGER

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

The following is the syntax to create a BEFORE INSERT trigger in MySQL:

CREATE TRIGGER trigger_name

BEFORE INSERT

ON table_name FOR EACH ROW

Trigger_body ;

The BEFORE INSERT trigger syntax parameter can be explained as below:

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

each row modifications occur on the table.

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

the trigger. See the below syntax:

History of Java
DELIMITER $$

CREATE TRIGGER trigger_name BEFORE INSERT

ON table_name FOR EACH ROW

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.

o We cannot create a BEFORE INSERT trigger on a VIEW.

BEFORE INSERT Trigger Example

Let us understand how to create a BEFORE INSERT trigger using the CREATE TRIGGER state-
ment in MySQL with an example.

Suppose we have created a table named employee as follows:

CREATE TABLE employee(

name varchar(45) NOT NULL,

occupation varchar(35) NOT NULL,

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

mysql> Create Trigger before_insert_occupation

BEFORE INSERT ON employee FOR EACH ROW

BEGIN

IF NEW.occupation = 'Scientist' THEN SET NEW.occupation = 'Doctor';

END IF;

END //

If the trigger is created successfully, we will get the output as follows:

How to call the BEFORE INSERT trigger?

We can use the following statements to invoke the above-created trigger:

mysql> INSERT INTO employee VALUES

('Markus', 'Scientist', '2020-10-08', 14);

mysql> INSERT INTO employee VALUES

('Alexander', 'Actor', '2020-10-012', 13);

After execution of the above statement, we will get the output as follows:

Execute the SELECT statement to verify the output:


In this output, we can see that on inserting the occupation column values as 'Scientist', the table will automatically fill the 'Doc -

tor' value by invoking a trigger.

How to create BEFORE INSERT Trigger in MySQL workbench?

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:

Now do the following steps for creating BEFORE 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, mysqltestdb), double click on it. It will show the sub-menu containing Tables, Views,

Functions, and Stored Procedures. See the below screen.

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:

4. Clicking on the Alter Table option gives the screen as below:


5. Now, click on the Trigger tab shown in the previous section's red rectangular box, then select the Timing/Event BEFORE IN -

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

trigger based on choosing Timing/Event:

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

The following is the syntax to create an AFTER INSERT trigger in MySQL:

CREATE TRIGGER trigger_name

AFTER INSERT

ON table_name FOR EACH ROW

trigger_body ;

The AFTER INSERT trigger syntax parameter can be explained as below:

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-

gic for the trigger. See the below syntax:

DELIMITER $$

CREATE TRIGGER trigger_name AFTER INSERT

ON table_name FOR EACH ROW


BEGIN

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.

o We cannot create the AFTER INSERT trigger on a VIEW.

AFTER INSERT Trigger Example

Let us understand how to create an AFTER INSERT trigger using the CREATE TRIGGER statement
in MySQL with an example.

Suppose we have created a table named "student_info" as follows:

CREATE TABLE student_info (

stud_id int NOT NULL,

stud_code varchar(15) DEFAULT NULL,

stud_name varchar(35) DEFAULT NULL,

subject varchar(25) DEFAULT NULL,

marks int DEFAULT NULL,

phone varchar(15) DEFAULT NULL,

PRIMARY KEY (stud_id)

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:

CREATE TABLE student_detail (

stud_id int NOT NULL,

stud_code varchar(15) DEFAULT NULL,

stud_name varchar(35) DEFAULT NULL,

subject varchar(25) DEFAULT NULL,

marks int DEFAULT NULL,

phone varchar(15) DEFAULT NULL,

Lasinserted Time,

PRIMARY KEY (stud_id)

);

Next, we will use a CREATE TRIGGER statement to create an after_insert_details trigger on the student_info table. This trig-

ger will be fired after an insert operation is performed on the table.

mysql> DELIMITER //

mysql> Create Trigger after_insert_details

AFTER INSERT ON student_info FOR EACH ROW

BEGIN

INSERT INTO student_detail VALUES (new.stud_id, new.stud_code,

new.stud_name, new.subject, new.marks, new.phone, CURTIME());

END //

If the trigger is created successfully, we will get the output as follows:


How to call the AFTER INSERT trigger?

We can use the following statements to invoke the above-created trigger:

mysql> INSERT INTO student_info VALUES

(10, 110, 'Alexandar', 'Biology', 67, '2347346438');

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:

mysql> SELECT * FROM student_detail;

In this output, we can see that on inserting values into the student_info table, the student_detail table will automatically fill the

records by invoking a trigger.

How to create AFTER INSERT Trigger in MySQL workbench?

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-

tions, and Stored Procedures. See the below screen.

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

trigger based on choosing Timing/Event:


6. Now, complete the trigger code, review them once again, and if no error is found, click on the Apply button.

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:

MYSQL AGGREGATE FUNCTIONS


MySQL's aggregate function is used to perform calculations on multiple values and return the result in a single value

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:

The following are the syntax to use aggregate functions in MySQL:


function_name (DISTINCT | ALL expression)

In the above syntax, we had used the following parameters:

o First, we need to specify the name of the aggregate function.

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

summarised in the below table:

Aggregate Function Descriptions

count() It returns the number of rows, including rows with NULL values in a group.

sum() It returns the total summed values (Non-NULL) in a set.

average() It returns the average value of an expression.

min() It returns the minimum (lowest) value in a set.

max() It returns the maximum (highest) value in a set.

groutp_concat() It returns a concatenated string.

first() It returns the first value of an expression.

last() It returns the last value of an expression.

Why we use aggregate functions?

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-

ment may require the following details:

o Most rented movies.

o Least rented movies.

o Average number that each movie is rented out in a month.

We can easily produce these details with the help of aggregate functions.

Let us discuss the most commonly used aggregate functions in detail. First, we will create a new table for the demonstration of

all aggregate functions.

Execute the below statement to create an employee table:


CREATE TABLE employee(

name varchar(45) NOT NULL,

occupation varchar(35) NOT NULL,

working_date date,

working_hours varchar(10)

);

Execute the below statement to insert the records into the employee table:

INSERT INTO employee VALUES

('Robin', 'Scientist', '2020-10-04', 12),

('Warner', 'Engineer', '2020-10-04', 10),

('Peter', 'Actor', '2020-10-04', 13),

('Marco', 'Doctor', '2020-10-04', 14),

('Brayden', 'Teacher', '2020-10-04', 12),

('Antonio', 'Business', '2020-10-04', 11);

Now, execute the SELECT statement to show the record:

Count() Function

MySQL count() function returns the total number of values in the expression. This function produces all rows or only some

rows of the table based on a specified condition, and its return type is BIGINT. It returns zero if it does not find any matching

rows. It can work with both numeric and non-numeric data types.

Example

Suppose we want to get the total number of employees in the employee table, we need to use the count() function as shown in

the following query:

mysql> SELECT COUNT(name) FROM employee;

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

as shown in the following query:

mysql> SELECT SUM(working_hours) AS "Total working hours" FROM employee;

Output:

After execution, we can see the total working hours of all employees in the table.

AVG() Function

MySQL AVG() function calculates the average of the values specified in the column. Similar to the SUM() function, it also

works with numeric data type only.

Suppose we want to get the average working hours of all employees in the table, we need to use the AVG() function as shown in

the following query:

1. mysql> SELECT AVG(working_hours) AS "Average working hours" FROM employee;

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

shown in the following query:

mysql> SELECT MIN(working_hours) AS Minimum_working_hours FROM employee;

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

shown in the following query:

mysql> SELECT MAX(working_hours) AS Maximum_working_hours FROM employee;

Output:

After execution, we can see that the maximum working hours of an employee available in the table:
FIRST() Function

This function returns the first value of the specified column. To get the first value of the column, we must have to use

the LIMIT clause. It is because FIRST() function only supports in MS Access.

Suppose we want to get the first working date of an employee available in the table, we need to use the following query:

mysql> SELECT working_date FROM employee LIMIT 1;

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:

mysql> SELECT working_hours FROM employee ORDER BY name DESC LIMIT 1;

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.

Suppose we have another employee table as below:

If we want to concatenate the designation of the same dept_id on the employee table, we need to use the following query:

1. mysql> SELECT emp_id, emp_fname, emp_lname, dept_id,

2. GROUP_CONCAT(designation) as "designation" FROM employee group by emp_id;

Output:

After execution, we can see that the designation of the same dept_id concatenated successfully:

MySQL Count() Function

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

it does not find any matching rows.

We can use the count function in three forms, which are explained below:

o Count (*)

o Count (expression)
o Count (distinct)

Let us discuss each in detail.

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

Hello Java Program for Beginners

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

result of the expression.

Syntax

The following are the syntax of the COUNT() function:

SELECT COUNT (aggregate_expression)

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

the FROM clause.

WHERE conditions: It is optional. It specifies the conditions that must be fulfilled for the records to be selected.

MySQL count() function example

Consider a table named "employees" that contains the following data.


Let us understand how count() functions work in MySQL.

Example1

Execute the following query that uses the COUNT(expression) function to calculates the total number of employees name avail-

able in the table:

mysql> SELECT COUNT(emp_name) FROM employees;

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:

mysql> SELECT COUNT(*) FROM employees WHERE emp_age>32;

Output:
Example3

This statement uses the COUNT(distinct expression) function that counts the Non-Null and distinct rows in the column emp_age:

mysql> SELECT COUNT(DISTINCT emp_age) FROM employees;

Output:

MySQL Count() Function with GROUP BY Clause

We can also use the count() function with the GROUP BY clause that returns the count of the element in each group. For ex-

ample, the following statement returns the number of employee in each city:

mysql> SELECT emp_name, city, COUNT(*) FROM employees GROUP BY city;

After the successful execution, we will get the result as below:


MySQL Count() Function with HAVING and ORDER BY Clause

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:

mysql> SELECT emp_name, emp_age, COUNT(*) FROM employees

GROUP BY emp_age

HAVING COUNT(*)>=2

ORDER BY COUNT(*);

This statement will give the output as below:

MySQL sum() function

The MySQL sum() function is used to return the total summed value of an expression. It returns NULL if the result set does not

have any rows. It is one of the kinds of aggregate functions in MySQL.

Syntax

Following are the syntax of sum() function in MySQL:

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

with various examples:

1. Basic Example

Execute the following query that calculates the total number of working hours of all employees in the table:

mysql> SELECT SUM(working_hours) AS "Total working hours" FROM employees;

Output:

We will get the result as below:

2. MySQL sum() function with WHERE clause

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:

3. MySQL sum() function with GROUP BY clause

We can also use the SUM() function with the GROUP BY clause to return the total summed value for each group. For example,

this statement calculates the total working hours of each employee by using the SUM() function with the GROUP BY clause, as

shown in the following query:

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.

4. MySQL sum() function with HAVING clause

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.

mysql> SELECT emp_id, emp_name, occupation,

SUM(working_hours) Total_working_hours

FROM employees

GROUP BY occupation
HAVING SUM(working_hours)>24;

Output:

5. MySQL sum() function with DISTINCT clause

MySQL uses the DISTINCT keyword to remove the duplicate rows from the column name. This clause can also be used with

sum() function to return the total summed value of a Unique number of records present in the table.

Execute the following query that removes the duplicate records in the working_hours column of the employee table and then

calculates the sum:

mysql> SELECT emp_name, occupation,

SUM(DISTINCT working_hours) Total_working_hours

FROM employees

GROUP BY occupation;

Output:

MySQL avg() function

The MySQL avg() is an aggregate function used to return the average value of an expression in various records.

Syntax

The following are the basic syntax an avg() function in MySQL:


SELECT AVG(aggregate_expression)

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.

MySQL avg() function example

Consider our database has a table named employees, having the following data. Now, we are going to understand this function

with various examples:

1. Basic Example

Execute the following query that calculates the average working hours of all employees in the table:

mysql> SELECT AVG(working_hours) Avg_working_hours FROM employees;

Output:

We will get the result as below:


2. MySQL AVG() function with WHERE clause

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.

mysql> SELECT AVG(working_hours) Avg_working_hours FROM employees WHERE working_hours>=12;

Output:

It will give the following output:

3. MySQL AVG() function with GROUP BY clause

The GROUP BY clause is used to return the result for each group by one or more columns.

For example, this statement calculates the average working hours of each employee using the AVG() function and then group

the result with the GROUP BY clause:

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.

mysql> SELECT emp_name, occupation,

AVG(working_hours) Avg_working_hours

FROM employees

GROUP BY occupation

HAVING AVG(working_hours)>9;

Output:

5. MySQL AVG() function with DISTINCT clause

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-

turns the average value:

mysql> SELECT emp_name, occupation,

AVG(DISTINCT working_hours) Avg_working_hours

FROM employees

GROUP BY occupation;
Output:

MySQL MIN() Function

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

The following is the basic syntax of MIN() function in MySQL:

SELECT MIN ( DISTINCT aggregate_expression)

FROM table_name(s)

[WHERE conditions];

Parameter explanation

This function uses the following parameters:

aggregate_expression: It is the required expression. It specifies the column or expression name from which the minimum

value will be returned.

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.

MySQL MIN() Function Example

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:

mysql> SELECT MIN(income) AS Minimum_Income FROM employees;

Output

The above query produces the result of minimum values in all rows. After execution, we will get the output as below:

2. MySQL MIN() Function with WHERE Clause

The WHERE clause allows us to filter the result from the selected records. The following statement finds the minimum
income in all rows from the employee table and WHERE clause specifies all those rows whose emp_age column is greater than

or equal to 32 and less than or equal to 40.

mysql> SELECT MIN(income) AS Minimum_Income

FROM employees

WHERE emp_age >= 32 AND emp_age <= 40;

Output

The above statement will get the output as below:


3. MySQL MIN() Function with GROUP BY Clause

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-

ployee table for each emp_age group.

mysql> SELECT emp_age, MIN(income) AS Minimum_Income

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:

4. MySQL MIN() Function with HAVING Clause

The HAVING clause is always used with the GROUP BY clause to filter the records from the table. For example, the be-
low statement returns the minimum income of all employees, grouping them based on their city and returns the result whose

MIN(income)>150000.

1. mysql> SELECT city, MIN(income) AS Minimum_Income

2. FROM employees

3. GROUP BY city

4. HAVING MIN(income) > 150000;

Output
This statement will return the output as below:

5. MySQL MIN() Function with DISTINCT Clause

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

then returns the minimum value:

mysql> SELECT emp_name, city, MIN(DISTINCT income) AS Minimum_Income

FROM employees

GROUP BY city;

Output

This statement will give the output as below:

MySQL MAX() Function

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

customer from your table.


Syntax

The following is the basic syntax of MAX() function in MySQL:

SELECT MAX(DISTINCT aggregate_expression)

FROM table_name(s)

[WHERE conditions];

Parameter Explanation

This function uses the following parameters:

Aggregate_expression: It is the required expression. It specifies the column, expression, or formula from which the maximum

value will be returned.

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.

MySQL MAX() Function Example

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:

mysql> SELECT MAX(income) AS "Maximum Income" FROM employees;

Output
The above query produces the result of maximum values in all rows. After execution, we will get the output as below:

2. MySQL MAX() Function with WHERE Clause

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.

mysql> SELECT MAX(income) AS "Maximum_Income"

FROM employees

WHERE emp_age > 35;

Output

The above statement will get the output as below:

3. MySQL MAX() Function with GROUP BY Clause

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

from the employee table for each emp_age group.

1. mysql> SELECT emp_age, MAX(income) AS "Maximum Income"

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

whose MAX(income) >= 200000.

mysql> SELECT city, MAX(income) AS "Maximum Income"

FROM employees

GROUP BY city

HAVING MAX(income) >= 200000;

Output

This statement will return the output as below:

5. MySQL MAX() Function with DISTINCT Clause

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

returns the maximum value:

mysql> SELECT city, MAX(DISTINCT income) AS "Maximum Income"


FROM employees

GROUP BY city;

Output

This statement will give the output as below:

6. MySQL MAX() Function in Subquery Example

Sometimes it is required to use the subquery for returning the maximum value in the table. In that case, we use the following

query:

mysql> SELECT * FROM employees WHERE

emp_age = (SELECT MAX(emp_age) FROM employees);

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.

The following are the rules to use subqueries:

o Subqueries should always use in parentheses.

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 If we use a subquery in a set function, it cannot be immediately enclosed in a set function.

The following are the advantages of using subqueries:

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.

MySQL Subquery Syntax

The following is the basic syntax to use the subquery in MySQL: History of Java

SELECT column_list (s) FROM table_name

WHERE column_name OPERATOR

(SELECT column_list (s) FROM table_name [WHERE])

MySQL Subquery Example

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:

SELECT emp_name, city, income FROM employees

WHERE emp_id IN (SELECT emp_id FROM employees);

This query will return the following output:

MySQL Subquery with Comparison Operator

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

WHERE emp_id IN (SELECT emp_id FROM employees

WHERE income > 350000);

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-

come using a subquery.

SELECT emp_name, city, income FROM employees

WHERE income = (SELECT MAX(income) FROM employees);

It will give the output where we can see two employees detail who have maximum income.

MySQL Subquery with IN or NOT-IN Operator

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

both tables as follows:

SELECT Name, City FROM student

WHERE City NOT IN (

SELECT City FROM student2 WHERE City='Los Angeles');

After execution, we can see that the result contains the student details not belonging to Los Angeles City.

MySQL Subquery in the FROM Clause

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

this table as a derived table, inline views, or materialized subquery.

The following subquery returns the maximum, minimum, and average number of items in the order table:

SELECT Max(items), MIN(items), FLOOR(AVG(items))

FROM

(SELECT order_id, COUNT(order_id) AS items FROM orders

GROUP BY order_date) AS Student_order_detail;


It will give the output as follows:

MySQL Correlated Subqueries

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.

SELECT emp_name, city, income

FROM employees emp WHERE income > (

SELECT AVG(income) FROM employees WHERE city = emp.city);

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.

MySQL Subqueries with EXISTS or NOT EXISTS

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 -

erwise, it returns false.

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.

SELECT name, occupation, age FROM customer C

WHERE EXISTS (SELECT * FROM Orders O

WHERE C.cust_id = O.cust_id);

This statement uses NOT EXISTS operator that returns the customer details who have not placed an order.

SELECT name, occupation, age FROM customer C

WHERE NOT EXISTS (SELECT * FROM Orders O

WHERE C.cust_id = O.cust_id);

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:

SELECT * FROM customer C WHERE ROW(cust_id, occupation) = (

SELECT order_id, order_date FROM Orders O WHERE C.cust_id = O.cust_id);

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

empty set, which can be shown in the below image:

MySQL Subqueries with ALL, ANY, and SOME

We can use a subquery which is followed by the keyword ALL, ANY, or SOME after a comparison operator. The following are the

syntax to use subqueries with ALL, ANY, or SOME:

1. operand comparison_operator ANY (subquery)

2. operand comparison_operator ALL (subquery)

3. operand comparison_operator SOME (subquery)


The ALL keyword compares values with the value returned by a subquery. Therefore, it returns TRUE if the comparison is TRUE

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 -

ample explains it more clearly:

SELECT cust_id, name FROM customer WHERE

cust_id > ANY (SELECT cust_id FROM Orders);

We will get the output as follows:

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 -

query. For example:

SELECT cust_id, name FROM customer WHERE

cust_id > ALL (SELECT cust_id FROM Orders);

We can see the output as below:

You might also like