Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
10 views61 pages

MySQL Summary

The document provides an overview of data, databases, and their types, including distributed, relational, and NoSQL databases. It explains database normalization, RDBMS terminology, and introduces MySQL as an open-source relational database management system with various data types and commands. Additionally, it covers SQL commands such as SELECT, LIMIT, DISTINCT, WHERE, and logical operators for querying data.

Uploaded by

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

MySQL Summary

The document provides an overview of data, databases, and their types, including distributed, relational, and NoSQL databases. It explains database normalization, RDBMS terminology, and introduces MySQL as an open-source relational database management system with various data types and commands. Additionally, it covers SQL commands such as SELECT, LIMIT, DISTINCT, WHERE, and logical operators for querying data.

Uploaded by

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

Summary – Day 1

Data:

In simple words, data can be facts related to any object in consideration. For example, your
name, age, height, weight, etc. are some data related to you. A picture, image, file, pdf, etc.
can also be considered data.

Database:

A database is a systematic collection of data. They support electronic storage and


manipulation of data. Databases make data management easy.

Let us discuss a database example: An online telephone directory uses a database to store
data of people, phone numbers, and other contact details. Your electricity service provider
uses a database to manage billing, client-related issues, handle fault data, etc.

Let us also consider Facebook. It needs to store, manipulate, and present data related to
members, their friends, member activities, messages, advertisements, and a lot more. We can
provide a countless number of examples for the usage of databases.

Types of Databases:

• Distributed databases:

A distributed database is a type of database that has contributions from the


common database and information captured by local computers. In this type
of database system, the data is not in one place and is distributed at various
organizations.
• Relational databases:

This type of database defines database relationships in the form of tables. It is


also called Relational DBMS, which is the most popular DBMS type in the
market. Database example of the RDBMS system include MySQL, Oracle, and
Microsoft SQL Server database.

• Object-oriented databases:

This type of computers database supports the storage of all data types. The
data is stored in the form of objects. The objects to be held in the database
have attributes and methods that define what to do with the data. PostgreSQL
is an example of an object-oriented relational DBMS.

• Centralized database:

It is a centralized location, and users from different backgrounds can access


this data. This type of computers databases store application procedures that
help users access the data even from a remote location.

• Open-source databases:

This kind of database stored information related to operations. It is mainly used in


the field of marketing, employee relations, customer service, of databases.

• Cloud databases:

A cloud database is a database which is optimized or built for such a virtualized


environment. There are so many advantages of a cloud database, some of which can
pay for storage capacity and bandwidth. It also offers scalability on-demand, along
with high availability.

• Data warehouses:

Data Warehouse is to facilitate a single version of truth for a company for decision
making and forecasting. A Data warehouse is an information system that contains
historical and commutative data from single or multiple sources. Data Warehouse
concept simplifies the reporting and analysis process of the organization.

• NoSQL databases:

NoSQL database is used for large sets of distributed data. There are a few big data
performance problems that are effectively handled by relational databases. This type
of computers database is very efficient in analysing large-size unstructured data.
Database Normalization:

Normalization is a database design technique that reduces data redundancy and eliminates
undesirable characteristics like Insertion, Update and Deletion Anomalies. Normalization
rules divides larger tables into smaller tables and links them using relationships. The purpose
of Normalisation in SQL is to eliminate redundant (repetitive) data and ensure data is stored
logically.

Database Normal Forms:

• 1NF (First Normal Form)


o Each table cell should contain a single value.
o Each record needs to be unique.

• 2NF (Second Normal Form)


o Rule 1- Be in 1NF
o Rule 2- Single Column Primary Key that does not functionally dependant on
any subset of candidate key relation

• 3NF (Third Normal Form)


o Rule 1- Be in 2NF
o Rule 2- Has no transitive functional dependencies

• BCNF (Boyce-Codd Normal Form)


• 4NF (Fourth Normal Form)
• 5NF (Fifth Normal Form)
• 6NF (Sixth Normal Form)

RDBMS Terminology:

Nowadays, we use relational database management systems (RDBMS) to store and manage
huge volume of data. This is called relational database because all the data is stored into
different tables and relations are established using primary keys or other keys known as
Foreign Keys.

• A Relational Database Management System (RDBMS) is a software that −


• Enables you to implement a database with tables, columns and indexes.
• Guarantees the Referential Integrity between rows of various tables
• Updates the indexes automatically.
• Interprets an SQL query and combines information from various tables.

RDBMS Terminologies:

• Database − A database is a collection of tables, with related data.


• Table − A table is a matrix with data. A table in a database looks like a simple
spreadsheet.
• Column − One column (data element) contains data of one and the same kind, for
example the column postcode.
• Row − A row (= tuple, entry or record) is a group of related data, for example the
data of one subscription.
• Redundancy − Storing data twice, redundantly to make the system faster.
• Primary Key − A primary key is unique. A key value can not occur twice in one table.
With a key, you can only find one row.
• Foreign Key − A foreign key is the linking pin between two tables.
• Compound Key − A compound key (composite key) is a key that consists of multiple
columns, because one column is not sufficiently unique.
• Index − An index in a database resembles an index at the back of a book.
• Referential Integrity − Referential Integrity makes sure that a foreign key value always
points to an existing row

What is MySQL ?

MySQL is an open-source relational database management system. As with other relational


databases, MySQL stores data in tables made up of rows and columns. Users can define,
manipulate, control, and query data using Structured Query Language, more commonly
known as SQL.

Benefits:

• Ease of use
• Reliability
• Scalability
• Performance
• High availability
• Security
• Flexibility
Summary – Day 2

MySQL supports several standard SQL data types. Each column can contain only one data
type. In MySQL, data types are grouped in different categories:

• Numeric
• Date and time
• String
• Spatial
• JSON

MySQL String Data Types (Text Formats):

In MySQL, string data types usually store data as long strings of text, for example, feedback
or product description. Strings can consist of letters, numbers, or binary media files such as
images, photos, or audio files.

The MySQL string data types are divided into:

• TEXT
• BLOB
• CHAR and VARCHAR
• BINARY and VARBINARY
• ENUM
• SET

TEXT:
TEXT data type is used to store long-text strings to display information about the table
object, such as product descriptions, blog comments, etc. The storage size of the TEXT data
type varies from 1 byte to 4 GB. Unlike the numeric data types, you do not have to set a
length next to the TEXT data type in the table column. Moreover, TEXT values are not stored
in the server’s memory but use the disk instead. Therefore, the TEXT data types require +1
additional byte to retrieve data.

BLOB:

Unlike the TEXT data types, which are non-binary string data types, the BLOB data types are
binary strings. In MySQL, the BLOB data type represents a binary large object and can be
used to store binary media data, such as audio or video links, images, or files.

The BLOB data types, including TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB, have a
variable length, i.e. additional bytes (from 1 to 4) are required to store a value length in the
column. For example, the maximum size of data to be stored is as follows:

• TINYBLOB => 255 bytes + 1 byte


• BLOB => 65535 + 2 bytes
• MEDIUMBLOB => 16777215 + 3 bytes
• LONGBLOB => 4294967295 + 4 bytes

When comparing BLOB and TEXT data types, it should be noted that BLOB is defined as
numeric values, while TEXT – as character strings having a character set. This should be taken
into account when comparing and sorting information.

CHAR and VARCHAR:

• In MySQL, the CHAR data types store non-binary strings with a fixed length that
reaches 255 characters, while the VARCHAR data types store non-binary strings with
a variable length having a maximum size of up to 65535 characters.
• For both data types, you need to set a size parameter in characters (in brackets) when
creating a column. The size parameter represents the column length for a CHAR data
type and the maximum column length for a VARCHAR data type. For example,
CHAR(3) refers to up to 3 characters for the column value.
• The main distinction between the CHAR and VARCHAR data types is a way of storing
data. CHAR adds spaces to values on the right to the specified length, for example,
CHAR(3) will be displayed as follows ‘table ‘. VARCHAR outputs the value as it is,
without any additional spaces – VARCHAR(3) will be displayed as ‘table’.
• It should be noted that when defining a datatype for a phone number in MySQL,
VARCHAR is more preferable to integers as sometimes there may be special symbols
or characters. In addition, VARCHAR simplifies validation.

BINARY and VARBINARY:

• Though CHAR and VARCHAR seem to be similar to BINARY and VARBINARY data
types, they have some differences. BINARY and VARBINARY store binary strings, and
length is measured in bytes.

ENUM:

• The MySQL ENUM data types are strings with enumeration values. ENUM allows you
to set a list of predefined values and then choose any of them. If you add an invalid
value that is not included in the list, you will get an empty string.
• For example, we want to create a table that will store information about the size of
women’s clothes: small, medium, and large. In the table, we will insert the size column
with the ENUM type. It means that this column will take only specified values.

MySQL Numeric Data Types (Number Formats):

MySQL supports numeric data types such as integers, decimals, and floating-point data
types:

• Integers represent numbers without fractions and can have SIGNED and UNSIGNED
attributes. Usually, they may be used for IDs or counting numbers.
• Decimals represent numbers with fractions and store exact numeric values in the
column. They can be signed and unsigned and are usually used for columns that
store monetary values. In the comparison with the floating-point numbers, decimals
are more accurate.
• Floating-point represent numbers with fractions but do not store exact numeric
values. They can be signed and unsigned. Floating-point numeric values use a
double-precision 64-bit format or a single-precision 32-bit format to store data. They
may lead to a loss of precision during arithmetic operations.

Integer:

Integer data types are numeric values without fractions. MySQL supports the following
integer data types:

• TINYINT
• SMALLINT
• INT
• MEDIUMINT
• BIGINT

They can be UNSIGNED, which allow only zero and positive numbers in a column, and
SIGNED, which store zero, positive, and negative numbers.

Boolean:

• The boolean data types can only accept either true or false values. In a binary format,
true refers to 1 and false – to 0. As a rule, they are used for logical operations.
• MySQL does not have a boolean (or bool) data type. Instead, it converts boolean
values into integer data types (TINYINT). When you create a table with a boolean data
type, MySQL outputs data as 0, if false, and 1, if true.

Float:

The Float data types represent single-precision approximate numeric values that require 4
bytes for storage.

Double:

The Double data types refer to the floating-point numeric data types and use 8 bytes to
store double-precision values. The syntax for the double data type is DOUBLE
PRECISION(m,d) where ‘m‘ is the total number of digits and ‘d‘ is the number of digits
following the decimal point. For example, DOUBLE(7,5) means that it will store a value with
seven digits and five decimals.

Decimal:

• The DECIMAL data type can be used to store exact and fixed numeric values. When
creating a table column, the syntax for the data type is DECIMAL(p,s) where ‘p‘ stands
for precision, the maximum number of digits, and ‘s‘ stands for scale, the number of
digits following the decimal.
• As a result, the main difference between float and double data types is precision
(from 0 to 23 for FLOAT, and from 24 to 53 for DOUBLE) and accuracy (up to
approximately 7 decimals for FLOAT, and up to approximately 15 decimals for
DOUBLE).
• To sum up, decimals are better to use for fixed amounts, such as monetary and
financial information (price, salary, etc,), while float and double – for approximate
calculations where rounding values might have a negative impact.

MySQL Date & Time Data Types:


MySQL Commands:

• DDL – Data Definition Language


• DQL – Data Query Language
• DML – Data Manipulation Language
• DCL – Data Control Language
• TCL – Transaction Control Language
Summary – Day 3

SELECT:

The SELECT statement in MySQL is used to fetch data from one or more tables. We can
retrieve records of all fields or specified fields that match specified criteria using this
statement. It can also work with various scripting languages such as PHP, Ruby, and many
more.

Syntax:

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

LIMIT:

The LIMIT clause is used in the SELECT statement to constrain the number of rows to return.
The LIMIT clause accepts one or two arguments. The values of both arguments must be zero
or positive integers.
Syntax:

In this syntax:

• The offset specifies the offset of the first row to return. The offset of the first row is 0,
not 1.
• The row_count specifies the maximum number of rows to return.

DISTINCT:

When querying data from a table, you may get duplicate rows. To remove these duplicate
rows, you use the DISTINCT clause in the SELECT statement.

Syntax:

• In this syntax, you specify one or more columns that you want to select distinct values
after the SELECT DISTINCT keywords.
• If you specify one column, the DISTINCT clause will evaluate the uniqueness of rows
based on the values of that column.
• However, if you specify two or more columns, the DISTINCT clause will use the values
of these columns to evaluate the uniqueness of the rows.

WHERE:

MySQL WHERE Clause is used with SELECT, INSERT, UPDATE and DELETE clause to filter the
results. It specifies a specific position where you have to do the operation.
Syntax:

There can be one condition or many conditions written with AND/OR clauses.

AND/OR:

In MySQL, you can use AND & OR condition both together with the SELECT, INSERT, UPDATE
and DELETE statement. While combine these conditions, you must be aware where to use
round brackets so that the database know the order to evaluate each condition.

Syntax:

IN:

The IN operator allows you to determine if a value matches any value in a list of values.

Syntax:

NOT IN:

The NOT operator negates the IN operator

Syntax:

The NOT IN operator returns one if the value doesn’t equal any value in the list. Otherwise, it
returns 0.
BETWEEN:

The BETWEEN operator is a logical operator that specifies whether a value is in a range or
not.

Syntax:

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.

ISNULL:

The ISNULL function takes one argument and tests whether that argument is NULL or not.
The ISNULL function returns 1 if the argument is NULL, otherwise, it returns 0.

Syntax:

IS NOT NULL:

The IS NOT NULL operator is used to test for non-empty values (NOT NULL values).

Syntax:
Wild Cards:

The wildcards in MySQL are characters that allow us to search complex data from the table
very easily and quickly. It works with string by substituting one or more characters and
produce the result after matching the string into the table.

MySQL uses wildcards in conjunction with the LIKE or NOT LIKE comparison operators. The
LIKE operator works with the WHERE clause to find the result for a specified pattern in a
column.

Types of wildcards:

Syntax:

ORDER BY:

When you use the SELECT statement to query data from a table, the order of rows in the
result set is unspecified. To sort the rows in the result set, you add the ORDER BY clause to
the SELECT statement.
Syntax:

In this syntax, you specify the one or more columns that you want to sort after the ORDER BY
clause.

The ASC stands for ascending and the DESC stands for descending. You use ASC to sort the
result set in ascending order and DESC to sort the result set in descending order respectively.
Summary – Day 4

CASE:

• MySQL CASE expression is a control flow structure that allows you to add if-else logic
to a query. Generally speaking, you can use the CASE expression anywhere that
allows a valid expression e.g., SELECT, WHERE and ORDER BY clauses.
• The CASE expression has two forms: simple CASE and searched CASE.

Simple case syntax:

• In this syntax, CASE matches the value with the value1, value2, etc., for equality and
return the corresponding result1, result2,… If the value does not equal to any value1,
value2, … CASE returns the result in the ELSE clause if the ELSE clause is specified.

Searched CASE syntax:

• In this syntax, the CASE evaluates expressions specified in the WHEN clauses. If an
expression evaluates to true. CASE returns the corresponding result in the THEN
clause. Otherwise, it returns the result specified in the ELSE clause. In case the ELSE
clause is not available, then the CASE expression returns NULL .
IFNULL:

• MySQL IFNULL function is one of the MySQL control flow functions that accepts two
arguments and returns the first argument if it is not NULL. Otherwise, the IFNULL
function returns the second argument.
• The two arguments can be literal values or expressions.
• Syntax:

• The IFNULL function returns expression_1 if expression_1 is not NULL ; otherwise, it


returns expression_2. The
• The IFNULL function returns a string or a numeric based on the context where it is
used.

✓ IFNULL(1,0) returns 1 because 1 is not NULL .


✓ IFNULL(' ',1) returns ' ' because the ' ' string is not NULL .
✓ IFNULL(NULL,'IFNULL function') returns IFNULL function string because the first
argument is NULL.

COALESCE:

• The COALESCE function takes a number of arguments and returns the first non-NULL
argument. In case all arguments are NULL, the COALESCE function returns NULL.
• Syntax:
• The IFNULL function takes two arguments and returns the first argument if it is not
NULL, otherwise, it returns the second argument.
• The IFNULL function works great with two arguments whereas the COALESCE
function works with n arguments. In case the number of arguments is two, both
functions are the same.
Summary – Day 5

GROUP BY:

• The GROUP BY clause groups a set of rows into a set of summary rows by values of
columns or expressions. The GROUP BY clause returns one row for each group. In
other words, it reduces the number of rows in the result set.
• The GROUP BY clause is an optional clause of the SELECT statement.

• In this syntax, you place the GROUP BY clause after the FROM and WHERE clauses.
After the GROUP BY keywords, you place is a list of comma-separated columns or
expressions to group rows.
• MySQL evaluates the GROUP BY clause after the FROM and WHERE clauses and
before the HAVING, SELECT, DISTINCT, ORDER BY and LIMIT clauses.
HAVING:

• The HAVING clause is used in the SELECT statement to specify filter conditions for a
group of rows or aggregates.
• The HAVING clause is often used with the GROUP BY clause to filter groups based on
a specified condition. If you omit the GROUP BY clause, the HAVING clause behaves
like the WHERE clause.

• The HAVING clause evaluates each group returned by the GROUP BY clause. If the
result is true, the row is included in the result set.
• Notice that the HAVING clause applies a filter condition to each group of rows, while
the WHERE clause applies the filter condition to each individual row.

SUM:

• The SUM() function is an aggregate function that allows you to calculate the sum of
values in a set.

• The DISTINCT option instructs the SUM() function to calculate the sum of only
distinct values in a set.

AVG:

• The MySQL AVG() function is an aggregate function that allows you to calculate the
average value of a set.

• You use the DISTINCT operator in the AVG function to calculate the average value of
the distinct values.
MIN:

• The MIN() function returns the minimum value in a set of values. The MIN() function
is very useful in some scenarios such as finding the smallest number, selecting the
least expensive product, or getting the lowest credit limit.

• In this syntax, the MIN() function accepts an expression which can be a column or a
valid expression that involves columns.

MAX:

• The MySQL MAX() function returns the maximum value in a set of values. The MAX()
function comes in handy in many cases such as finding the greatest number, the
most expensive product, and the largest payment from customers.

• If you add the DISTINCT operator, the MAX() function returns the maximum value of
distinct values, which is the same as the maximum value of all values. It means that
DISTINCT does not take any effects in the MAX() function.

COUNT:

• The COUNT() function is an aggregate function that returns the number of rows in a
table. The COUNT() function allows you to count all rows or only rows that match a
specified condition.
• The COUNT() function has three forms: COUNT(*), COUNT(expression) and
COUNT(DISTINCT expression).
• The COUNT(*) function returns the number of rows in a result set returned by
a SELECT statement.
• The COUNT(expression) returns the number of rows that do not contain NULL values
as the result of the expression.
• The COUNT(DISTINCT expression) returns the number of distinct rows that do not
contain NULL values as the result of the expression.
• The return type of the COUNT() function is BIGINT. The COUNT() function returns 0 if
there is no matching row found.
String Functions:

Date & Time Functions:

• NOW: Returns current date-time


• CURRENT_DATE: Returns today’s date
• CURRENT_TIME: Returns current time
• CURRENT_TIMESTAMP: Same as now
• YEAR: Returns year of the date
• QUARTER: Returns quarter of the date
• MONTH: Returns month number of the date
• DAY: Returns day number of the date
• WEEK: Returns week number of the date
• MONTHNAME: Returns name of the month from the date
• DAYNAME: : Returns name of the day from the date
• DAYOFWEEK: : Returns the position of the day in that week of the date
• HOUR: Returns the hour part of the date
• MINUTE: Returns the minute part of the date
• SECOND: Returns the second part of the date
• DATE_FORMAT: Used to format the date in any form
• DATE_ADD: Used to add/subtract the day/month/year/hour/minute/second
• DATEDIFF: Used to find the difference between the two dates in number of days
• TIMESTAMPDIFF: Used to find the difference between the two dates in
year/month/day/hour/minute/second form
Summary – Day 6

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 Constraints:

• Column Level Constraints: These constraints are applied only to the single column
that limits the type of particular column data.
• Table Level Constraints: These constraints are applied to the entire table that limits
the type of data for the whole table.

How to create the constraints ?


Types:

NOT NULL:

This constraint specifies that the column cannot have NULL or empty values. The below
statement creates a table with NOT NULL constraint.

UNIQUE:

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:

CHECK:

It controls the value in a particular column. It ensures that the inserted value in a column
must be satisfied with the given condition. In other words, it determines whether the value
associated with the column is valid or not with the given condition.

DEFAULT:

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.
PRIMARY KEY:

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.

ENUM:

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.

FOREIGN KEY:
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.

What is AUTO_INCREMENT ?

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.
Summary – Day 7

Joins:

• Joins are used to combine the data from multiple tables in the database.
• We can join the tables from same / different databases.
• The data types and the values must be same for the columns of the two tables we are
joining.

Types:

• Inner Join
• Left Join
• Right Join
• Full Outer Join
• Cross Join
• Self Join

Inner Join:
• The inner join clause compares each row from the first table with every row from the
second table.
• If values from both rows satisfy the join condition, the inner join clause creates a new
row whose column contains all columns of the two rows from both tables and
includes this new row in the result set. In other words, the inner join clause includes
only matching rows from both tables.

Left Join:

• The left join selects data starting from the left table. For each row in the left table, the
left join compares with every row in the right table.
• If the values in the two rows satisfy the join condition, the left join clause creates a
new row whose columns contain all columns of the rows in both tables and includes
this row in the result set.
• If the values in the two rows are not matched, the left join clause still creates a new
row whose columns contain columns of the row in the left table and NULL for
columns of the row in the right table.
• In other words, the left join selects all data from the left table whether there are
matching rows exist in the right table or not.
• In case there are no matching rows from the right table found, the left join uses
NULLs for columns of the row from the right table in the result set.

Right Join:

• The right join clause is similar to the left join clause except that the treatment of left
and right tables is reversed. The right join starts selecting data from the right table
instead of the left table.
• The right join clause selects all rows from the right table and matches rows in the left
table. If a row from the right table does not have matching rows from the left table,
the column of the left table will have NULL in the final result set.

Full Outer Join:

• The FULL OUTER JOIN combines the results of both left and right outer joins and
returns all (matched or unmatched) rows from the tables on both sides of the join
clause.
• In MySQL, we don’t have Full Outer Join keyword so we can use Union clause to do
full outer join.
• We can write full outer join in below manner.
o SELECT * FROM T1 LEFT JOIN T2 ON T1.C1 = T2.C2

UNION

SELECT * FROM T1 RIGHT JOIN T2 ON T1.C1 = T2.C2;


• Full outer join tis the combination of left and right joins.

Cross Join:

• Unlike the inner join, left join, and right join, the cross join clause does not have a join
condition.
• The cross join makes a Cartesian product of rows from the joined tables. The cross
join combines each row from the first table with every row from the right table to
make the result set.
• Suppose the first table has n rows and the second table has m rows. The cross join
that joins the tables will return nxm rows.
• The cross join is useful for generating planning data. For example, you can carry the
sales planning by using the cross join of customers, products, and years.

Self Join:

• A SELF JOIN is a join that is used to join a table with itself. In the previous sections,
we have learned about the joining of the table with the other tables using different
JOINS, such as INNER, LEFT, RIGHT, and CROSS JOIN. However, there is a need to
combine data with other data in the same table itself. In that case, we use Self Join.
• We can perform Self Join using table aliases. The table aliases allow us not to use the
same table name twice with a single statement. If we use the same table name more
than one time in a single query without table aliases, it will throw an error.
• The table aliases enable us to use the temporary name of the table that we are going
to use in the query. Let us understand the table aliases with the following
explanation.
Summary – Day 8

• DDL is an abbreviation of Data Definition Language.


• The DDL Commands in Structured Query Language are used to create and modify the
schema of the database and its objects. The syntax of DDL commands is predefined
for describing the data. The commands of Data Definition Language deal with how
the data should exist in the database.

Types:

• CREATE Command
• DROP Command
• ALTER Command
• TRUNCATE Command
• RENAME Command

CREATE:

• CREATE is a DDL command used to create databases, tables, triggers and other
database objects.
• Syntax to Create a Database:

• Syntax to create a new table:


DROP:

• DROP is a DDL command used to delete/remove the database objects from the SQL
database. We can easily remove the entire table, view, or index from the database
using this DDL command.
• Syntax to remove a database:

• Syntax to remove a table:

ALTER :

• ALTER is a DDL command which changes or modifies the existing structure of the
database, and it also changes the schema of database objects.
• We can also add and drop constraints of the table using the ALTER command.
• Below are the use-cases of alter table.

1. Add a column:

2. Drop a column:
3. Modify the column:

TRUNCATE:

• TRUNCATE is another DDL command which deletes or removes all the records from
the table.
• This command also removes the space allocated for storing the table records.

RENAME:

• RENAME is a DDL command which is used to change the name of the database table.
Summary – Day 9

DML Commands:

• DML is an abbreviation of Data Manipulation Language.


• The DML commands in Structured Query Language change the data present in the
SQL database. We can easily access, store, modify, update and delete the existing
records from the database using DML commands.

Types:

• INSERT
• UPDATE
• DELETE

INSERT:

• INSERT is another most important data manipulation command in Structured Query


Language, which allows users to insert data in database tables.

INSERT INTO TABLE_NAME ( column_Name1 , column_Name2 , column_Name3 , .... c


olumn_NameN ) VALUES (value_1, value_2, value_3, .... value_N ) ;

UPDATE:

• UPDATE is another most important data manipulation command in Structured Query


Language, which allows users to update or modify the existing data in database
tables.
• Here, 'UPDATE', 'SET', and 'WHERE' are the SQL keywords, and 'Table_name' is the
name of the table whose values you want to update.
• We can do updates on multiple columns and multiple rows in a table.

DELETE:

• DELETE is a DML command which allows SQL users to remove single or multiple
existing records from the database tables.
• This command of Data Manipulation Language does not delete the stored data
permanently from the database. We use the WHERE clause with the DELETE
command to select specific rows from the table.

TCL Commands:

• TCL stands for Transaction control language.


• A single unit of work in a database is formed after the consecutive execution of
commands is known as a transaction.
• There are certain commands present in SQL known as TCL commands that help the
user manage the transactions that take place in a database.
• COMMIT. ROLLBACK and SAVEPOINT are the most commonly used TCL commands
in MySQL.
• BEGIN / START TRANSACTION command is used to start the transaction.

COMMIT:

• COMMIT command in SQL is used to save all the transaction-related changes


permanently to the disk. Whenever DDL commands such as INSERT, UPDATE and
DELETE are used, the changes made by these commands are permanent only after
closing the current session.
• So before closing the session, one can easily roll back the changes made by the DDL
commands. Hence, if we want the changes to be saved permanently to the disk
without closing the session, we will use the commit command.
ROLLBACK:

• While carrying a transaction, we must create savepoints to save different parts of the
transaction. According to the user's changing requirements, he/she can roll back the
transaction to different savepoints.
• Consider a scenario: We have initiated a transaction followed by the table creation
and record insertion into the table. After inserting records, we have created a
savepoint INS. Then we executed a delete query, but later we thought that mistakenly
we had removed the useful record. Therefore in such situations, we have an option of
rolling back our transaction.
• In this case, we have to roll back our transaction using the ROLLBACK command to
the savepoint INS, which we have created before executing the DELETE query.

SAVEPOINT:

• We can divide the database operations into parts. For example, we can consider all
the insert related queries that we will execute consecutively as one part of the
transaction and the delete command as the other part of the transaction.
• Using the SAVEPOINT command in SQL, we can save these different parts of the
same transaction using different names. For example, we can save all the insert
related queries with the savepoint named INS. To save all the insert related queries in
one savepoint, we have to execute the SAVEPOINT query followed by the savepoint
name after finishing the insert command execution.
Summary – Day 10

Indexes:

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

Syntax:
Unique Index:

• Generally, we use the primary key constraint to enforce the uniqueness value of one
or more columns. But, we can use only one primary key for each table. So if we want
to make multiple sets of columns with unique values, the primary key constraint will
not be used.
• MySQL allows another constraint called the UNIQUE INDEX to enforce the
uniqueness of values in one or more columns. We can create more than one UNIQUE
index in a single table, which is not possible with the primary key constraint.

Syntax:

Show Indexes:

We can get the index information of a table using the Show Indexes statement.

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.

Views:

• A view is a database object that has no values. Its contents are based on the base
table. It contains rows and columns similar to the real table. In MySQL, the View is a
virtual table created by a query by joining one or more tables. It is operated similarly
to the base table but does not contain any data of its own.
• The View and table have one main difference that the views are definitions built on
top of other tables (or views). If any changes occur in the underlying table, the same
changes reflected in the View also.
• Below query is used to create the view.
• We can change the logic in the view as well. To do that we use below query.

• We can drop the existing VIEW by using the DROP VIEW statement.

Purpose to use Views:

MySQL view provides the following advantages to the user.

• Simplify complex query:


o 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:


o 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:


o 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:
o 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.
Summary – Day 11

Stored Procedures:

• A procedure (often called a stored procedure) is a collection of pre-compiled SQL


statements stored inside the database. It is a subroutine or a subprogram in the
regular computing language. A procedure always contains a name, parameter lists,
and SQL statements.
• If we consider the enterprise application, we always need to perform specific tasks
such as database clean-up, processing payroll, and many more on the database
regularly. Such tasks involve multiple SQL statements for executing each task.
• This process might easy if we group these tasks into a single task. We can fulfil this
requirement in MySQL by creating a stored procedure in our database.

Stored Procedure Features:

• Stored Procedure increases the performance of the applications. Once stored


procedures are created, they are compiled and stored in the database.
• Stored procedure reduces the traffic between application and database server.
Because the application has to send only the stored procedure's name and
parameters instead of sending multiple SQL statements.
• Stored procedures are reusable and transparent to any applications.
• A procedure is always secure. The database administrator can grant permissions to
applications that access stored procedures in the database without giving any
permissions on the database tables.
How to create a procedure?

• The following syntax is used for creating a stored procedure in MySQL. It can return
one or more value through parameters or sometimes may not return at all. By
default, a procedure is associated with our current database. But we can also create it
into another database from the current database by specifying the name as
database_name.procedure_name.

Parameters:

IN parameter:

It is the default mode. It takes a parameter as input, such as an attribute. When we define it,
the calling program has to pass an argument to the stored procedure. This parameter's value
is always protected.

OUT parameters:

It is used to pass a parameter as output. Its value can be changed inside the stored
procedure, and the changed (new) value is passed back to the calling program. It is noted
that a procedure cannot access the OUT parameter's initial value when it starts.

INOUT parameters:
It is a combination of IN and OUT parameters. It means the calling program can pass the
argument, and the procedure can modify the INOUT parameter, and then passes the new
value back to the calling program.

How to call a stored procedure?

We can use the CALL statement to call a stored procedure. This statement returns the values
to its caller through its parameters (IN, OUT, or INOUT). The following syntax is used to call
the stored procedure in MySQL:

How to show or list stored procedures in MySQL?

When we have several procedures in the MySQL server, it is very important to list all
procedures. It is because sometimes the procedure names are the same in many databases.
In that case, this query is very useful. We can list all procedure stored on the current MySQL
server as follows.

How to delete/drop stored procedures in MySQL?

MySQL also allows a command to drop the procedure. When the procedure is dropped, it is
removed from the database server also. The following statement is used to drop a stored
procedure in MySQL.

How to alter the procedure in MySQL?

MySQL does not allow any command to alter the procedure in MySQL. However, it provides
a command that is used to change the characteristics of a stored procedure. This command
may alter more than one change in the procedure but does not modify the stored
procedure's parameters or body. If we want to make such changes, we must drop and re-
create the procedure using the DROP PROCEDURE and CREATE PROCEDURE statement.
Drawbacks of Using Stored Procedures:

• If we use stored procedures, the memory uses of every connection that uses those
stored procedures will increase substantially. Also, if we overuse many logical
applications inside stored procedures, the CPU usage will increase. It is because the
database server is not well designed for logical operations.
• Stored procedure's constructs are not designed to develop complex and flexible
business logic.
• It is difficult to debug stored procedures. Only a few database management systems
allow us to debug stored procedures. Unfortunately, MySQL does not provide
facilities for debugging stored procedures.
• It is not easy to develop and maintain stored procedures. Developing and
maintaining stored procedures are often required a specialized skill set that not all
application developers possess. It may lead to problems in both application
development and maintenance phases.
Summary – Day 12

User Defined Functions:

• Functions are blocks of codes to perform specific tasks and return the result.
However, it is not mandatory for a function return anything and also a function is not
limited to performing one task only. User defined functions are basic building blocks
of a program and can be found in the basic structure of C program.
• Functions can be classified into two categories, namely, system-defined functions and
user-defined functions. The functions which are developed by user at the time of
writing a program are called user defined functions. Thus, user defined functions are
functions developed by user.

Syntax:
• In this syntax:

o First, specify the name of the stored function that you want to create after
CREATE FUNCTION keywords.

o Second, list all parameters of the stored function inside the parentheses
followed by the function name. By default, all parameters are the IN
parameters. You cannot specify IN , OUT or INOUT modifiers to
parameters.

o Third, specify the data type of the return value in the RETURNS statement,
which can be any valid MySQL data types.

o Fourth, specify if a function is deterministic or not using the


DETERMINISTIC keyword.

o A deterministic function always returns the same result for the same input
parameters whereas a non-deterministic function returns different results
for the same input parameters.

o If you don’t use DETERMINISTIC or NOT DETERMINISTIC, MySQL uses the


NOT DETERMINISTIC option by default.

o Fifth, write the code in the body of the stored function in the BEGIN END
block. Inside the body section, you need to specify at least one RETURN
statement. The RETURN statement returns a value to the calling programs.
Whenever the RETURN statement is reached, the execution of the stored
function is terminated immediately.

Window Functions:

• Windows function in MySQL helps to solve a query problem. The operation is


performed on a set of query rows while keeping the number of rows intact.

• The window functions allow you to solve query problems in new, easier ways and
with better performance.

• Aggregate functions summarize the data from multiple rows into a single result row,
but window functions, which also operate on a subset of rows, do not reduce the
number of rows returned by the query.
Syntax:

window_function (expression) OVER ( [partition_definition] [order_defenition] )

Where

• window_funtion -the name of the window function

• expression – field on which function is performed

• partition_definition – constraint for partition

• order_definition – order of result set

Types:

ROW_NUMBER(): Used to insert the row numbers.

RANK(): Provides every row with rank but it is not always a consecutive number like
Row_number()

DENSE_RANK(): Will assign consecutive rank numbers for each group.

PERCENT_RANK(): Calculates the percentile of a row within the small result set and will return
a value ranging from 0 to 1 for every row.

CUME_DIST(): Returns a value that represents the number of rows with values less than or
equal to ( <= )the current row's value divided by the total number of rows.

NTILE(): Helps to split the result set rows into a specified number of groups based upon the
partition_by and order_by clauses provided.

LAG(): Returns the value to the previous rows in a sorted and partitioned result set.

LEAD(): Will return the values ahead, in the partitioned and sorted result set.

FIRST_VALUE(): Returns the first row among a partitioned sorted result set.

LAST_VALUE(): Returns the last row among a partitioned sorted result set.

NTH VALUE(): Returns the Nth row among a partitioned sorted result set.
Summary – Day 13

Union:

• MySQL UNION operator allows you to combine two or more result sets of queries
into a single result set. The following illustrates the syntax of the UNION operator.

• To combine result set of two or more queries using the UNION operator, these are
the basic rules that you must follow:
1. First, the number and the orders of columns that appear in all SELECT
statements must be the same.
2. Second, the data types of columns must be the same or compatible.

• By default, the UNION operator removes duplicate rows even if you don’t specify the
DISTINCT operator explicitly.
Union All:

• MySQL UNION ALL operator is a union query command which syndicates multiple
SELECT statements’ results into a single result row.

• Like, MySQL UNION operator it is also a useful command in MySQL database to


combine more than two of the output set provided by the use of SELECT queries. But
there is slightly a difference in their work which makes them two different commands
used in MySQL for their respective purposes.

• The MySQL UNION operator performs to give the distinctive values of set in the
result after the union of the result rows of SELECT statements whereas the MySQL
UNION ALL operator allows the union producing the result set from SELECT
statements having replica values in the records fetched from the database tables
where it is applied.
Intersect:

• The INTERSECT operator is a set operator that returns only distinct rows of two
queries or more queries.
• The INTERSECT operator compares the result sets of two queries and returns the
distinct rows that are output by both queries
• To use the INTERSECT operator for two queries, you follow these rules.
o The order and the number of columns in the select list of the queries must be
the same.
o The data types of the corresponding columns must be compatible.
• We can emulate intersect using two ways.
o Using inner join:
▪ The following statement uses DISTINCT operator and INNER JOIN
clause to return the distinct rows in both tables.

o Using IN and Subquery:


▪ The following statement uses the IN operator and a subquery to
return the intersection of the two result sets.

Subqueries:

• A MySQL subquery is a query nested within another query such as SELECT, INSERT,
UPDATE or DELETE. Also, a subquery can be nested within another subquery.

• A MySQL subquery is called an inner query while the query that contains the
subquery is called an outer query. A subquery can be used anywhere that expression
is used and must be closed in parentheses.

• For example, the following query uses a subquery to return the employees who work
in the offices located in the USA.
• We can also use the subqueries after FROM clause.

• When you use a subquery in the FROM clause, the result set returned from a
subquery is used as a temporary table. This table is referred to as a derived table or
materialized subquery.

• The following subquery finds the maximum, minimum, and average number of items
in sale orders.
Correlated Subquery:

• A subquery is independent. It means that you can execute the subquery as a


standalone query.
• Unlike a standalone subquery, a correlated subquery is a subquery that uses the data
from the outer query. In other words, a correlated subquery depends on the outer
query. A correlated subquery is evaluated once for each row in the outer query.
• The following example uses a correlated subquery to select products whose buy
prices are greater than the average buy price of all products in each product line.

Subqueries with EXISTS and NOT EXISTS:

• When a subquery is used with the EXISTS or NOT EXISTS operator, a subquery returns
a Boolean value of TRUE or FALSE. The following query illustrates a subquery used
with the EXISTS operator.
Summary – Day 14

Exception Handling:

• When an error occurs inside a stored procedure, it is important to handle it


appropriately, such as continuing or exiting the current code block’s execution, and
issuing a meaningful error message.

• MySQL provides an easy way to define handlers that handle from general conditions
such as warnings or exceptions to specific conditions e.g., specific error codes.

• To declare a handler, you use the DECLARE HANDLER statement as follows.

• If a condition whose value matches the condition_value , MySQL will execute the
statement and continue or exit the current code block based on the action.

• The action accepts one of the following values:


o CONTINUE : the execution of the enclosing code block ( BEGIN … END )
continues.
o EXIT : the execution of the enclosing code block, where the handler is
declared, terminates.

• The condition_value specifies a particular condition or a class of conditions that


activate the handler. The condition_value accepts one of the following values:
o A MySQL error code.
o A standard SQLSTATE value. Or it can be an SQLWARNING , NOTFOUND or
SQLEXCEPTION condition, which is shorthand for the class of SQLSTATE
values. The NOTFOUND condition is used for a cursor or SELECT INTO
variable list statement.
o A named condition associated with either a MySQL error code or SQLSTATE
value.

• The statement could be a simple statement or a compound statement enclosing by


the BEGIN and END keywords.

Loops:

• The MySQL LOOP statement could be used to run a block of code or set of
statements, again and again, depending on the condition. Stored procedures are
a subset of SQL statements that are kept in the SQL catalog as subroutines. These
procedures may have both IN and OUT parameters. If you use SELECT statements,
they might return result sets or multiple result sets. In MYSQL, functions can also
be made.

• IF, CASE, ITERATE, LEAVE LOOP, WHILE, and REPEAT are examples of flow control
statements supported by MySQL, much like in other programming languages.
These statements can be used in stored programs (procedures), and stored
functions can use RETURN. One Flow Control Statement may be used inside
another.

LOOP:

• The LOOP can have optional labels at the beginning and end of the block.

• The LOOP executes the statement_list repeatedly. The statement_list may have
one or more statements, each terminated by a semicolon (;) statement
delimiter.

• Typically, you terminate the loop when a condition is satisfied by using the
LEAVE statement.
• Syntax of the LOOP statement with LEAVE Statement.
REPEAT:

• The REPEAT statement executes one or more statements until a search


condition is true.

• Syntax:

• The REPEAT executes the statement until the search_condition evaluates to


true.

• The REPEAT checks the search_condition after the execution of statement,


therefore, the statement always executes at least once. This is why the REPEAT
is also known as a post-test loop.

• The REPEAT statement can have labels at the beginning and at the end. These
labels are optional.

WHILE:

• The WHILE loop is a loop statement that executes a block of code repeatedly
as long as a condition is true.

• Syntax:
• In this syntax:

o First, specify a search condition after the WHILE keyword.

o The WHILE checks the search_condition at the beginning of each


iteration.

o If the search_condition evaluates to TRUE, the WHILE executes the


statement_list as long as the search_condition is TRUE.

o The WHILE loop is called a pretest loop because it checks the


search_condition before the statement_list executes.

o Second, specify one or more statements that will execute between the
DO and END WHILE keywords.

o Third, specify optional labels for the WHILE statement at the beginning
and end of the loop construct.

Cursors:

• Cursor in My SQL is used to iterate through a result set returned by a select


statement.

• To handle a result set inside a stored procedure, we use a cursor. A cursor


allows you to iterate a set of rows returned by a query and process each row
accordingly.

Steps:

1. DECLARE cursor_name CURSOR FOR SELECT_statement;


2. DECLARE CONTINUE HANDLER FOR NOT FOUND // termination statement
3. OPEN cursor_name;
4. FETCH cursor_name INTO variables_list;
5. CLOSE cursor_name;

Features of a MySQL Cursor:

• A cursor is read-only and cannot update or remove data in the result set from
the procedure.
• A cursor needs to be declared before it can be used. The cursor definition is
only a step to tell MySQL that such a cursor exists and does not retrieve and
data.
• You can only retrieve data in the order specified by the select statement and
not in any reverse order, commonly known as non-scrollable.
• You use a cursor by opening it and then perform fetch operations on the data
stored.
• You must close a cursor after the fetch operations complete.
Summary – Day 15

Triggers:

• 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 contrast, a stored procedure must be called explicitly.

• In MySQL, a trigger is a stored program invoked automatically in response to an


event such as insert, update, or delete that occurs in the associated table. For
example, you can define a trigger that is invoked automatically before a new row is
inserted into a table.

• MySQL supports triggers that are invoked in response to the INSERT, UPDATE or
DELETE event.

• The SQL standard defines two types of triggers: row-level triggers and statement-
level triggers.

• A row-level trigger is activated for each row that is inserted, updated, or deleted. For
example, if a table has 100 rows inserted, updated, or deleted, the trigger is
automatically invoked 100 times for the 100 rows affected.

• A statement-level trigger is executed once for each transaction regardless of how


many rows are inserted, updated, or deleted.
• MySQL supports only row-level triggers. It doesn’t support statement-level triggers.

Types:

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.

Syntax:

Parameters 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.
• trigger_event: It is the type of operation name that activates the trigger. It can be
either INSERT, UPDATE, or DELETE 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 multiple 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 existing row before the updation or
deletion occurs. NEW.col_name indicates the column of a new row that will be
inserted or an existing 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 access the column value before the update as
OLD.message_info and the new value NEW.message_info.

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

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.
Why we need/use triggers in MySQL ?

• Triggers help us to enforce business rules.


• Triggers help us to validate data even before they are inserted or updated.
• Triggers help us to keep a log of records like maintaining audit trails in tables.
• SQL triggers provide an alternative way to check the integrity of data.
• Triggers provide an alternative way to run the scheduled task.
• Triggers increases the performance of SQL queries because it does not need to
compile each time the query is executed.
• Triggers reduce the client-side code that saves time and effort.
• Triggers help us to scale our application across different platforms.
• Triggers are easy to maintain.

Limitations:

• 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.
• Triggers are invoked and executed invisibly from the client application. Therefore, it
isn't easy to troubleshoot what happens in the database layer.
• Triggers may increase the overhead of the database server.

You might also like