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

SQL Cheat Sheet ? – Your Ultimate Guide to Querying Data!

SQL (Structured Query Language) is a standardized language for managing data in relational databases, allowing users to execute queries, retrieve, insert, update, and delete records. MySQL is a popular open-source RDBMS that supports various operations and is commonly used with PHP for web applications. The document also covers SQL commands, including Data Definition Language (DDL) and Data Manipulation Language (DML), as well as creating databases, tables, and views.

Uploaded by

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

SQL Cheat Sheet ? – Your Ultimate Guide to Querying Data!

SQL (Structured Query Language) is a standardized language for managing data in relational databases, allowing users to execute queries, retrieve, insert, update, and delete records. MySQL is a popular open-source RDBMS that supports various operations and is commonly used with PHP for web applications. The document also covers SQL commands, including Data Definition Language (DDL) and Data Manipulation Language (DML), as well as creating databases, tables, and views.

Uploaded by

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

Introduction to SQL

SQL (Structured Query Language) is a database computer


language designed for managing data in relational database
management systems (RDBMS).

SQL, is a standardized computer language that was originally


developed by IBM for querying, altering and defining relational
databases, using declarative statements.
What can SQL do?
 SQL can execute queries against a database
 SQL can retrieve data from a database
 SQL can insert records in a database
 SQL can update records in a database
 SQL can delete records from a database
 SQL can create new databases
 SQL can create new tables in a database
 SQL can create stored procedures in a database
 SQL can create views in a database
 SQL can set permissions on tables, procedures, and views

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 fr om
multiple tables for the end-users

Data Definition Language (DDL)

The Data Definition Language (DDL) manages table and index


structure. The most basic items of DDL are the CREATE, ALTER,
RENAME and DROP statements:

 CREATE creates an object (a table, for example) in the database.


 DROP deletes an object in the database, usually irretrievably.
 ALTER modifies the structure an existing object in various
ways—for example, adding a column to an existing table.

Data Manipulation Language (DML)

The Data Manipulation Language (DML) is the subset of SQL used


to add, update and delete data.

The acronym CRUD refers to all of the major functions that need
to be implemented in a relational database application to consider
it complete. Each letter in the acronym can be mapped to a
standard SQL statement:

Operation SQ Description
L
Create INSERT INTO inserts new data
into a database
Read (Retrieve) SELECT extracts data from a
database
Update UPDATE updates data in a database
Delete (Destroy) DELETE deletes data from a
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.
1. CREATE DATABASE [IF NOT EXISTS] database_name
2. [CHARACTER SET charset_name]
3. [COLLATE collation_name];
CREATE DATABASE employeesdb;

To show databases:
SHOW DATABASES;
To use databases:
USE emplyeedb;
CREATE TABLE
The CREATE TABLE statement is used to create a table in a database.
Syntax:

column_name1 data_type,
column_name2 data_type,
column_name3 data_type,

CREATE TABLE CUSTOMER


(
CustomerId int IDENTITY(1,1) PRIMARY KEY,
CustomerNumber int NOT NULL UNIQUE, LastName varchar(50) NOT
NULL, FirstName varchar(50) NOT NULL, AreaCode int NULL,
Address varchar(50) NULL,
Phone varchar(50) NULL,
)
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 INTO table_name ( field1, field2,...fieldN )
2. VALUES
3. ( value1, value2,...valueN );

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


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

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.
1. UPDATE table_name
2. SET column_name1 = new-value1,
3. column_name2=new-value2, ...
4. [WHERE Clause]

e.g
1. UPDATE trainer
2. SET email = '[email protected]'
3. WHERE course_name = 'Java';

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.
1. DELETE FROM table_name WHERE condition;

e.g. DELETE FROM Employees WHERE emp_id=107;

MySQL SELECT Statement


The SELECT statement in MySQL is used to fetch data from one or
more tables.
1. SELECT field_name1, field_name 2,... field_nameN
2. FROM table_name1, table_name2...
3. [WHERE condition]
4. [GROUP BY field_name(s)]
5. [HAVING condition]
6. [ORDER BY field_name(s)]
7. [OFFSET M ][LIMIT N];

e.g. SELECT * FROM employee_detail;

The ORDER BY Keyword


If you want the data to appear in a specific order you need to use the
“order by” keyword. Example:

SELECT DISTINCT

In a table, some of the columns may contain duplicate values.


This is not a problem, however, sometimes you will want to list
only the different (distinct) values in a table.

The DISTINCT keyword can be used to return only

distinct (different) values. The syntax is as follows:


Example:

The WHERE Clause

The WHERE clause is used to extract only those records that

fulfill a specified criterion. The syntax is as follows:

select <column_names>

Example:

Operators
With the WHERE clause, the following operators can be used:

Operat Description
or
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETW Between an inclusive range
EEN
LIKE Search for a pattern
IN If you know the exact value you want to return for at least
one of the columns
Examples:

LIKE Operator

The LIKE operator is used to search for a

specified pattern in a column. Syntax:

SELECT column_name(s)

Example:

IN Operator

The IN operator allows you to specify multiple

values in a WHERE clause. Syntax:

SELECT column_name(s)

BETWEEN Operator

The BETWEEN operator selects a range of data between two


values. The values can be numbers, text, or dates.

Syntax:
SELECT column_name(s)

Alias

You can give a table or a column another name by using an alias.


This can be a good thing to do if you have very long or complex
table names or column names.

An alias name could be anything, but usually it is short.

SELECT column_name(s)

Alias Syntax for Columns:

MySQL Constraints
Constraints are used to limit the type of data that can go into a table.
Constraints can be specified when a table is created (with the CREATE
TABLE statement) or after the table is created (with the ALTER TABLE
statement).
Here are the most important constraints:
 PRIMARY KEY
 NOT NULL
 UNIQUE
 FOREIGN KEY
 CHECK
 DEFAULT
 IDENTITY
1)PRIMARY KEY

The PRIMARY KEY constraint uniquely identifies each record in a database


table.
CREATE TABLE [CUSTOMER] (
CustomerId int IDENTITY(1,1) PRIMARY KEY,
CustomerNumber int NOT NULL UNIQUE, LastName varchar(50) NOT
NULL, FirstName varchar(50) NOT NULL, AreaCode int NULL,
Address varchar(50) NULL, Phone varchar(50) NULL,
)

2)FOREIGN KEY
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
SCHOOL:

CLASS:

3)NOT NULL / Required Columns

The NOT NULL constraint enforces a column to NOT accept NULL values.

The NOT NULL constraint enforces a field to always contain a


value. This means that you cannot insert a new record, or update
a record without adding a value to this field.
CREATE TABLE [CUSTOMER] (
CustomerId int IDENTITY(1,1) PRIMARY KEY,
CustomerNumber int NOT NULL UNIQUE, LastName varchar(50) NOT
NULL, FirstName varchar(50) NOT NULL, AreaCode int NULL,
Address varchar(50) NULL, Phone varchar(50) NULL,
)

4)UNIQUE

The UNIQUE constraint uniquely identifies each record in a


database table. The UNIQUE and PRIMARY KEY constraints both
provide a guarantee for uniqueness for a column or set of columns.
CREATE TABLE [CUSTOMER] (
CustomerId int IDENTITY(1,1) PRIMARY KEY,
CustomerNumber int NOT NULL UNIQUE, LastName varchar(50) NOT
NULL, FirstName varchar(50) NOT NULL, AreaCode int NULL,
Address varchar(50) NULL,
)

5)CHECK

The CHECK constraint is used to limit the value range that can be placed in
a column.

If you define a CHECK constraint on a single column it allows


only certain values for this column.
CREATE TABLE [CUSTOMER] (
CustomerId int IDENTITY(1,1) PRIMARY KEY,
CustomerNumber int NOT NULL UNIQUE
CHECK(CustomerNumber>0), LastName varchar(50) NOT NULL,
FirstName varchar(50) NOT NULL, AreaCode int NULL,
Address varchar(50) NULL, Phone varchar(50) NULL,
)

6)DEFAULT

The DEFAULT constraint is used to insert a default value into a column.


The default value will be added to all new records, if no other value is
specified.
CREATE TABLE [CUSTOMER] (
CustomerId int IDENTITY(1,1) PRIMARY KEY,
CustomerNumber int NOT NULL UNIQUE, LastName varchar(50) NOT
NULL, FirstName varchar(50) NOT NULL, Country varchar(20)
DEFAULT 'Norway', AreaCode int NULL,
Address varchar(50) NULL, Phone varchar(50) NULL,
)

ALTER TABLE

The ALTER TABLE statement is used to add, delete, or modify columns in


an existing table.

To add a column in a table, use the following syntax:

To delete a column in a table, use the following syntax (notice that


some database systems don't allow deleting a column):

To change the data type of a column in a table, use the following syntax:

INSERT INTO
The INSERT INTO statement is used to insert a new row in a table. It is
possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will be
inserted, only their values:

Example:

'California', '11111111')

The second form specifies both the column names and the values to be
inserted:

This form is recommended! Example:

UPDATE
The UPDATE statement is used to update existing records in a table. The
syntax is as follows:

SET column1=value, column2=value2,...


WHERE some_column=some_value
DELETE
The DELETE statement is used to delete rows in a table.

Syntax:

DELETE FROM table_name


WHERE some_column=some_value

Delete All Rows:


It is possible to delete all rows in a table without deleting the table. This means
that the table structure, attributes, and indexes will be intact:

Views in SQL
o Views in SQL are considered as a virtual table. A view also contains
rows and columns.
o To create the view, we can select the fields from one or more tables
present in the database.
o A view can either have specific rows based on certain condition or all
the rows of a table.
Sample table:
Student_Detail

STU_ID NAME ADDRESS

1 Stephan Delhi
2 Kathrin Noida

3 David Ghaziabad

4 Alina Gurugram

Student_Marks

STU_ID NAME MARKS AGE

1 Stephan 97 19

2 Kathrin 86 21

3 David 74 18

4 Alina 90 20

5 John 96 18

1. Creating view
A view can be created using the CREATE VIEW statement. We can
create a view from a single table or multiple tables.
Syntax:

1. CREATE VIEW view_name AS


2. SELECT column1, column2.....
3. FROM table_name
4. WHERE condition;
2. Creating View from a single table
In this example, we create a View named DetailsView from the table
Student_Detail.
Query:
1. CREATE VIEW DetailsView AS
2. SELECT NAME, ADDRESS
3. FROM Student_Details
4. WHERE STU_ID < 4;
Just like table query, we can query the view to view the data.

1. SELECT * FROM DetailsView;


Output:

NAME ADDRESS

Stephan Delhi

Kathrin Noida

David Ghaziabad

3. Creating View from multiple tables


View from multiple tables can be created by simply include multiple
tables in the SELECT statement.
In the given example, a view is created named MarksView from two
tables Student_Detail and Student_Marks.
Query:

1. CREATE VIEW MarksView AS


2. SELECT Student_Detail.NAME, Student_Detail.ADDRESS, Student_M
arks.MARKS
3. FROM Student_Detail, Student_Mark
4. WHERE Student_Detail.NAME = Student_Marks.NAME;
To display data of View MarksView
1. SELECT * FROM MarksView;
NAME ADDRESS MARKS

Stephan Delhi 97

Kathrin Noida 86

David Ghaziabad 74

Alina Gurugram 90

4. Deleting View
A view can be deleted using the Drop View statement.
Syntax

1. DROP VIEW view_name;


Example:
If we want to delete the View MarksView, we can do this as
1. DROP VIEW MarksView;

MySQL JOIN
As the name shows, JOIN means to combine something. In case of
SQL, JOIN means "to combine two or more tables".
In MySQL, JOIN clause is used to combine the records from two or
more tables in a database.
Types of MySQL JOIN
1. INNER JOIN
2. LEFT JOIN
3. RIGHT JOIN
4. FULL JOIN
Sample Table
EMPLOYEE

EMP_ID EMP_NAME CITY SALARY AGE

1 Angelina Chicago 200000 30

2 Robert Austin 300000 26

3 Christian Denver 100000 42

4 Kristen Washington 500000 29

5 Russell Los angels 200000 36

6 Marry Canada 600000 48

PROJECT

PROJECT_NO EMP_ID DEPARTMENT

101 1 Testing

102 2 Development

103 3 Designing

104 4 Development
1. INNER JOIN
In SQL, INNER JOIN selects records that have matching values in both
tables as long as the condition is satisfied. It returns the combination of
all rows from both the tables where the condition satisfies.
Syntax

1. SELECT table1.column1, table1.column2, table2.column1,....


2. FROM table1
3. INNER JOIN table2
4. ON table1.matching_column = table2.matching_column;
Query

1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


2. FROM EMPLOYEE
3. INNER JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

2. LEFT JOIN
The SQL left join returns all the values from left table and the matching
values from the right table. If there is no matching join value, it will
return NULL.
Syntax
1. SELECT table1.column1, table1.column2, table2.column1,....
2. FROM table1
3. LEFT JOIN table2
4. ON table1.matching_column = table2.matching_column;
Query

1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


2. FROM EMPLOYEE
3. LEFT JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

Russell NULL

Marry NULL

3. RIGHT JOIN
In SQL, RIGHT JOIN returns all the values from the values from the
rows of right table and the matched values from the left table. If there is
no matching in both tables, it will return NULL.
Syntax
1. SELECT table1.column1, table1.column2, table2.column1,....
2. FROM table1
3. RIGHT JOIN table2
4. ON table1.matching_column = table2.matching_column;
Query

1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


2. FROM EMPLOYEE
3. RIGHT JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

4. FULL JOIN
In SQL, FULL JOIN is the result of a combination of both left and right
outer join. Join tables have all the records from both tables. It puts
NULL on the place of matches not found.
Syntax

1. SELECT table1.column1, table1.column2, table2.column1,....


2. FROM table1
3. FULL JOIN table2
4. ON table1.matching_column = table2.matching_column;
Query

1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


2. FROM EMPLOYEE
3. FULL JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

Russell NULL

Marry NULL

Views

Views are virtual table for easier access to data stored in multiple tables.
Syntax for creating a View:

Syntax for using a View:


Example:

We use the SCHOOL and CLASS tables as an example for our


View. We want to create a View that lists all the existing schools and
the belonging classes.

We create the VIEW using the CREATE VIEW command:

SCHOOL.SchoolName,

1. CREATE [OR REPLACE] VIEW view_name AS


2. SELECT columns
3. FROM tables
4. [WHERE conditions];

5. CREATE VIEW trainer AS


6. SELECT course_name, trainer
7. FROM courses;

1. SELECT * FROM view_name;


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:
1. ALTER VIEW view_name AS
2. SELECT columns
3. FROM table
4. WHERE conditions;
Example:
The following example will alter the already created VIEW name "trainer" by
adding a new column.
1. ALTER VIEW trainer AS
2. SELECT id, course_name, trainer
3. FROM courses;
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:
1. DROP VIEW [IF EXISTS] view_name;

SQL Aggregate Functions


o SQL aggregation function is used to perform the calculations on multiple
rows of a single column of a table. It returns a single value.
o It is also used to summarize the data.
Types of SQL Aggregation Function

1. COUNT FUNCTION
o COUNT function is used to Count the number of rows in a database
table. It can work on both numeric and non-numeric data types.
o COUNT function uses the COUNT(*) that returns the count of all the
rows in a specified table. COUNT(*) considers duplicate and Null.
Syntax
1. COUNT(*)
2. or
3. COUNT( [ALL|DISTINCT] expression )
Sample table:

PRODUCT COMPANY QTY RATE COST

Item1 Com1 2 10 20

Item2 Com2 3 25 75

Item3 Com1 2 30 60
Item4 Com3 5 10 50

Item5 Com2 2 20 40

Item6 Cpm1 3 25 75

Item7 Com1 5 30 150

Item8 Com1 3 10 30

Item9 Com2 2 25 50

Item10 Com3 4 30 120

PRODUCT_MAST
Example: COUNT()
1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
Output:
10
Example: COUNT with WHERE
1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
3. WHERE RATE>=20;
Output:
7
Example: COUNT() with DISTINCT
1. SELECT COUNT(DISTINCT COMPANY)
2. FROM PRODUCT_MAST;
Output:
3
Example: COUNT() with GROUP BY
1. SELECT COMPANY, COUNT(*)
2. FROM PRODUCT_MAST
3. GROUP BY COMPANY;
Output:
Com1 5
Com2 3
Com3 2
Example: COUNT() with HAVING
1. SELECT COMPANY, COUNT(*)
2. FROM PRODUCT_MAST
3. GROUP BY COMPANY
4. HAVING COUNT(*)>2;
Output:
Com1 5
Com2 3
2. SUM Function
Sum function is used to calculate the sum of all selected columns. It works on
numeric fields only.
Syntax
1. SUM()
2. or
3. SUM( [ALL|DISTINCT] expression )
Example: SUM()
1. SELECT SUM(COST)
2. FROM PRODUCT_MAST;
Output:
670
Example: SUM() with WHERE
1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3;
Output:
320
Example: SUM() with GROUP BY
1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3
4. GROUP BY COMPANY;
Output:
Com1 150
Com2 170
Example: SUM() with HAVING
1. SELECT COMPANY, SUM(COST)
2. FROM PRODUCT_MAST
3. GROUP BY COMPANY
4. HAVING SUM(COST)>=170;
Output:
Com1 335
Com3 170
3. AVG function
The AVG function is used to calculate the average value of the numeric type.
AVG function returns the average of all non-Null values.
Syntax
1. AVG()
2. or
3. AVG( [ALL|DISTINCT] expression )
Example:
1. SELECT AVG(COST)
2. FROM PRODUCT_MAST;
Output:
67.00
4. MAX Function
MAX function is used to find the maximum value of a certain column. This
function determines the largest value of all selected values of a column.
Syntax
1. MAX()
2. or
3. MAX( [ALL|DISTINCT] expression )
Example:
1. SELECT MAX(RATE)
2. FROM PRODUCT_MAST;
30
5. MIN Function
MIN function is used to find the minimum value of a certain column. This
function determines the smallest value of all selected values of a column.
Syntax
1. MIN()
2. or
3. MIN( [ALL|DISTINCT] expression )
Example:
1. SELECT MIN(RATE)
2. FROM PRODUCT_MAST;
Output:
10
SET Operators in MySQL
SET operators are special type of operators which are used to combine the
result of two queries.
Operators covered under SET operators are:
1. UNION
2. UNION ALL
3. INTERSECT
4. MINUS
There are certain rules which must be followed to perform operations using
SET operators in SQL. Rules are as follows:
1. The number and order of columns must be the same.
2. Data types must be compatible.
Let us see each of the SET operators in more detail with the help of examples.
All the examples will be written using the MySQL database.
Consider we have the following tables with the given data.

ID Name Department Salary Year_of_Experience

1 Aakash Singh Development 72000 2

2 Abhishek Pawar Production 45000 1

3 Pranav Deshmukh HR 59900 3

4 Shubham Mahale Accounts 57000 2


5 Sunil Kulkarni Development 87000 3

6 Bhushan Wagh R&D 75000 2

7 Paras Jaiswal Marketing 32000 1

Table 1: t_employees

Table 2: t2_employees

ID Name Department Salary Year_of_Experience

1 Prashant Wagh R&D 49000 1

2 Abhishek Pawar Production 45000 1

3 Gautam Jain Development 56000 4

4 Shubham Mahale Accounts 57000 2

5 Rahul Thakur Production 76000 4

6 Bhushan Wagh R&D 75000 2

7 Anand Singh Marketing 28000 1

Table 3: t_students

ID Name Hometown Percentage Favourite_Subject

1 Soniya Jain Udaipur 89 Physics

2 Harshada Sharma Kanpur 92 Chemistry


3 Anuja Rajput Jaipur 78 History

4 Pranali Singh Nashik 88 Geography

5 Renuka Deshmukh Panipat 90 Biology

6 Swati Kumari Faridabad 93 English

7 Prachi Jaiswal Gurugram 96 Hindi

Table 4: t2_students

ID Name Hometown Percentage Favourite_Subject

1 Soniya Jain Udaipur 89 Physics

2 Ishwari Dixit Delhi 86 Hindi

3 Anuja Rajput Jaipur 78 History

4 Pakhi Arora Surat 70 Sanskrit

5 Renuka Deshmukh Panipat 90 Biology

6 Jayshree Patel Pune 91 Maths

7 Prachi Jaiswal Gurugram 96 Hindi

1. UNION:
o UNION will be used to combine the result of two select statements.
o Duplicate rows will be eliminated from the results obtained after
performing the UNION operation.
Example 1:
Write a query to perform union between the table t_employees and the table
t2_employees.
Query:
1. mysql> SELECT *FROM t_employees UNION SELECT *FROM t2_emp
loyees;
Here, in a single query, we have written two SELECT queries. The first
SELECT query will fetch the records from the t_employees table and perform
a UNION operation with the records fetched by the second SELECT query
from the t2_employees table.
You will get the following output:

ID Name Department Salary Year_of_Experience

1 Aakash Singh Development 72000 2

2 Abhishek Pawar Production 45000 1

3 Pranav Deshmukh HR 59900 3

4 Shubham Mahale Accounts 57000 2

5 Sunil Kulkarni Development 87000 3

6 Bhushan Wagh R&D 75000 2

7 Paras Jaiswal Marketing 32000 1

1 Prashant Wagh R&D 49000 1

3 Gautam Jain Development 56000 4

5 Rahul Thakur Production 76000 4

7 Anand Singh Marketing 28000 1

Since we have performed union operation between both the tables, so only
the records from the first and second table are displayed except for the
duplicate records.
Example 2:
Write a query to perform union between the table t_students and the table
t2_students.
Query:
1. mysql> SELECT *FROM t_students UNION SELECT *FROM t2_studen
ts;
Here, in a single query, we have written two SELECT queries. The first
SELECT query will fetch the records from the t_students table and perform a
UNION operation with the records fetched by the second SELECT query from
the t2_students table.
You will get the following output:

ID Name Department Salary Year_of_Experience

1 Soniya Jain Udaipur 89 Physics

2 Harshada Sharma Kanpur 92 Chemistry

3 Anuja Rajput Jaipur 78 History

4 Pranali Singh Nashik 88 Geography

5 Renuka Deshmukh Panipat 90 Biology

6 Swati Kumari Faridabad 93 English

7 Prachi Jaiswal Gurugram 96 Hindi

2 Ishwari Dixit Delhi 86 Hindi

4 Pakhi Arora Surat 70 Sanskrit

6 Jayshree Patel Pune 91 Maths

Since we have performed union operation between both the tables, so only
the records from the first and second table are displayed except for the
duplicate records.
2. UNION ALL
o This operator combines all the records from both the queries.
o Duplicate rows will be not be eliminated from the results obtained after
performing the UNION ALL operation.
Example 1:
Write a query to perform union all operation between the table t_employees
and the table t2_employees.
Query:
1. mysql> SELECT *FROM t_employees UNION ALL SELECT *FROM t2
_employees;

ID Name Department Salary Year_of_Experience

1 Aakash Singh Development 72000 2

2 Abhishek Pawar Production 45000 1

3 Pranav Deshmukh HR 59900 3

4 Shubham Mahale Accounts 57000 2

5 Sunil Kulkarni Development 87000 3

6 Bhushan Wagh R&D 75000 2

7 Paras Jaiswal Marketing 32000 1

1 Prashant Wagh R&D 49000 1

2 Abhishek Pawar Production 45000 1

3 Gautam Jain Development 56000 4

4 Shubham Mahale Accounts 57000 2

5 Rahul Thakur Production 76000 4


6 Bhushan Wagh R&D 75000 2

7 Anand Singh Marketing 28000 1

Here, in a single query, we have written two SELECT queries. The first
SELECT query will fetch the records from the t_employees table and perform
UNION ALL operation with the records fetched by the second SELECT query
from the t2_employees table.
You will get the following output:
Since we have performed union all operation between both the tables, so all
the records from the first and second table are displayed, including the
duplicate records.
Example 2:
Write a query to perform union all operation between the table t_students and
the table t2_students.
Query:
1. mysql> SELECT *FROM t_students UNION ALL SELECT *FROM t2_st
udents;
Here, in a single query, we have written two SELECT queries. The first
SELECT query will fetch the records from the t_students table and perform
UNION ALL operation with the records fetched by the second SELECT query
from the t2_students table.
You will get the following output:
ID Name Hometown Percentage Favourite_Subject

1 Soniya Jain Udaipur 89 Physics

2 Harshada Sharma Kanpur 92 Chemistry

3 Anuja Rajput Jaipur 78 History

4 Pranali Singh Nashik 88 Geography

5 Renuka Deshmukh Panipat 90 Biology

6 Swati Kumari Faridabad 93 English

7 Prachi Jaiswal Gurugram 96 Hindi

1 Soniya Jain Udaipur 89 Physics

2 Ishwari Dixit Delhi 86 Hindi

3 Anuja Rajput Jaipur 78 History

4 Pakhi Arora Surat 70 Sanskrit

5 Renuka Deshmukh Panipat 90 Biology

6 Jayshree Patel Pune 91 Maths

7 Prachi Jaiswal Gurugram 96 Hindi

Since we have performed union all operation between both the tables, so all
the records from the first and second table are displayed, including the
duplicate records.
3. INTERSECT:
o It is used to combine two SELECT statements, but it only returns the
records which are common from both SELECT statements.
Example 1:
Write a query to perform intersect operation between the table t_employees
and the table t2_employees.
Query:
1. mysql> SELECT *FROM t_employees INTERSECT SELECT *FROM t2
_employees;
Here, in a single query, we have written two SELECT queries. The first
SELECT query will fetch the records from the t_employees table and perform
INTERSECT operation with the records fetched by the second SELECT query
from the t2_employees table.
You will get the following output:

ID Name Hometown Percentage Favourite_Subject

2 Abhishek Pawar Production 45000 1

4 Shubham Mahale Accounts 57000 2

6 Bhushan Wagh R&D 75000 2

Since we have performed intersect operation between both the tables, so only
the common records from both the tables are displayed.

Example 2:
Write a query to perform intersect operation between the table t_students and
the table t2_students.
Query:
1. mysql> SELECT *FROM t_students INTERSECT SELECT *FROM t2_s
tudents;
Here, in a single query, we have written two SELECT queries. The first
SELECT query will fetch the records from the t_students table and perform a
UNION operation with the records fetched by the second SELECT query from
the t2_students table.
You will get the following output:
ID Name Hometown Percentage Favourite_Subject

1 Soniya Jain Udaipur 89 Physics

3 Anuja Rajput Jaipur 78 History

5 Renuka Deshmukh Panipat 90 Biology

7 Prachi Jaiswal Gurugram 96 Hindi

Since we have performed intersect operation between both the tables, so only
the common records from both the tables are displayed.
4. MINUS
o It displays the rows which are present in the first query but absent in the
second query with no duplicates.
Example 1:
Write a query to perform a minus operation between the table t_employees
and the table t2_employees.
Query:
1. mysql> SELECT *FROM t_employees MINUS SELECT *FROM t2_emp
loyees;
Here, in a single query, we have written two SELECT queries. The first
SELECT query will fetch the records from the t_employees table and perform
MINUS
operation with the records fetched by the second SELECT query from the
t2_employees table.

ID Name Department Salary Year_of_Experience

1 Aakash Singh Development 72000 2

3 Pranav Deshmukh HR 59900 3


5 Sunil Kulkarni Development 87000 3

7 Paras Jaiswal Marketing 32000 1

You will get the following output:


Since we have performed Minus operation between both the tables, so only
the unmatched records from both the tables are displayed.
Example 2:
Write a query to perform a minus operation between the table t_students and
the table t2_students.
Query:
1. mysql> SELECT *FROM t_students MINUS SELECT *FROM t2_studen
ts;
Here, in a single query, we have written two SELECT queries. The first
SELECT query will fetch the records from the t_employees table and perform
a UNION operation with the records fetched by the second SELECT query
from the t2_employees table.
You will get the following output:

ID Name Hometown Percentage Favourite_Subject

2 Harshada Sharma Kanpur 92 Chemistry

4 Pranali Singh Nashik 88 Geography

6 Swati Kumari Faridabad 93 English

Since we have performed a minus operation between both the tables, so only
the Unmatched records from both the tables are displayed.

Triggers

A database trigger is code that is automatically executed in


response to certain events on a particular table in a database.

Syntax for creating a Trigger:

The Trigger will automatically be executed when data is inserted,


updated or deleted in the table as specified in the Trigger header.

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.

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:
1. CREATE TRIGGER trigger_name
2. (AFTER | BEFORE) (INSERT | UPDATE | DELETE)
3. ON table_name FOR EACH ROW
4. BEGIN
5. --variable declarations
6. --trigger code
7. END;
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:
1. CREATE TABLE employee(
2. name varchar(45) NOT NULL,
3. occupation varchar(35) NOT NULL,
4. working_date date,
5. working_hours varchar(10)
6. );
Next, execute the below statement to fill the records into the employee table:
1. INSERT INTO employee VALUES
2. ('Robin', 'Scientist', '2020-10-04', 12),
3. ('Warner', 'Engineer', '2020-10-04', 10),
4. ('Peter', 'Actor', '2020-10-04', 13),
5. ('Marco', 'Doctor', '2020-10-04', 14),
6. ('Brayden', 'Teacher', '2020-10-04', 12),
7. ('Antonio', 'Business', '2020-10-04', 11);

8. DELIMITER //
9. mysql> Create Trigger before_insert_empworkinghours
10. BEFORE INSERT ON employee FOR EACH ROW
11. BEGIN
12. IF NEW.working_hours < 0 THEN SET NEW.working_hours = 0;
13. END IF;
14. END //

1. INSERT INTO employee VALUES


2. ('Markus', 'Former', '2020-10-08', 14);
3.
4. mysql> INSERT INTO employee VALUES
5. ('Alexander', 'Actor', '2020-10-012', -13);

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:
1. mysql> SHOW TRIGGERS;

You might also like