0% found this document useful (0 votes)
64 views

Unit 3 PHP

MySQL is an open-source relational database management system that is supported by Oracle Corporation. It allows users to organize data into tables, rows, columns, and indexes to find relevant information quickly. MySQL uses the client-server model, where clients make requests to the central MySQL server, which processes the requests and returns responses. The CREATE DATABASE and CREATE TABLE statements are used to construct databases and tables in MySQL, while the INSERT statement adds new records of data to tables.

Uploaded by

William Kuga
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views

Unit 3 PHP

MySQL is an open-source relational database management system that is supported by Oracle Corporation. It allows users to organize data into tables, rows, columns, and indexes to find relevant information quickly. MySQL uses the client-server model, where clients make requests to the central MySQL server, which processes the requests and returns responses. The CREATE DATABASE and CREATE TABLE statements are used to construct databases and tables in MySQL, while the INSERT statement adds new records of data to tables.

Uploaded by

William Kuga
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Unit 3

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

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.

What is MySQL?
MySQL is currently the most popular database management system software used for
managing the relational database. It is open-source database software, which is
supported by Oracle Company. It is fast, scalable, and easy to use database management
system in comparison with Microsoft SQL Server and Oracle Database. It is commonly
used in conjunction with PHP scripts for creating powerful and dynamic server-side or
web-based enterprise applications.

It is developed, marketed, and supported by MySQL AB, a Swedish company, and


written in C programming language and C++ programming language. The official
pronunciation of MySQL is not the My Sequel; it is My Ess Que Ell. However, you can
pronounce it in your way. Many small and big companies use MySQL. MySQL supports
many Operating Systems like Windows, Linux, MacOS, etc. with C, C++, and Java
languages.

MySQL is a Relational Database Management System (RDBMS) software that provides


many things, which are as follows:

o It allows us to implement database operations on tables, rows, columns, and indexes.


o It defines the database relationship in the form of tables (collection of rows and columns),
also known as relations.
o It provides the Referential Integrity between rows or columns of various tables.
o It allows us to updates the table indexes automatically.
o It uses many SQL queries and combines useful information from multiple tables for the
end-users.

How MySQL Works?


MySQL follows the working of Client-Server Architecture. This model is designed for the
end-users called clients to access the resources from a central computer known as a server
using network services. Here, the clients make requests through a graphical user interface
(GUI), and the server will give the desired output as soon as the instructions are matched.
The process of MySQL environment is the same as the client-server model.

The core of the MySQL database is the MySQL Server. This server is available as a separate
program and responsible for handling all the database instructions, statements, or
commands. The working of MySQL database with MySQL Server are as follows:

1. MySQL creates a database that allows you to build many tables to store and manipulate
data and defining the relationship between each table.
2. Clients make requests through the GUI screen or command prompt by using specific SQL
expressions on MySQL.
3. Finally, the server application will respond with the requested expressions and produce
the desired result on the client-side.

A client can use any MySQL GUI. But, it is making sure that your GUI should be lighter and
user-friendly to make your data management activities faster and easier. Some of the
most widely used MySQL GUIs are MySQL Workbench, SequelPro, DBVisualizer, and the
Navicat DB Admin Tool. Some GUIs are commercial, while some are free with limited
functionality, and some are only compatible with MacOS. Thus, you can choose the GUI
according to your needs.
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.

MySQL Workbench
It is a visual database designing or GUI tool used to work with database architects,
developers, and Database Administrators. This visual tool supports SQL development,
data modeling, data migration, and comprehensive administration tools for server
configuration, user administration, backup, and many more. It allows us to create new
physical data models, E-R diagrams, and SQL development (run queries, etc.).

The SQL CREATE DATABASE statement is used to create new SQL database.
Syntax:
Basic syntax of CREATE DATABASE statement is as follows:
CREATE DATABASE DatabaseName;
Always database name should be unique within the RDBMS.
Example:
If you want to create new database <testDB>, then CREATE DATABASE statement would
be as follows:
SQL> CREATE DATABASE testDB;
Make sure you have admin privilege before creating any database. Once a database is
created, you can check it in
the list of databases as follows:
SQL> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| AMROOD |
| TUTORIALSPOINT |
| mysql |
| orig |
| test |
| testDB |
+--------------------+

SQL CREATE Table


Creating a basic table involves naming the table and defining its columns and each
column's data type.
The SQL CREATE TABLE statement is used to create a new table.
Syntax:
Basic syntax of CREATE TABLE statement is as follows:
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
CREATE TABLE is the keyword telling the database system what you want to do. In this
case, you want to createa new table. The unique name or identifier for the table follows
the CREATE TABLE statement.
Then in brackets comes the list defining each column in the table and what sort of data
type it is. The syntax becomes clearer with an example below.
A copy of an existing table can be created using a combination of the CREATE TABLE
statement and the SELECT statement. You can check complete details at Create Table
Using another Table.
Create Table Using another Table
A copy of an existing table can be created using a combination of the CREATE TABLE
statement and the SELECT statement.
The new table has the same column definitions. All columns or specific columns can be
selected.
When you create a new table using existing table, new table would be populated using
existing values in the old table.
Syntax:
The basic syntax for creating a table from another table is as follows:
CREATE TABLE NEW_TABLE_NAME AS
SELECT [ column1, column2...columnN ]
FROM EXISTING_TABLE_NAME
[ WHERE ]
Here, column1, column2...are the fields of existing table and same would be used to
create fields of new table.
Example:
Following is an example, which would create a table SALARY using CUSTOMERS table
and having fields
customer ID and customer SALARY:
SQL> CREATE TABLE SALARY AS
SELECT ID, SALARY
FROM CUSTOMERS;
This would create new table SALARY, which would have the following records:
+----+----------+
| ID | SALARY |
+----+----------+
| 1 | 2000.00 |
| 2 | 1500.00 |
| 3 | 2000.00 |
| 4 | 6500.00 |
| 5 | 8500.00 |
| 6 | 4500.00 |
| 7 | 10000.00 |
+----+----------+
Example:
Following is an example, which creates a CUSTOMERS table with ID as primary key and
NOT NULL are the constraints showing that these fileds can not be NULL while creating
records in this table:
SQL> CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
You can verify if your table has been created successfully by looking at the message
displayed by the SQL server,
otherwise you can use DESC command as follows:
SQL> DESC CUSTOMERS;
+---------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------------+------+-----+---------+-------+
| ID | int(11) | NO | PRI | | |
| NAME | varchar(20) | NO | | | |
| AGE | int(11) | NO | | | |
| ADDRESS | char(25) | YES | | NULL | |
| SALARY | decimal(18,2) | YES | | NULL | |
+---------+---------------+------+-----+---------+-------+
Now, you have CUSTOMERS table available in your database which you can use to store
required information related to customers.

INSERT Query
The SQL INSERT INTO Statement is used to add new rows of data to a table in the
database.
Syntax:
There are two basic syntaxes of INSERT INTO statement as follows:
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)]
VALUES (value1, value2, value3,...valueN);
Here, column1, column2,...columnN are the names of the columns in the table into
which you want to insert data.
You may not need to specify the column(s) name in the SQL query if you are adding
values for all the columns of the table. But make sure the order of the values is in the
same order as the columns in the table. The SQL INSERT INTO syntax would be as
follows:
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);
Example:
Following statements would create six records in CUSTOMERS table:
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (3, 'kaushik', 23, 'Kota', 2000.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (6, 'Komal', 22, 'MP', 4500.00 );

You can create a record in CUSTOMERS table using second syntax as follows
INSERT INTO CUSTOMERS
VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );
All the above statements would produce the following records in CUSTOMERS table:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

SELECT Query
SQL SELECT Statement is used to fetch the data from a database table which returns
data in the form of result table. These result tables are called result-sets.
Syntax:
The basic syntax of SELECT statement is as follows:
SELECT column1, column2, columnN FROM table_name;
Here, column1, column2...are the fields of a table whose values you want to fetch. If you
want to fetch all the fields available in the field, then you can use the following syntax:
SELECT * FROM table_name;
Example:
Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example, which would fetch ID, Name and Salary fields of the customers
available in CUSTOMERS table:
SQL> SELECT ID, NAME, SALARY FROM CUSTOMERS;
This would produce the following result:
+----+----------+----------+
| ID | NAME | SALARY |
| 1 | Ramesh | 2000.00 |
| 2 | Khilan | 1500.00 |
| 3 | kaushik | 2000.00 |
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+
If you want to fetch all the fields of CUSTOMERS table, then use the following query:
SQL> SELECT * FROM CUSTOMERS;
This would produce the following result:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Sorting (Order By)


The ORDER BY clause is used to sort the data in ascending or descending order, based on one
ormore columns. Some database sorts query results in ascending order by default.
Syntax:
The basic syntax of ORDER BY clause is as follows:
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
You can use more than one column in the ORDER BY clause. Make sure whatever column you are
using to sort, that column should be in column-list.

The following table contains the items bought by several people last week:

cust_id item total price


1 balloon 1
2 apple 3
1 apple 4
1 pillow 25
3 plastic bag 1

Order By
Let's see the following query:

SELECT * FROM shopping ORDER BY total_price

The output will be:


cust_id item total price
1 balloon 1
3 plastic bag 1
2 apple 3
1 apple 4
1 pillow 25

as you can see the fiels have been ordered by the price. The default order is ascending. If you want
to specify how the data is ordered, write either ASC or DESC at the end of your query

Example:

SELECT * FROM shopping ORDER BY total_price DESC

will give the same table, but starting with the pillow.

GROUP BY CLAUSE
The SQL GROUP BY clause is used in collaboration with the SELECT statement to
arrange identical data into groups.
The GROUP BY clause follows the WHERE clause in a SELECT statement and
precedes the ORDER BY clause.
Syntax:
The basic syntax of GROUP BY clause is given below. The GROUP BY clause must
follow the conditions in the WHERE clause and must precede the ORDER BY
clause if one is used.
SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2

The group by statement, as said before, is especially useful for aggregating, meaning to apply some
function. Let's see an example:
SELECT cust_id, SUM(total_price) FROM shopping GROUP BY cust_id

This query returns the total amount of money spent by each customer during all their shoppings. The
table returned looks like this:

cust_id SUM(total_price)
1 30
2 3
3 1

The way you have to understand the query is that we compute the sum of all amounts for each
customer. This is expressed by the GROUP BY cust_id. Now, if we would try to do this for each
product. This would correspond to the total money gained per product. The query looks like this:

SELECT item, SUM(total_price) FROM shopping GROUP BY item

This query returns the following table:

item SUM(total_price)
apple 7
balloon 1
pillow 25
plastic bag 1

Update Query
The SQL UPDATE Query is used to modify the existing records in a table.
You can use WHERE clause with UPDATE query to update selected rows,
otherwise all the rows would be affected.

Syntax:
The basic syntax of UPDATE query with WHERE clause is as follows:
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
You can combine N number of conditions using AND or OR operators.

Example:
Consider the CUSTOMERS table having the following records:

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example, which would update ADDRESS for a customer whose ID is 6:
SQL> UPDATE CUSTOMERS

SET ADDRESS = 'Pune'


WHERE ID = 6;
Now, CUSTOMERS table would have the following records:

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | Pune | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
If you want to modify all ADDRESS and SALARY column values in CUSTOMERS table,
you do not need to use WHERE clause and UPDATE query would be as follows:
SQL> UPDATE CUSTOMERS
SET ADDRESS = 'Pune', SALARY = 1000.00;

Now, CUSTOMERS table would have the following records:

+----+----------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+---------+
| 1 | Ramesh | 32 | Pune | 1000.00 |
| 2 | Khilan | 25 | Pune | 1000.00 |
| 3 | kaushik | 23 | Pune | 1000.00 |
| 4 | Chaitali | 25 | Pune | 1000.00 |
| 5 | Hardik | 27 | Pune | 1000.00 |
| 6 | Komal | 22 | Pune | 1000.00 |
| 7 | Muffy | 24 | Pune | 1000.00 |

+----+----------+-----+---------+---------+
Delete Query in MySQL
The SQL DELETE Query is used to delete the existing records from a table.
You can use WHERE clause with DELETE query to delete selected rows, otherwise
all the records would be deleted.

Syntax:
The basic syntax of DELETE query with WHERE clause is as follows:

DELETE FROM table_name WHERE [condition];


You can combine N number of conditions using AND or OR operators.
Example:
Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |

+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |

| 4 | Chaitali | 25 | Mumbai | 6500.00 |


| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |

+----+----------+-----+-----------+----------+

Following is an example, which would DELETE a customer, whose ID is 6:

SQL> DELETE FROM CUSTOMERS


WHERE ID = 6;
Now, CUSTOMERS table would have the following records:

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
If you want to DELETE all the records from CUSTOMERS table, you do not need to
use WHERE clause and
DELETE query would be as follows:

SQL> DELETE FROM CUSTOMERS;


Now, CUSTOMERS table would not have any record.

MySQL - Useful Functions


Here is the list of all important MySQL functions. Each function has been explained along
with suitable example.
 MySQL Group By Clause − The MySQL GROUP BY statement is used
along with the SQL aggregate functions like SUM to provide means of grouping
the result dataset by certain database table column(s).
 MySQL IN Clause − This is a clause, which can be used along with any
MySQL query to specify a condition.
 MySQL BETWEEN Clause − This is a clause, which can be used along
with any MySQL query to specify a condition.
 MySQL DATE and Time Functions − Complete list of MySQL Date and
Time related functions.
 MySQL Numeric Functions − Complete list of MySQL functions required to
manipulate numbers in MySQL.
 MySQL String Functions − Complete list of MySQL functions required to
manipulate strings in MySQL.

MySQL IN Clause
IN -> The IN operator is used to compare a value to a list of literal values that have
been specified.
SQL> SELECT * FROM CUSTOMERS WHERE AGE IN ( 25, 27 );
+----+----------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+---------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
+----+----------+-----+---------+---------+

MySQL BETWEEN CLAUSE


BETWEEN -> The BETWEEN operator is used to search for values that are within a set of
values, given the minimum value and the maximum value.
SQL> SELECT * FROM CUSTOMERS WHERE AGE BETWEEN 25 AND 27;
+----+----------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+---------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |

MySQL - Date and Time Functions


MySQL provides a set of functions using which you can manipulate date and time values.
Following are the MySQL date time functions −

Sr.No. Name & Description

1 ADDDATE()

This function adds two given dates

2 DATE()

This function extracts the date part of a date or datetime expression

3 DATEDIFF()

This function subtracts two dates

4 DAY()
Synonym for DAYOFMONTH()

5 DAYOFMONTH()

This function returns the day of the month (1-31)

7 DAYOFYEAR()

This function returns the day of the year (1-366)

8 HOUR() e

This function Extracts the hour

9 MINUTE()

This function returns the minute from the argument

10 MONTH()

This function returns the month from the date passed

11 NOW()

This function returns the current date and time

12 SECOND()

This function returns the second (0-59)

13 TIME()

This function extracts the time portion of the expression passed

14 WEEKDAY()

This function returns the weekday index

15 YEAR()

This function returns the year

16 DATE_FORMAT()

This function formats the given date as specified.


MySQL - Numeric Functions and Operators

MySQL - Numeric Functions


MySQL numeric functions are used primarily for numeric manipulation and/or
mathematical calculations. The following table details the numeric functions that are
available in the MySQL.

Sr.No. Name & Description

1 ABS()

Returns the absolute value of numeric expression.

7 CEILING()

Returns the smallest integer value that is not less than passed numeric expression

13 EXP()

Returns the base of the natural logarithm (e) raised to the power of passed numeric
expression.

14 FLOOR()

Returns the largest integer value that is not greater than passed numeric
expression.

21 MOD()

Returns the remainder of one expression by diving by another expression.

22 PI()

Returns the value of pi

23 POW()

Returns the value of one expression raised to the power of another expression

26 RAND()
Returns a random floating-point value with in the range 0 to 1.0.

27 ROUND()

Returns numeric expression rounded to an integer. Can be used to round an


expression to a number of decimal points

28 SIGN()

Returns the sign of the given number.

30 SQRT()

Returns the non-negative square root of numeric expression.

32 TRUNCATE()

Returns numeric exp1 truncated to exp2 decimal places. If exp2 is 0, then the result
will have no decimal point.

SQL JOIN
SQL Join is used to fetch data from two or more tables, which is joined to appear as single
set of data. It is used for combining column from two or more tables by using values
common to both tables.
JOIN Keyword is used in SQL queries for joining two or more tables. Minimum required
condition for joining table, is (n-1) where n, is number of tables. A table can also join to
itself, which is known as, Self Join.

Types of JOIN
Following are the types of JOIN that we can use in SQL:

 Inner
 Outer
 Left
 Right
Cross JOIN or Cartesian Product
This type of JOIN returns the cartesian product of rows from the tables in Join. It will return
a table which consists of records which combines each row from the first table with each
row of the second table.
Cross JOIN Syntax is,
SELECT column-name-list
FROM
table-name1 CROSS JOIN table-name2;

Example of Cross JOIN


Following is the class table,

ID NAME

1 Abhi

2 Adam

4 Alex

and the class_info table,

ID Address

1 DELHI

2 MUMBAI

3 CHENNAI

Cross JOIN query will be,


SELECT * FROM
class CROSS JOIN class_info;
The resultset table will look like,

ID NAME ID Address

1 Abhi 1 DELHI

2 Adam 1 DELHI

4 Alex 1 DELHI

1 Abhi 2 MUMBAI

2 Adam 2 MUMBAI

4 Alex 2 MUMBAI

1 Abhi 3 CHENNAI

2 Adam 3 CHENNAI

4 Alex 3 CHENNAI

As you can see, this join returns the cross product of all the records present in both the
tables.

INNER Join or EQUI Join


This is a simple JOIN in which the result is based on matched data as per the equality
condition specified in the SQL query.
Inner Join Syntax is,
SELECT column-name-list FROM
table-name1 INNER JOIN table-name2
WHERE table-name1.column-name = table-name2.column-name;

Example of INNER JOIN


Consider a class table,

ID NAME

1 Abhi

2 Adam

3 Alex

4 Anu

and the class_info table,

ID Address

1 DELHI

2 MUMBAI

3 CHENNAI

Inner JOIN query will be,


SELECT * from class INNER JOIN class_info where class.id = class_info.id;
The resultset table will look like,

ID NAME ID Address
1 Abhi 1 DELHI

2 Adam 2 MUMBAI

3 Alex 3 CHENNAI

OUTER JOIN
Outer Join is based on both matched and unmatched data. Outer Joins subdivide further
into,

1. Left Outer Join


2. Right Outer Join
3. Full Outer Join

LEFT Outer Join


The left outer join returns a resultset table with the matched data from the two tables and
then the remaining rows of the left table and null from the right table's columns.
Syntax for Left Outer Join is,
SELECT column-name-list FROM
table-name1 LEFT OUTER JOIN table-name2
ON table-name1.column-name = table-name2.column-name;
To specify a condition, we use the ON keyword with Outer Join.
Example of Left Outer Join
Here is the class table,

ID NAME

1 Abhi

2 Adam
3 Alex

4 Anu

5 Ashish

and the class_info table,

ID Address

1 DELHI

2 MUMBAI

3 CHENNAI

7 NOIDA

8 PANIPAT

Left Outer Join query will be,


SELECT * FROM class LEFT OUTER JOIN class_info ON (class.id = class_info.id);
The resultset table will look like,

ID NAME ID Address

1 Abhi 1 DELHI

2 Adam 2 MUMBAI
3 Alex 3 CHENNAI

4 Anu null null

5 Ashish null null

RIGHT Outer Join


The right outer join returns a resultset table with the matched data from the two tables
being joined, then the remaining rows of the right table and null for the
remaining left table's columns.
Syntax for Right Outer Join is,
SELECT column-name-list FROM
table-name1 RIGHT OUTER JOIN table-name2
ON table-name1.column-name = table-name2.column-name;

Example of Right Outer Join


Once again the class table,

ID NAME

1 Abhi

2 Adam

3 Alex

4 Anu

5 Ashish
and the class_info table,

ID Address

1 DELHI

2 MUMBAI

3 CHENNAI

7 NOIDA

8 PANIPAT

Right Outer Join query will be,


SELECT * FROM class RIGHT OUTER JOIN class_info ON (class.id = class_info.id);
The resultant table will look like,

ID NAME ID Address

1 abhi 1 DELHI

2 adam 2 MUMBAI

3 alex 3 CHENNAI

null null 7 NOIDA

null null 8 PANIPAT


Full Outer Join
The full outer join returns a resultset table with the matched data of two table then
remaining rows of both left table and then the right table.
Syntax of Full Outer Join is,
SELECT column-name-list FROM
table-name1 FULL OUTER JOIN table-name2
ON table-name1.column-name = table-name2.column-name;

Example of Full outer join is,


The class table,

ID NAME

1 Abhi

2 Adam

3 Alex

4 Anu

5 Ashish

and the class_info table,

ID Address

1 DELHI

2 MUMBAI
3 CHENNAI

7 NOIDA

8 PANIPAT

Full Outer Join query will be like,


SELECT * FROM class FULL OUTER JOIN class_info ON (class.id = class_info.id);
The resultset table will look like,

ID NAME ID Address

1 abhi 1 DELHI

2 adam 2 MUMBAI

3 alex 3 CHENNAI

4 anu Null null

5 ashish Null null

null null 7 NOIDA

null null 8 PANIPAT


MySQL Transaction
A transaction in MySQL is a sequential group of statements, queries, or operations such
as select, insert, update or delete to perform as a one single work unit that can be
committed or rolled back. If the transaction makes multiple modifications into the
database, two things happen:

o Either all modification is successful when the transaction is committed.


o Or, all modifications are undone when the transaction is rollback.

In other words, a transaction cannot be successful without completing each operation


available in the set. It means if any statement fails, the transaction operation cannot
produce results.

A transaction in MySQL starts with the first executable SQL statement and ends when it
finds a commit or rolled back either explicitly or implicitly. It explicitly uses COMMIT or
ROLLBACK statement and implicitly when a DDL statement is used.

Let us understand the concept of a transaction through the following explanation.

by considering a banking database. Suppose a bank customer wants to transfer money


from one account to another account. We can achieve this by using the SQL statements
that will be divided into the following steps:

o First, it is required to check the availability of the requested amount in the first account.
o Next, if the amount is available, deduct it from the first account. Then, update the first
account.
o Finally, deposit the amount in the second account. Then update the second account to
complete the transaction.
o If any of the above processes fails, the transaction will be rolled back into its previous state.

Properties of Transaction
The transaction contains mainly four properties, which referred to as ACID property. Now,
we are going to discuss the ACID property in detail. The ACID property stands for:

1. Atomicity
2. Consistency
3. Isolation
4. Durability

Atomicity: This property ensures that all statements or operations within the transaction
unit must be executed successfully. Otherwise, if any operation is failed, the whole
transaction will be aborted, and it goes rolled back into their previous state. It includes
features:

o COMMIT statement.
o ROLLBACK statement.
o Auto-commit setting.
o Operational data from the INFORMATION_SCHEMA tables.

Consistency: This property ensures that the database changes state only when a
transaction will be committed successfully. It is also responsible for protecting data from
crashes. It includes features:

o InnoDB doublewrite buffer.


o InnoDB crash recovery.

Isolation: This property guarantees that each operation in the transaction unit operated
independently. It also ensures that statements are transparent to each other. It includes
features:

o SET ISOLATION LEVEL statement.


o Auto-commit setting.
o The low-level details of InnoDB locking.

Durability: This property guarantees that the result of committed transactions persists
permanently even if the system crashes or failed. It includes features:

o Write buffer in a storage device.


o Battery-backed cache in a storage device.
o Configuration option innodb_file_per_table.
o Configuration option innodb_flush_log_at_trx_commit.
o Configuration option sync_binlog.
MySQL Transaction Statement
MySQL control transactions with the help of the following statement:

o MySQL provides a START TRANSACTION statement to begin the transaction. It also offers
a "BEGIN" and "BEGIN WORK" as an alias of the START TRANSACTION.
o We will use a COMMIT statement to commit the current transaction. It allows the database
to make changes permanently.
o We will use a ROLLBACK statement to roll back the current transaction. It allows the
database to cancel all changes and goes into their previous state.
o We will use a SET auto-commit statement to disable/enable the auto-commit mode for
the current transaction. By default, the COMMIT statement executed automatically. So if
we do not want to commit changes automatically, use the below statement:

1. SET autocommit = 0;
2. OR,
3. SET autocommit = OFF:

Again, use the below statement to enable auto-commit mode:

1. SET autocommit = 1;
2. OR,
3. SET autocommit = ON:
MySQL Transaction Example
Suppose we have two tables named "employees" and "Orders" that contains the
following data:

Table: employees
Table: orders

COMMIT Example
If we want to use a transaction, it is required to break the sql statements into logical
portions. After that, we can define whether the data should be committed or rollback.

The following steps illustrate to create a transaction:

1. Begin the transaction using the START TRANSACTION statement.


2. Then, select maximum income among the employee.
3. Add a new record to the employee table.
4. Add a new record into the order table.
5. Use the COMMIT statement to complete the transaction.

Below are the commands that perform the above operations:

1. -- 1. Start a new transaction


2. START TRANSACTION;
3. -- 2. Get the highest income
4. SELECT @income:= MAX(income) FROM employees;
5. -- 3. Insert a new record into the employee table
6. INSERT INTO employees(emp_id, emp_name, emp_age, city, income)
7. VALUES (111, 'Alexander', 45, 'California', 70000);
8. -- 4. Insert a new record into the order table
9. INSERT INTO Orders(order_id, prod_name, order_num, order_date)
10. VALUES (6, 'Printer', 5654, '2020-01-10');
11. -- 5. Commit changes
12. COMMIT;

ROLLBACK Example
We can understand the rollback transaction with the help of the following illustration.
First, open the MySQL command prompt and log into the database server using the
password. Next, we have to select a database.

Suppose our database contains the "Orders" table. Now, the following are the scripts that
perform the rollback operations:

1. -- 1. Start a new transaction


2. START TRANSACTION;
3. -- 2. Delete data from the order table
4. DELETE FROM Orders;

After the execution of the above statement, we will get the output as below that shows
all the records from the table Orders were successfully deleted.

Now, we need to open a separate session of MySQL database server and execute the
below statement to verify the data in Orders table:
1. SELECT * FROM Orders;

It will give the output as below.

Although we have made changes in the first session, we still can see the records are
available in the table. It is because the changes are not permanent until we have not
executed the COMMIT or ROLLBACK statement in the first session.

Therefore if we want to make changes permanent, use the COMMIT statement. Otherwise,
execute the ROLLBACK statement to roll back the changes in the first session.

1. -- 3. Rollback changes
2. ROLLBACK;
3. -- 4. Verify the records in the first session
4. SELECT * FROM Orders;

After the successful execution, it will produce the following result where we can see that
the change has been rolled back.
Statements that cannot be a rollback in using MySQL Transaction.

MySQL Transaction cannot be able to roll back all statements. For example, these
statements include DDL (Data Definition Language) commands such as CREATE, ALTER,
or DROP database as well as CREATE, UPDATE, or DROP tables or stored routines. We
have to make sure that when we design our transaction, these statements do not include.

MySQL - INDEXES
A database index is a data structure that improves the speed of operations in a table.
Indexes can be created using one or more columns, providing the basis for both rapid
random lookups and efficient ordering of access to records.
While creating index, it should be taken into consideration which all columns will be used
to make SQL queries and create one or more indexes on those columns.
Practically, indexes are also a type of tables, which keep primary key or index field and
a pointer to each record into the actual table.
The users cannot see the indexes, they are just used to speed up queries and will be
used by the Database Search Engine to locate records very fast.
The INSERT and UPDATE statements take more time on tables having indexes,
whereas the SELECT statements become fast on those tables. The reason is that while
doing insert or update, a database needs to insert or update the index values as well.

Simple and Unique Index


You can create a unique index on a table. A unique index means that two rows cannot
have the same index value. Here is the syntax to create an Index on a table.
CREATE UNIQUE INDEX index_name ON table_name ( column1,
column2,...);
You can use one or more columns to create an index.
For example, we can create an index on tutorials_tbl using tutorial_author.
CREATE UNIQUE INDEX AUTHOR_INDEX ON tutorials_tbl (tutorial_author)
You can create a simple index on a table. Just omit the UNIQUE keyword from the query
to create a simple index. A Simple index allows duplicate values in a table.
If you want to index the values in a column in a descending order, you can add the
reserved word DESC after the column name.
mysql> CREATE UNIQUE INDEX AUTHOR_INDEX ON tutorials_tbl
(tutorial_author DESC)

ALTER command to add and drop INDEX


There are four types of statements for adding indexes to a table −
 ALTER TABLE tbl_name ADD PRIMARY KEY (column_list) − This statement
adds a PRIMARY KEY, which means that the indexed values must be unique and
cannot be NULL.
 ALTER TABLE tbl_name ADD UNIQUE index_name (column_list) − This
statement creates an index for which the values must be unique (except for the
NULL values, which may appear multiple times).
 ALTER TABLE tbl_name ADD INDEX index_name (column_list) − This adds
an ordinary index in which any value may appear more than once.
 ALTER TABLE tbl_name ADD FULLTEXT index_name (column_list) − This
creates a special FULLTEXT index that is used for text-searching purposes.
The following code block is an example to add index in an existing table.
mysql> ALTER TABLE testalter_tbl ADD INDEX (c);
You can drop any INDEX by using the DROP clause along with the ALTER command.
Try out the following example to drop the above-created index.
mysql> ALTER TABLE testalter_tbl DROP INDEX (c);
You can drop any INDEX by using the DROP clause along with the ALTER command.

ALTER Command to add and drop the PRIMARY KEY


You can add a primary key as well in the same way. But make sure the Primary Key
works on columns, which are NOT NULL.
The following code block is an example to add the primary key in an existing table. This
will make a column NOT NULL first and then add it as a primary key.
mysql> ALTER TABLE testalter_tbl MODIFY i INT NOT NULL;
mysql> ALTER TABLE testalter_tbl ADD PRIMARY KEY (i);
You can use the ALTER command to drop a primary key as follows −
mysql> ALTER TABLE testalter_tbl DROP PRIMARY KEY;
To drop an index that is not a PRIMARY KEY, you must specify the index name.
Displaying INDEX Information
You can use the SHOW INDEX command to list out all the indexes associated with a
table. The vertical-format output (specified by \G) often is useful with this statement, to
avoid a long line wraparound −
Try out the following example −
mysql> SHOW INDEX FROM table_name

You might also like