You are on page 1of 51

CORPORATE TRAINING BOOK – MYSQL

1. OBJECTIVE
The objective of the mysql training book is to learn the database programming of mysql in a
detailed formats clearly and efficiently.

2. INTRODUCTION
MySQL is the most popular Open Source Relational SQL database management system. MySQL
is one of the best RDBMS being used for developing web-based software applications.

2.1 WHAT IS MYSQL


MySQL, the most popular Open Source SQL database management system, is developed,
distributed, and supported by Oracle Corporation.

MySQL is a database management system:

A database is a structured collection of data. It may be anything from a simple shopping list to a
picture gallery or the vast amounts of information in a corporate network. To add, access, and
process data stored in a computer database, you need a database management system such as
MySQL Server.

MySQL databases are relational:


A relational database stores data in separate tables rather than putting all the data in one big
storeroom. The database structures are organized into physical files optimized for speed. The
logical model, with objects such as databases, tables, views, rows, and columns, offers a flexible
programming environment.

MySQL software is Open Source:


Open Source means that it is possible for anyone to use and modify the software. Anybody can
download the MySQL software from the Internet and use it without paying anything.

The MySQL Database Server is very fast, reliable, scalable, and easy to use:
If that is what you are looking for, you should give it a try. MySQL Server can run comfortably on a
desktop or laptop, alongside your other applications, web servers, and so on, requiring little or no
attention.

MySQL Server works in client/server or embedded systems:


The MySQL Database Software is a client/server system that consists of a multi-threaded SQL
server that supports different backends, several different client programs and libraries,
administrative tools, and a wide range of application programming interfaces (APIs).

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 1


CORPORATE TRAINING BOOK – MYSQL

A large amount of contributed MySQL software is available:


MySQL Server has a practical set of features developed in close cooperation with our users. It is
very likely that your favorite application or language supports the MySQL Database Server.

2.2 FEATURES OF MYSQL


Internals and Portability

 Written in C and C++.

 Tested with a broad range of different compilers.

 Works on many different platforms.

 For portability, uses CMake in MySQL 5.5 and up. Previous series use GNU Automake,
Autoconf, and Libtool.

 Security

A privilege and password system that is very flexible and secure, and that enables host-
based verification.
Password security by encryption of all password traffic when you connect to a server.

Scalability and Limits:


Support for large databases. We use MySQL Server with databases that contain 50 million records.
We also know of users who use MySQL Server with 200,000 tables and about 5,000,000,000 rows.

Connectivity:

Clients can connect to MySQL Server using several protocols:

Clients can connect using TCP/IP sockets on any platform.

Localization:

The server can provide error messages to clients in many languages.

Full support for several different character sets, including latin1 (cp1252), german, big5, ujis,
several Unicode character sets, and more. For example, the Scandinavian characters “å”, “ä” and
“ö” are permitted in table and column names.

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 2


CORPORATE TRAINING BOOK – MYSQL

3. CREATING AND USING DATABASE


Once you know how to enter SQL statements, you are ready to access a database.
Suppose that you have several pets in your home (your menagerie) and you would like to keep
track of various types of information about them. You can do so by creating tables to hold your data
and loading them with the desired information. Then you can answer different sorts of questions
about your animals by retrieving data from the tables.

3.1 CREATING AND SELECTING A DATABASE

If the administrator creates your database for you when setting up your permissions, you can begin
using it. Otherwise, you need to create it yourself:
mysql> CREATE DATABASE poll;

CREATING A TABLECreating a database does not select it for use; you must do that explicitly. To
make menagerie the current database, use this statement:

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 3


CORPORATE TRAINING BOOK – MYSQL

3.2 CREATING A TABLE


Use a CREATE TABLE statement to specify the layout of your table:

3.3 RETRIEVING INFORMATION FROM TABLE


The SELECT statement is used to pull information from a table. The general form of the statement
is:

what_to_select indicates what you want to see. This can be a list of columns, or * to indicate “all
columns.” which_table indicates the table from which you want to retrieve data. The WHERE
clause is optional. If it is present, conditions_to_satisfy specifies one or more conditions that rows
must satisfy to qualify for retrieval.

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 4


CORPORATE TRAINING BOOK – MYSQL

4. COMMON QUERIES

Mysql queries are usually written once and then wrapped in class functions to minimize code
repetition. Mysql queries are usually written once and then wrapped in class functions to minimize
code repetition.

4.1 MAXIMUM VALUE FOR A COLUMN


“What is the highest item number?”

4.2 ROW HOLDING THE MAXIMUM OF A CERTAIN COLUMN


Find the number, dealer, and price of the most expensive article.

This is easily done with a subquery:

Other solutions are to use a LEFT JOIN or to sort all rows descending by price and get only the first
row using the MySQL-specific LIMIT clause:

4.3 MAXIMUM OF COLUMN PER GROUP


Find the highest price per article.

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 5


CORPORATE TRAINING BOOK – MYSQL

4.4 ROWS HOLDING THE GROUP-WISE MAXIMUM OF A CERTAIN COLUMN


For each article, find the dealer or dealers with the most expensive price.

This problem can be solved with a subquery like this one:

SELECT article, dealer, price

FROM shop s1

WHERE price=(SELECT MAX(s2.price)

FROM shop s2

WHERE s1.article = s2.article);

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

| article | dealer | price |

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

| 0001 | B | 3.99 |

| 0002 | A | 10.99 |

| 0003 | C | 1.69 |

| 0004 | D | 19.95 |

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

The preceding example uses a correlated subquery, which can be inefficient. Other possibilities for
solving the problem are to use an uncorrelated subquery in the FROM clause or a LEFT JOIN.

Uncorrelated subquery:

SELECT s1.article, dealer, s1.price

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 6


CORPORATE TRAINING BOOK – MYSQL

FROM shop s1

JOIN (

SELECT article, MAX(price) AS price

FROM shop

GROUP BY article) AS s2

ON s1.article = s2.article AND s1.price = s2.price;

LEFT JOIN:

SELECT s1.article, s1.dealer, s1.price

FROM shop s1

LEFT JOIN shop s2 ON s1.article = s2.article AND s1.price < s2.price

WHERE s2.article IS NULL;

4.5 USER-DEFINED VARIABLES

You can employ MySQL user variables to remember results without having to store them in tem
porary variables in the client.

For example, to find the articles with the highest and lowest price you can do this:

mysql> SELECT @min_price:=MIN(price),@max_price:=MAX(price) FROM shop;

mysql> SELECT * FROM shop WHERE price=@min_price OR price=@max_price;

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

| article | dealer | price |

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

| 0003 | D | 1.25 |

| 0004 | D | 19.95 |

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

4.6 USING AUTO_INCREMENT

The AUTO_INCREMENT attribute can be used to generate a unique identity for new rows:

CREATE TABLE animals (

id MEDIUMINT NOT NULL AUTO_INCREMENT,

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 7


CORPORATE TRAINING BOOK – MYSQL

name CHAR(30) NOT NULL,

PRIMARY KEY (id)

);

INSERT INTO animals (name) VALUES

('dog'),('cat'),('penguin'),

('lax'),('whale'),('ostrich');

SELECT * FROM animals;

Which returns:

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

| id | name |

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

| 1 | dog |

| 2 | cat |

| 3 | penguin |

| 4 | lax |

| 5 | whale |

| 6 | ostrich |

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

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 8


CORPORATE TRAINING BOOK – MYSQL

5. OPTIMIZING SQL STATEMENTS


Sql statements are used to retrieve data from the database. We can get same results by writing
different sql queries. But use of the best query is important when performance is considered. So
you need to sql query tuning based on the requirement.

5.1 OPTIMIZING SELECT STATEMENT


 Speed of SELECT Statements

 How MySQL Optimizes WHERE Clauses

 Range Optimization

 Index Merge Optimization

 Engine Condition Pushdown Optimization

 Index Condition Pushdown Optimization

 Use of Index Extensions

 IS NULL Optimization

 LEFT JOIN and RIGHT JOIN Optimization

 Nested-Loop Join Algorithms

 Nested Join Optimization

 Outer Join Simplification

 Multi-Range Read Optimization

 Block Nested-Loop and Batched Key Access Joins

 ORDER BY Optimization

 GROUP BY Optimization

 DISTINCT Optimization

 Subquery Optimization

 LIMIT Query Optimization

 Row Constructor Expression Optimization

 How to Avoid Full Table Scans

Queries, in the form of SELECT statements, perform all the lookup operations in the database.
Tuning these statements is a top priority, whether to achieve sub-second response times for
dynamic web pages, or to chop hours off the time to generate huge overnight reports.
Besides SELECT statements, the tuning techniques for queries also apply to constructs such as
CREATE TABLE...AS SELECT, INSERT INTO...SELECT, and WHERE clauses in DELETE

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 9


CORPORATE TRAINING BOOK – MYSQL

statements. Those statements have additional performance considerations because they combine
write operations with the read-oriented query operations.

5.2 OPTIMIZING DML STATEMENTS

Speed of INSERT Statements

To optimize insert speed, combine many small operations into a single large operation. Ideally, you
make a single connection, send the data for many new rows at once, and delay all index updates
and consistency checking until the very end. The time required for inserting a row is determined by
the following factors, where the numbers indicate approximate proportions:

1) Connecting: (3)

2) Sending query to server: (2)

3) Parsing query: (2)

4) Inserting row: (1 × size of row)

5) Inserting indexes: (1 × number of indexes)

6) Closing: (1)

Speed of UPDATE Statements


An update statement is optimized like a SELECT query with the additional overhead of a write. The
speed of the write depends on the amount of data being updated and the number of indexes that
are updated. Indexes that are not changed do not get updated.Another way to get fast updates is to
delay updates and then do many updates in a row later. Performing multiple updates together is
much quicker than doing one at a time if you lock the table.

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 10


CORPORATE TRAINING BOOK – MYSQL

Speed of DELETE Statement

The time required to delete individual rows in a MyISAM table is exactly proportional to the number
of indexes. To delete rows more quickly, you can increase the size of the key cache by increasing
the key_buffer_size system variable. See Section 6.1.1, “Configuring the Server”. To delete all
rows from a MyISAM table, TRUNCATE TABLE tbl_name is faster than DELETE FROM tbl_name.
Truncate operations are not transaction-safe; an error occurs when attempting one in the course of
an active transaction or active table lock.

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 11


CORPORATE TRAINING BOOK – MYSQL

6. OPTIMIZATION AND INDEXES

The best way to improve the performance of select operations is to create indexes on one or more
of the columns that are tested in the query. The index entries act like pointers to the table rows,
allowing the query to quickly determine which rows match a condition in the where clause, and
retrieve the other column values for those rows. All mysql data types can be indexed

6.1 PRIMARY KEYS


The primary key for a table represents the column or set of columns that you use in your most vital
queries. It has an associated index, for fast query performance. Query performance benefits from
the NOT NULL optimization, because it cannot include any NULL values. With the InnoDB storage
engine, the table data is physically organized to do ultra-fast lookups and sorts based on the
primary key column or columns.

If your table is big and important, but does not have an obvious column or set of columns to use as
a primary key, you might create a separate column with auto-increment values to use as the
primary key. These unique IDs can serve as pointers to corresponding rows in other tables when
you join tables using foreign keys.

6.2 FOREIGN KEYS


If a table has many columns, and you query many different combinations of columns, it might be
efficient to split the less-frequently used data into separate tables with a few columns each, and
relate them back to the main table by duplicating the numeric ID column from the main table. That
way, each small table can have a primary key for fast lookups of its data, and you can query just
the set of columns that you need using a join operation. Depending on how the data is distributed,
the queries might perform less I/O and take up less cache memory because the relevant columns
are packed together on disk. (To maximize performance, queries try to read as few data blocks as
possible from disk; tables with only a few columns can fit more rows in each data block.)

Example of primary key and Foreign key

The "Employee" table:

E_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

The "Salary" table:

S_Id Salary E_Id


1 20000 3
2 40000 3
3 50000 2

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 12


CORPORATE TRAINING BOOK – MYSQL

7. OPTIMIZING DATABASE STRUCTURE


In your role as a database designer, look for the most efficient way to organize your schemas,
tables, and columns. As when tuning application code, you minimize i/o, keep related items
together, and plan ahead so that performance stays high as the data volume increases. Starting
with an efficient database design makes it easier for team members to write high-performing
application code, and makes the database likely to endure as applications evolve and are rewritten.

7.1 OPTIMIZING DATA SIZE


Design your tables to minimize their space on the disk. This can result in huge improvements by
reducing the amount of data written to and read from disk. Smaller tables normally require less
main memory while their contents are being actively processed during query execution. Any space
reduction for table data also results in smaller indexes that can be processed faster.
MySQL supports many different storage engines (table types) and row formats. For each table, you
can decide which storage and indexing method to use. Choosing the proper table format for your
application can give you a big performance gain.

7.2 OPTIMIZING MYSQL DATA TYPES


Optimizing for Numeric Data
For unique IDs or other values that can be represented as either strings or numbers, prefer
numeric columns to string columns. Since large numeric values can be stored in fewer bytes than
the corresponding strings, it is faster and takes less memory to transfer and compare them.

Optimizing for Character and String Types


For character and string columns, follow these guidelines:
Use binary collation order for fast comparison and sort operations, when you do not need
language-specific collation features. You can use the BINARY operator to use binary collation
within a particular query.
When comparing values from different columns, declare those columns with the same character
set and collation wherever possible, to avoid string conversions while running the query.
For column values less than 8KB in size, use binary VARCHAR instead of BLOB. The GROUP BY
and ORDER BY clauses can generate temporary tables, and these temporary tables can use the
MEMORY storage engine if the original table does not contain any BLOB columns.

Optimizing for BLOB Types


When storing a large blob containing textual data, consider compressing it first. Do not use this
technique when the entire table is compressed by InnoDB or MyISAM.
For a table with several columns, to reduce memory requirements for queries that do not use the
BLOB column, consider splitting the BLOB column into a separate table and referencing it with a
join query when needed.

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 13


CORPORATE TRAINING BOOK – MYSQL

Since the performance requirements to retrieve and display a BLOB value might be very different
from other data types, you could put the BLOB-specific table on a different storage device or even
a separate database instance. For example, to retrieve a BLOB might require a large sequential
disk read that is better suited to a traditional hard drive than to an SSD device.

7.3 OPTIMIZING DATABASE STRUCTURE


How MySQL Opens and Closes Tables
When you execute a mysqladmin status command, you should see something like this:
Uptime: 426 Running threads: 1 Questions: 11082
Reloads: 1 Open tables: 12
The Open tables value of 12 can be somewhat puzzling if you have only six tables.
MySQL is multi-threaded, so there may be many clients issuing queries for a given table
simultaneously. To minimize the problem with multiple client sessions having different states on the
same table, the table is opened independently by each concurrent session. This uses additional
memory but normally increases performance. With MyISAM tables, one extra file descriptor is
required for the data file for each client that has the table open. (By contrast, the index file
descriptor is shared between all sessions.)

Disadvantages of Creating Many Tables in the Same Database


If you have many MyISAM tables in the same database directory, open, close, and create
operations are slow. If you execute SELECT statements on many different tables, there is a little
overhead when the table cache is full, because for every table that has to be opened, another must
be closed. You can reduce this overhead by increasing the number of entries permitted in the table
cache.

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 14


CORPORATE TRAINING BOOK – MYSQL

8. DATA TYPES
Mysql supports a number of sql data types in several categories: numeric types, date and time
types, string (character and byte) types, and spatial types. This chapter provides an overview of
these data types, a more detailed description of the properties of the types in each category, and a
summary of the data type storage requirements

8.1 DATA TYPE OVERVIEW

 Numeric Type Overview


 Date and Time Type Overview
 String Type Overview

8.2 NUMERIC TYPE OVERVIEW


Numeric data types that permit the unsigned attribute also permit signed. However, these data
types are signed by default, so the signed attribute has no effect.numeric data types that permit the
unsigned attribute also permit signed. However, these data types are signed by default, so the
signed attribute has no effect.

1. BIT[(M)]
A bit-value type. M indicates the number of bits per value, from 1 to 64. The default is 1 if M
is omitted.
2. BIT[(M)]
A bit-value type. M indicates the number of bits per value, from 1 to 64. The default is 1 if M
is omitted.

3. TINYINT[(M)] [UNSIGNED] [ZEROFILL]

A very small integer. The signed range is -128 to 127. The unsigned range is 0 to 255.

4. BOOL, BOOLEAN
These types are synonyms for TINYINT(1). A value of zero is considered false. Nonzero
values are considered true:

5. SMALLINT[(M)] [UNSIGNED] [ZEROFILL]


A small integer. The signed range is -32768 to 32767. The unsigned range is 0 to 65535.

6. MEDIUMINT[(M)] [UNSIGNED] [ZEROFILL]


A medium-sized integer. The signed range is -8388608 to 8388607. The unsigned range is 0
to 16777215.

7. INT[(M)] [UNSIGNED] [ZEROFILL]


A normal-size integer. The signed range is -2147483648 to 2147483647. The unsigned
range is 0 to 4294967295.

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 15


CORPORATE TRAINING BOOK – MYSQL

8. BIGINT[(M)] [UNSIGNED] [ZEROFILL]


A large integer. The signed range is -9223372036854775808 to 9223372036854775807.
The unsigned range is 0 to 18446744073709551615.
9. SERIAL is an alias for BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE.
Some things you should be aware of with respect to BIGINT columns:
All arithmetic is done using signed BIGINT or DOUBLE values, so you should not use
unsigned big integers larger than 9223372036854775807 (63 bits) except with bit functions!
If you do that, some of the last digits in the result may be wrong because of rounding errors
when converting a BIGINT vaBIT[(M)]
A bit-value type. M indicates the number of bits per value, from 1 to 64. The default is 1 if M
is omitted.
10. TINYINT[(M)] [UNSIGNED] [ZEROFILL]
Very small integer. The signed range is -128 to 127. The unsigned range is 0 to 255.
11. BIT[(M)]
A bit-value type. M indicates the number of bits per value, from 1 to 64. The default is 1 if M
is omitted.
12. TINYINT[(M)] [UNSIGNED] [ZEROFILL]
A very small integer. The signed range is -128 to 127. The unsigned range is 0 to 255.

13. BOOL, BOOLEAN


These types are synonyms for TINYINT(1). A value of zero is considered false. Nonzero
values are considered true:

14. SMALLINT[(M)] [UNSIGNED] [ZEROFILL]


A small integer. The signed range is -32768 to 32767. The unsigned range is 0 to 65535.

15. MEDIUMINT[(M)] [UNSIGNED] [ZEROFILL]


A medium-sized integer. The signed range is -8388608 to 8388607. The unsigned range is 0
to 16777215.

16. INT[(M)] [UNSIGNED] [ZEROFILL]


A normal-size integer. The signed range is -2147483648 to 2147483647. The unsigned
range is 0 to 4294967295.

17. INTEGER[(M)] [UNSIGNED] [ZEROFILL]


This type is a synonym for INT.

8.3 INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT


MySQL supports the SQL standard integer types INTEGER (or INT) and SMALLINT. As an
extension to the standard, MySQL also supports the integer types TINYINT, MEDIUMINT, and
BIGINT. The following table shows the required storage and range for each integer type.

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 16


CORPORATE TRAINING BOOK – MYSQL

Type Storage(Bytes) Minimum Maximum


Value(Signed/Unsigned) Value(Signed/Unsigned)

TINYINT 1 -128 127


0 255

SMALLINT 2 -32767 32768


0 65535

MEDIUMINT 3 -8388608 0
8388607 16777215

INT 4 2147483648 0
2147483647 4294967295

BIGINT 8 -9223372036854775808 9223372036854775807


0 184467440737095516

Example:

CREATE TABLE hardware (


id int(11) NOT NULL AUTO_INCREMENT,
brand varchar(60) DEFAULT NULL,
description text,
amount float DEFAULT NULL,
paid_date date DEFAULT NULL,
paid_mode enum('Cheque','cash','online transfer') DEFAULT NULL,
create_date datetime DEFAULT NULL,
created_by tinyint(4) DEFAULT NULL,
PRIMARY KEY (`id`)
)

8.4 DATE AND TIME TYPE OVERVIEW


For the DATE and DATETIME range descriptions, “supported” means that although earlier values
might work, there is no guarantee.
MySQL permits fractional seconds for TIME, DATETIME, and TIMESTAMP values, with up to
microseconds (6 digits) precision. To define a column that includes a fractional seconds part, use

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 17


CORPORATE TRAINING BOOK – MYSQL

the syntax type_name(fsp), where type_name is TIME, DATETIME, or TIMESTAMP, and fsp is the
fractional seconds precision. For example:
CREATE TABLE t1 (t TIME(3), dt DATETIME(6));
The fsp value, if given, must be in the range 0 to 6. A value of 0 signifies that there is no fractional
part. If omitted, the default precision is 0. (This differs from the standard SQL default of 6, for
compatibility with previous MySQL versions.)

DATE
A date. The supported range is '1000-01-01' to '9999-12-31'. MySQL displays DATE values in
'YYYY-MM-DD' format, but permits assignment of values to DATE columns using either strings or
numbers.
DATETIME[(fsp)]
A date and time combination. The supported range is '1000-01-01 00:00:00.000000' to '9999-12-31
23:59:59.999999'. MySQL displays DATETIME values in 'YYYY-MM-DD HH:MM:SS[.fraction]'
format, but permits assignment of values to DATETIME

Example:

CREATE TABLE t1 (
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
dt DATETIME DEFAULT CURRENT_TIMESTAMP
);

8.5 THE DATE, DATETIME, AND TIMESTAMP TYPES


The DATE, DATETIME, and TIMESTAMP types are related. This section describes their
characteristics, how they are similar, and how they differ. MySQL recognizes DATE, DATETIME,
and TIMESTAMP values in several formats, described in Section 10.1.3, “Date and Time Literals”.
For the DATE and DATETIME range descriptions, “supported” means that although earlier values
might work, there is no guarantee.
The DATE type is used for values with a date part but no time part. MySQL retrieves and displays
DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.
The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and
displays DATETIME values in 'YYYY-MM-DD HH:MM:SS' format. The supported range is '1000-
01-01 00:00:00' to '9999-12-31 23:59:59'.
The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP
has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.
A DATETIME or TIMESTAMP value can include a trailing fractional seconds part in up to
microseconds (6 digits) precision. In particular, any fractional part in a value inserted into a
DATETIME or TIMESTAMP column is stored rather than discarded. With the fractional part
included, the format for these values is 'YYYY-MM-DD HH:MM:SS[.fraction]', the range for
DATETIME values is '1000-01-01 00:00:00.000000' to '9999-12-31 23:59:59.999999', and the
Date and Time Type Overviewrange for TIMESTAMP values is '1970-01-01 00:00:01.000000' to
'2038-01-19 03:14:07.999999'. The fractional part should always be separated from the rest of the

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 18


CORPORATE TRAINING BOOK – MYSQL

time by a decimal point; no other fractional seconds delimiter is recognized. For information about
fractional seconds support in MySQL

Example:

CREATE TABLE dt(date1 DATE,time1 TIME, timestamp1 TIMESTAMP, timestamp2


TIMESTAMP);

8.6 TIME TYPE, YEAR TYPE


The TIME Type
MySQL retrieves and displays TIME values in 'HH:MM:SS' format (or 'HHH:MM:SS' format for large
hours values). TIME values may range from '-838:59:59' to '838:59:59'. The hours part may be so
large because the TIME type can be used not only to represent a time of day (which must be less
than 24 hours), but also elapsed time or a time interval between two events (which may be much
greater than 24 hours, or even negative).
MySQL recognizes TIME values in several formats, some of which can include a trailing fractional
seconds part in up to microseconds (6 digits) precision. See Section 10.1.3, “Date and Time
Literals”. For information about fractional seconds support in MySQL,In particular, any fractional
part in a value inserted into a TIME column is stored rather than discarded. With the fractional part
included, the range for TIME values is '-838:59:59.000000' to '838:59:59.000000'.

The YEAR Type


The YEAR type is a 1-byte type used to represent year values. It can be declared as YEAR or
YEAR(4) and has a display width of four characters.
MySQL displays YEAR values in YYYY format, with a range of 1901 to 2155, or 0000.
You can specify input YEAR values in a variety of formats:
As a 4-digit number in the range 1901 to 2155.
As a 4-digit string in the range '1901' to '2155'.
As a 1- or 2-digit number in the range 1 to 99. MySQL converts values in the ranges 1 to 69
and 70 to 99 to YEAR values in the ranges 2001 to 2069 and 1970 to 1999.
As a 1- or 2-digit string in the range '0' to '99'. MySQL converts values in the ranges '0' to '69'
and '70' to '99' to YEAR values in the ranges 2000 to 2069 and 1970 to 1999.
The result of inserting a numeric 0 has a display value of 0000 and an internal value of 0000. To
insert zero and have it be interpreted as 2000, specify it as a string '0' or '00'.
As the result of a function that returns a value that is acceptable in a YEAR context, such as
NOW().
MySQL converts invalid YEAR values to 0000.
columns using either strings or numbers.

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 19


CORPORATE TRAINING BOOK – MYSQL

8.7 STRING TYPE OVERVIEW


A summary of the string data types follows.
In some cases, MySQL may change a string column to a type different from that given in a
CREATE TABLE or ALTER TABLE statement.
MySQL interprets length specifications in character column definitions in character units. This
applies to CHAR, VARCHAR, and the TEXT types.
Column definitions for many string data types can include attributes that specify the character set
or collation of the column. These attributes apply to the CHAR, VARCHAR, the TEXT types,
ENUM, and SET data types:

The CHARACTER SET attribute specifies the character set, and the COLLATE attribute specifies a
collation for the character set. For example:

CREATE TABLE t
(
c1 VARCHAR(20) CHARACTER SET utf8,

c2 TEXT CHARACTER SET latin1 COLLATE latin1_general_cs

);

8.8 THE CHAR AND VARCHAR TYPES


The CHAR and VARCHAR types are similar, but differ in the way they are stored and retrieved.
They also differ in maximum length and in whether trailing spaces are retained.
The CHAR and VARCHAR types are declared with a length that indicates the maximum number of
characters you want to store. For example, CHAR(30) can hold up to 30 characters.
The length of a CHAR column is fixed to the length that you declare when you create the table. The
length can be any value from 0 to 255. When CHAR values are stored, they are right-padded with
spaces to the specified length. When CHAR values are retrieved, trailing spaces are removed
unless the PAD_CHAR_TO_FULL_LENGTH SQL mode is enabled.
Values in VARCHAR columns are variable-length strings. The length can be specified as a value
from 0 to 65,535. The effective maximum length of a VARCHAR is subject to the maximum row
size (65,535 bytes, which is shared among all columns) and the character set used.

8.9 THE ENUM TYPE


An ENUM is a string object with a value chosen from a list of permitted values that are enumerated
explicitly in the column specification at table creation time. It has these advantages:
Compact data storage in situations where a column has a limited set of possible values. The
strings you specify as input values are automatically encoded as numbers.

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 20


CORPORATE TRAINING BOOK – MYSQL

Readable queries and output. The numbers are translated back to the corresponding strings in
query results. If you make enumeration values that look like numbers, it is easy to mix up the literal
values with their internal index numbers, as explained in Enumeration Limitations.
Using ENUM columns in ORDER BY clauses requires extra care, as explained in Enumeration
Sorting.
Creating and Using ENUM Columns
An enumeration value must be a quoted string literal. For example, you can create a table with an
ENUM column like this:
CREATE TABLE shirts (
name VARCHAR(40),
size ENUM('x-small', 'small', 'medium', 'large', 'x-large')
);
INSERT INTO shirts (name, size) VALUES ('dress shirt','large'), ('t-shirt','medium'),
('polo shirt','small');
SELECT name, size FROM shirts WHERE size = 'medium';
+---------+--------+
| name | size |
+---------+--------+
| t-shirt | medium |
+---------+--------+
UPDATE shirts SET size = 'small' WHERE size = 'large';
COMMIT;

8.10 THE SET TYPE


A SET is a string object that can have zero or more values, each of which must be chosen from a
list of permitted values specified when the table is created. SET column values that consist of
multiple set members are specified with members separated by commas (,). A consequence of this
is that SET member values should not themselves contain commas.
For example, a column specified as SET('one', 'two') NOT NULL can have any of these values:

''
'one'
'two'
'one,two'
A SET column can have a maximum of 64 distinct members.

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 21


CORPORATE TRAINING BOOK – MYSQL

9. DATA TYPE STORAGE REQUIREMENTS


The storage requirements for table data on disk depend on several factors. Different storage
engines represent data types and store raw data differently. Table data might be compressed,
either for a column or an entire row, complicating the calculation of storage requirements for a table
or column.
Despite differences in storage layout on disk, the internal MySQL APIs that communicate and
exchange information about table rows use a consistent data structure that applies across all
storage engines.
Storage Requirements for Numeric Types

Data Type Storage Required

TINYINT 1 byte

SMALLINT 2 bytes

MEDIUMINT 3 bytes

INT, INTEGER 4 bytes

BIGINT 8 bytes

FLOAT(p) 4 bytes if 0 <= p <= 24, 8 bytes if 25 <= p <= 53

FLOAT 4 bytes

DOUBLE 8 bytes
[PRECISION], REAL

BIT(M) approximately (M+7)/8 bytes

Storage Requirements for Date and Time Types


For TIME, DATETIME, and TIMESTAMP columns, the storage required for tables created before
MySQL 5.6.4 differs from tables created from 5.6.4 on. This is due to a change in 5.6.4 that permits
these types to have a fractional part, which requires from 0 to 3 bytes.

Data Type Storage Required Before MySQL Storage Required as of MySQL


5.6.4 5.6.4

YEAR 1 byte 1 byte

DATE 3 bytes 3 bytes

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 22


CORPORATE TRAINING BOOK – MYSQL

TIME 3 bytes
3 bytes + fractional seconds
storage

DATETIME 8 bytes 5 bytes + fractional seconds


storage

TIMESTAMP 4 bytes
4 bytes + fractional seconds
storage

Storage Requirements for String Types

In the following table, M represents the declared column length in characters for nonbinary string
types and bytes for binary string types. L represents the actual length in bytes of a given string value.

Data Type Storage Required

CHAR(M) M × w bytes, 0 <= M <= 255, where w is the number of bytes


required for the maximum-length

CHAR data character in the character set. “Physical Row Structure of InnoDB
Tables” for information about type storage requirements for InnoDB
tables.

BINARY(M) M bytes, 0 <= M <= 255

VARCHAR(M), L + 1 bytes if column values require 0 − 255 bytes, L + 2 bytes if


VARBINARY(M) values may require more than 255 bytes

TINYBLOB, TINYTEXT L + 1 bytes, where L < 28

BLOB, TEXT L + 2 bytes, where L < 216

MEDIUMBLOB, L + 3 bytes, where L < 224


MEDIUMTEXT

ENUM('value1','value2',...) 1 or 2 bytes, depending on the number of enumeration values


(65,535 values maximum)

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 23


CORPORATE TRAINING BOOK – MYSQL

SET('value1','value2',...) 1, 2, 3, 4, or 8 bytes, depending on the number of set members (64


members maximum)

Variable-length string types are stored using a length prefix plus data. The length prefix requires
from one to four bytes depending on the data type, and the value of the prefix is L (the byte length of
the string). For example, storage for a MEDIUMTEXT value requires L bytes to store the value plus
three bytes to store the length of the value.

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 24


CORPORATE TRAINING BOOK – MYSQL

10. FUNCTIONS AND OPERATORS


Expressions can be written using literal values, column values, null , built-in functions, stored
functions, user-defined functions, and operators. This chapter describes the functions and
operators that are permitted for writing expressions in mysql.

10.1 FUNCTION AND OPERATOR REFERENCE

Name Description

ABS() Return the absolute value

ACOS() Return the arc cosine

ADDDATE() Add time values (intervals) to a date value

ADDTIME() Add time

AES_DECRYPT() Decrypt using AES

AES_ENCRYPT() Encrypt using AES

AND, && Logical AND

Area() Return Polygon or MultiPolygon area

AsBinary(), AsWKB() Convert from internal geometry format to WKB

ASCII() Return numeric value of left-most character

ASIN() Return the arc sine

:= Assign a value

AVG() Return the average value of the argument

BENCHMARK() Repeatedly execute an expression

BETWEEN ... AND ... Check whether a value is within a range of values

BINARY Cast a string to a binary string

BIT_AND() Return bitwise AND

BIT_COUNT() Return the number of bits that are set

BIT_LENGTH() Return length of argument in bits

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 25


CORPORATE TRAINING BOOK – MYSQL

BIT_OR() Return bitwise OR

BIT_XOR() Return bitwise XOR

10.2 TYPE CONVERSION IN EXPRESSION EVALUATION


When an operator is used with operands of different types, type conversion occurs to make the
operands compatible. Some conversions occur implicitly. For example, MySQL automatically
converts numbers to strings as necessary, and vice versa.
mysql> SELECT 1+'1';

-> 2

mysql> SELECT CONCAT(2,' test');

-> '2 test'

It is also possible to convert a number to a string explicitly using the CAST() function. Conversion
occurs implicitly with the CONCAT() function because it expects string arguments.
mysql> SELECT 38.8, CAST(38.8 AS CHAR);
-> 38.8, '38.8'
mysql> SELECT 38.8, CONCAT(38.8);
-> 38.8, '38.8'
See later in this section for information about the character set of implicit number-to-string
conversions, and for modified rules that apply to CREATE TABLE ... SELECT statements.

10.3 OPERATORS
Operator Precedence
Operator precedences are shown in the following list, from highest precedence to the lowest.
Operators that are shown together on a line have the same precedence.
INTERVAL
BINARY, COLLATE
!
- (unary minus), ~ (unary bit inversion)
^
*, /, DIV, %, MOD
-, +
<<, >>
&
|

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 26


CORPORATE TRAINING BOOK – MYSQL

= (comparison), <=>, >=, >, <=, <, <>, !=, IS, LIKE, REGEXP, IN

BETWEEN, CASE, WHEN, THEN, ELSE

NOT

AND, &&

XOR

OR, ||

= (assignment),:=

Example:

mysql> SELECT 1+2*3;

-> 7

mysql> SELECT (1+2)*3;

-> 9

Comparison Functions and Operators

Name Description

BETWEEN ... AND ... Check whether a value is within a range of values

COALESCE() Return the first non-NULL argument

= Equal operator

<=> NULL-safe equal to operator

> Greater than operator

>= Greater than or equal operator

GREATEST() Return the largest argument

IN() Check whether a value is within a set of values

IS Test a value against a boolean

IS NOT Test a value against a boolean

IS NOT NULL NOT NULL value test

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 27


CORPORATE TRAINING BOOK – MYSQL

IS NULL NULL value test

ISNULL() Test whether the argument is NULL

LEAST() Return the smallest argument

< Less than operator

<= Less than or equal operator

LIKE Simple pattern matching

!=, <> Not equal operator

NOT IN() Check whether a value is not within a set of values

NOT LIKE Negation of simple pattern matching

STRCMP() Compare two strings

Logical Operators

Name Description

AND, && Logical AND

NOT,! Negates value

||, OR Logical OR

XOR Logical XOR

1. AND, &&

SELECT * FROM Customers


WHERE Country='Germany'
AND City='Berlin';

2. NOT,!
SELECT title_id, type, price
FROM titles
WHERE NOT type = 'biography'
AND NOT price < 20;

3. ||, OR

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 28


CORPORATE TRAINING BOOK – MYSQL

SELECT * FROM Customers


WHERE City='Berlin'
OR City='München';

4. XOR
SELECT EmployeeID, FirstName, LastName, ReportsTo
FROM employees
WHERE ReportsTo=2 XOR FirstName='Nancy';

In SQL, all logical operators evaluate to TRUE, FALSE, or NULL (UNKNOWN). In MySQL,
these are implemented as 1 (TRUE), 0 (FALSE), and NULL. Most of this is common to
different SQL database servers, although some servers may return any nonzero value for
TRUE.

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 29


CORPORATE TRAINING BOOK – MYSQL

11. STRING FUNCTION


MySQL SUBSTRING() returns a specified number of characters from a particular position of a
given string

11.1 NUMERIC FUNCTIONS AND OPERATORS

Name Description

ABS() Return the absolute value

ACOS() Return the arc cosine

ASIN() Return the arc sine

ATAN() Return the arc tangent

ATAN2(), ATAN() Return the arc tangent of the two arguments

CEIL() Return the smallest integer value not less than the
argument

CEILING() Return the smallest integer value not less than the
argument

CONV() Convert numbers between different number bases

COS() Return the cosine

COT() Return the cotangent

CRC32() Compute a cyclic redundancy check value

DEGREES() Convert radians to degrees

DIV Integer division

/ Division operator

Arithmetic Operators

Name Description

DIV Integer division

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 30


CORPORATE TRAINING BOOK – MYSQL

/ Division operator

- Minus operator

%, MOD Modulo operator

+ Addition operator

* Multiplication operator

- Change the sign of the argument

Example:

SELECT cust_name, opening_amt,


receive_amt, (opening_amt + receive_amt)
FROM customer
WHERE (opening_amt + receive_amt)>15000;

Mathematical Functions

Name Description

Return the absolute value

ABS() SELECT ABS(-1.0), ABS(0.0), ABS(1.0);

Return the arc cosine

SET NOCOUNT OFF;


DECLARE @cos float;
ACOS()
SET @cos = -1.0;
SELECT 'The ACOS of the number is: ' + CONVERT(varchar,
ACOS(@cos));

Return the arc sine

DECLARE @angle float


SET @angle = -1.00
ASIN()
SELECT 'The ASIN of the angle is: ' + CONVERT(varchar,
ASIN(@angle)

Return the arc tangent

ATAN() SELECT 'The ATAN of -45.01 is: ' + CONVERT(varchar, ATAN(-


45.01))

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 31


CORPORATE TRAINING BOOK – MYSQL

11.2 DATE AND TIME FUNCTIONS


This section describes the functions that can be used to manipulate temporal values. “Date and
Time Types”, for a description of the range of values each date and time type has and the valid
formats in which values may be specified.

Name Description

Add time values (intervals) to a date value

ADDDATE() SELECT ADDDATE('2008-05-15', INTERVAL 10 DAY) as


required_date;

Add time

ADDTIME() SELECT ADDTIME('2008-05-15 13:20:32.50','2 1:39:27.50') as


required_datetime;

Convert from one time zone to another

CONVERT_TZ() SELECT CONVERT_TZ('2008-05-15 12:00:00','+00:00','+10:00');

Return the current date

CURDATE() SELECT CURDATE();

Synonyms for CURDATE()

CURRENT_DATE(), SELECT CURRENT_DATE;


CURRENT_DATE

CURRENT_TIME(), Synonyms for CURTIME()


CURRENT_TIME
SELECT CURRENT_TIME;

CURRENT_TIMESTAMP(), Synonyms for NOW()


CURRENT_TIMESTAMP
SELECT CURRENT_TIMESTAMP;

Return the current time

CURTIME() SELECT CURTIME();

Add time values (intervals) to a date value

DATE_ADD() SELECT DATE_ADD(‘2008-05-15’, INTERVAL 10 DAY) as


required_date;

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 32


CORPORATE TRAINING BOOK – MYSQL

Examples:

1. Now():

2. Curdate():

3. Curtime():

4. Date_add():

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 33


CORPORATE TRAINING BOOK – MYSQL

5. Curtime():

6. Convert_TZ():

11.3 ENCRYPTION AND COMPRESSION FUNCTIONS

Name Description

AES_DECRYPT() Decrypt using AES

AES_ENCRYPT() Encrypt using AES

COMPRESS() Return result as a binary string

DECODE() Decodes a string encrypted using ENCODE()

DES_DECRYPT() Decrypt a string

DES_ENCRYPT() Encrypt a string

ENCODE() Encode a string

ENCRYPT() Encrypt a string

MD5() Calculate MD5 checksum

PASSWORD() Calculate and return a password string

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 34


CORPORATE TRAINING BOOK – MYSQL

SHA1(), SHA() Calculate an SHA-1 160-bit checksum

SHA2() Calculate an SHA-2 checksum

UNCOMPRESS() Uncompress a string compressed

UNCOMPRESSED_LENGTH() Return the length of a string before compression

Many encryption and compression functions return strings for which the result might contain
arbitrary byte values. If you want to store these results, use a column with a VARBINARY or BLOB
binary string data type. This will avoid potential problems with trailing space removal or character
set conversion that would change data values, such as may occur if you use a nonbinary string
data type (CHAR, VARCHAR, TEXT).

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 35


CORPORATE TRAINING BOOK – MYSQL

12. GROUP BY (AGGREGATE) FUNCTIONS

The group by clause is normally used along with five built-in, or "aggregate" functions. These
functions perform special operations on an entire table or on a set, or group, of rows rather than on
each row and then return one row of values for each group.the group by clause is normally used
along with five built-in, or "aggregate" functions. These functions perform special operations on an
entire table or on a set, or group, of rows rather than on each row and then return one row of
values for each group.

12.1 GROUP BY (AGGREGATE) FUNCTION DESCRIPTIONS

Name Description

AVG() Return the average value of the argument

BIT_AND() Return bitwise AND

BIT_OR() Return bitwise OR

BIT_XOR() Return bitwise XOR

COUNT() Return a count of the number of rows returned

COUNT(DISTINCT) Return the count of a number of different values

GROUP_CONCAT() Return a concatenated string

MAX() Return the maximum value

MIN() Return the minimum value

STD() Return the population standard deviation

STDDEV() Return the population

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 36


CORPORATE TRAINING BOOK – MYSQL

Example 1:

Example 2:

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 37


CORPORATE TRAINING BOOK – MYSQL

Example 3:
Testing Table:

Test2 Table

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 38


CORPORATE TRAINING BOOK – MYSQL

Result:

This section describes group (aggregate) functions that operate on sets of values. Unless
otherwise stated, group functions ignore NULL values.
If you use a group function in a statement containing no GROUP BY clause, it is equivalent to
grouping on all rows. For more information, “MySQL Handling of GROUP BY”.
For numeric arguments, the variance and standard deviation functions return a DOUBLE value.
The SUM() and AVG() functions return a DECIMAL value for exact-value arguments (integer or
DECIMAL), and a DOUBLE value for approximate-value arguments (FLOAT or DOUBLE).

12.2 GROUP BY MODIFIERS


The GROUP BY clause permits a WITH ROLLUP modifier that causes extra rows to be added to
the summary output. These rows represent higher-level (or super-aggregate) summary operations.
ROLLUP thus enables you to answer questions at multiple levels of analysis with a single query. It
can be used, for example, to provide support for OLAP (Online Analytical Processing) operations.
Suppose that a table named sales has year, country, product, and profit columns for recording
sales profitability:
CREATE TABLE sales
(
year INT NOT NULL,
country VARCHAR(20) NOT NULL,
product VARCHAR(32) NOT NULL,
profit INT
);

12.3 MYSQL HANDLING OF GROUP BY


In standard SQL, a query that includes a GROUP BY clause cannot refer to nonaggregated
columns in the select list that are not named in the GROUP BY clause. For example, this query is
illegal in standard SQL because the nonaggregated name column in the select list does not appear
in the GROUP BY:

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 39


CORPORATE TRAINING BOOK – MYSQL

SELECT o.custid, c.name, MAX(o.payment)


FROM orders AS o, customers AS c
WHERE o.custid = c.custid
GROUP BY o.custid;
For the query to be legal, the name column must be omitted from the select list or named in the
GROUP BY clause.
MySQL extends the standard SQL use of GROUP BY so that the select list can refer to
nonaggregated columns not named in the GROUP BY clause. This means that the preceding
query is legal in MySQL. You can use this feature to get better performance by avoiding
unnecessary column sorting and grouping. However, this is useful primarily when all values in each
nonaggregated column not named in the GROUP BY are the same for each group. The server is
free to choose any value from each group, so unless they are the same, the values chosen are
indeterminate. Furthermore, the selection of values from each group cannot be influenced by
adding an ORDER BY clause. Result set sorting occurs after values have been chosen, and
ORDER BY does not affect which values within each group the server chooses.

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 40


CORPORATE TRAINING BOOK – MYSQL

13. SQL STATEMENT SYNTAX

The select statement is used to select data from a database.the select statement is used to select
data from a database.

13.1 DATA DEFINITION STATEMENTS


ALTER DATABASE Syntax

ALTER EVENT Syntax


ALTER

[DEFINER = { user | CURRENT_USER }]

EVENT event_name

[ON SCHEDULE schedule]

[ON COMPLETION [NOT] PRESERVE]

[RENAME TO new_event_name]

[ENABLE | DISABLE | DISABLE ON SLAVE]

[COMMENT 'comment']

[DO event_body]

ALTER FUNCTION Syntax


ALTER FUNCTION func_name [characteristic ...]

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 41


CORPORATE TRAINING BOOK – MYSQL

characteristic:

COMMENT 'string'

| LANGUAGE SQL

| { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }

| SQL SECURITY { DEFINER | INVOKER }

ALTER LOGFILE GROUP Syntax

ALTER LOGFILE GROUP logfile_group

ADD UNDOFILE 'file_name'

[INITIAL_SIZE [=] size]

[WAIT]

ENGINE [=] engine_name

13.2 DATA MANIPULATION STATEMENTS


CALL Syntax

CALL sp_name([parameter[,...]])

CALL sp_name[()]

The CALL statement invokes a stored procedure that was defined previously with CREATE
PROCEDURE.

DELETE Syntax
Single-table syntax:

DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM tbl_name

[WHERE where_condition]

[ORDER BY ...]

[LIMIT row_count]

Multiple-table syntax:

DELETE [LOW_PRIORITY] [QUICK] [IGNORE]

tbl_name[.*] [, tbl_name[.*]] ...

FROM table_references

[WHERE where_condition]

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 42


CORPORATE TRAINING BOOK – MYSQL

13.3 MYSQL UTILITY STATEMENTS

DESCRIBE Syntax

The DESCRIBE and EXPLAIN statements are synonyms, used either to obtain information about
table structure or query execution plans. For more information

EXPLAIN Syntax
{EXPLAIN | DESCRIBE | DESC}
tbl_name [col_name | wild]
{EXPLAIN | DESCRIBE | DESC}
[explain_type] SELECT select_options

explain_type: {EXTENDED | PARTITIONS}


The DESCRIBE and EXPLAIN statements are synonyms. In practice, the DESCRIBE keyword is
more often used to obtain information about table structure, whereas EXPLAIN is used to obtain a
query execution plan (that is, an explanation of how MySQL would execute a query). The following

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 43


CORPORATE TRAINING BOOK – MYSQL

discussion uses the DESCRIBE and EXPLAIN keywords in accordance with those uses, but the
MySQL parser treats them as completely synonymous.

HELP Syntax
HELP 'search_string'
The HELP statement returns online information from the MySQL Reference manual. Its proper
operation requires that the help tables in the mysql database be initialized with help topic
information

USE Syntax
USE db_name
The USE db_name statement tells MySQL to use the db_name database as the default (current)
database for subsequent statements. The database remains the default until the end of the session
or another USE statement is issued:
USE db1;
SELECT COUNT(*) FROM mytable; # selects from db1.mytable
USE db2;
SELECT COUNT(*) FROM mytable; # selects from db2.mytable

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 44


CORPORATE TRAINING BOOK – MYSQL

14. STORED PROGRAMS AND VIEWS

This chapter discusses stored programs and views, which are database objects defined in terms of
sql code that is stored on the server for later execution.
Views are stored queries that when referenced produce a result set. A view acts as a virtual table.

14.1 DEFINING STORED PROGRAMS

Each stored program contains a body that consists of an SQL statement. This statement may be a
compound statement made up of several statements separated by semicolon (;) characters. For
example, the following stored procedure has a body made up of a BEGIN ... END block that
contains a SET statement and a REPEAT loop that itself contains another SET statement:
CREATE PROCEDURE dorepeat(p1 INT)

BEGIN

SET @x = 0;

REPEAT SET @x = @x + 1; UNTIL @x > p1 END REPEAT;

END;

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 45


CORPORATE TRAINING BOOK – MYSQL

14.2 USING STORED ROUTINES (PROCEDURES AND FUNCTIONS)

1) Stored Routine Syntax


2) Stored Routines and MySQL Privileges
3) Stored Routine Metadata
4) Stored Procedures, Functions, Triggers, and LAST_INSERT_ID()
MySQL supports stored routines (procedures and functions). A stored routine is a set of SQL
statements that can be stored in the server. Once this has been done, clients don't need to keep
reissuing the individual statements but can refer to the stored routine instead.
Stored routines require the proc table in the mysql database. This table is created during the
MySQL installation procedure. If you are upgrading to MySQL 5.5 from an earlier version, be sure
to update your grant tables to make sure that the proc table exists. See Section 4.4.7,
“mysql_upgrade — Check and Upgrade MySQL Tables”.

Stored routines can be particularly useful in certain situations:


1) When multiple client applications are written in different languages or work on different
platforms, but need to perform the same database operations.
2) When security is paramount. Banks, for example, use stored procedures and functions for
all common operations. This provides a consistent and secure environment, and routines
can ensure that each operation is properly logged. In such a setup, applications and users
would have no access to the database tables directly, but can only execute specific stored
routines.

14.3 USING TRIGGERS

1) Trigger Syntax and Examples

2) Trigger Metadata

A trigger is a named database object that is associated with a table, and that activates when a
particular event occurs for the table. Some uses for triggers are to perform checks of values to be
inserted into a table or to perform calculations on values involved in an update.
A trigger is defined to activate when a statement inserts, updates, or deletes rows in the associated
table. These row operations are trigger events. For example, rows can be inserted by INSERT or
LOAD DATA statements, and an insert trigger activates for each inserted row. A trigger can be set
to activate either before or after the trigger event. For example, you can have a trigger activate
before each row that is inserted into a table or after each row that is updated.

Trigger Syntax and Examples


To create a trigger or drop a trigger, use the CREATE TRIGGER or DROP TRIGGER statement,
described in Section 13.1.19, “CREATE TRIGGER Syntax”, and Section 13.1.30, “DROP
TRIGGER Syntax”.
Here is a simple example that associates a trigger with a table, to activate for INSERT operations.
The trigger acts as an accumulator, summing the values inserted into one of the columns of the
table.
mysql> CREATE TABLE account (acct_num INT, amount DECIMAL(10,2));

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 46


CORPORATE TRAINING BOOK – MYSQL

Query OK, 0 rows affected (0.03 sec)

mysql> CREATE TRIGGER ins_sum BEFORE INSERT ON account

-> FOR EACH ROW SET @sum = @sum + NEW.amount;

Query OK, 0 rows affected (0.06 sec)

Trigger Metadata

Metadata about triggers can be obtained as follows:

1) Query the TRIGGERS table of the INFORMATION_SCHEMA database.

2) Use the SHOW CREATE TRIGGER statement.

3) Use the SHOW TRIGGERS statement.

14.4 USING VIEWS

View Syntax
The CREATE VIEW statement creates a new view (see Section 13.1.20, “CREATE VIEW Syntax”).
To alter the definition of a view or drop a view, use ALTER VIEW (see Section 13.1.9, “ALTER
VIEW Syntax”), or DROP VIEW (see Section 13.1.31, “DROP VIEW Syntax”).
A view can be created from many kinds of SELECT statements. It can refer to base tables or other
views. It can use joins, UNION, and subqueries. The SELECT need not even refer to any tables.
The following example defines a view that selects two columns from another table, as well as an
expression calculated from those columns:
mysql> CREATE TABLE t (qty INT, price INT);
mysql> INSERT INTO t VALUES(3, 50), (5, 60);

mysql> CREATE VIEW v AS SELECT qty, price, qty*price AS value FROM t;

mysql> SELECT * FROM v;

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

| qty | price | value |

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

| 3| 50 | 150 |

| 5| 60 | 300 |

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

mysql> SELECT * FROM v WHERE qty = 5;

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

| qty | price | value |

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 47


CORPORATE TRAINING BOOK – MYSQL

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

| 5| 60 | 300 |

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

View Processing Algorithms


The optional ALGORITHM clause for CREATE VIEW or ALTER VIEW is a MySQL extension to
standard SQL. It affects how MySQL processes the view. ALGORITHM takes three values:
MERGE, TEMPTABLE, or UNDEFINED.
1) For MERGE, the text of a statement that refers to the view and the view definition are
merged such that parts of the view definition replace corresponding parts of the statement.
2) For TEMPTABLE, the results from the view are retrieved into a temporary table, which then
is used to execute the statement.
3) For UNDEFINED, MySQL chooses which algorithm to use. It prefers MERGE over
TEMPTABLE if possible, because MERGE is usually more efficient and because a view
cannot be updatable if a temporary table is used.
4) If no ALGORITHM clause is present, UNDEFINED is the default algorithm.

Updatable and Insertable Views


Some views are updatable and references to them can be used to specify tables to be updated in
data change statements. That is, you can use them in statements such as UPDATE, DELETE, or
INSERT to update the contents of the underlying table.
For a view to be updatable, there must be a one-to-one relationship between the rows in the view
and the rows in the underlying table. There are also certain other constructs that make a view
nonupdatable. To be more specific, a view is not updatable if it contains any of the following:

1) Aggregate functions (SUM(), MIN(), MAX(), COUNT(), and so forth)

2) DISTINCT

3) GROUP BY

4) HAVING

5) UNION or UNION ALL

6) Subquery in the select list

7) Certain joins (see additional join discussion later in this section)

8) Reference to nonupdatable view in the FROM clause

9) Subquery in the WHERE clause that refers to a table in the FROM clause

10) Refers only to literal values (in this case, there is no underlying table to update)

11) ALGORITHM = TEMPTABLE (use of a temporary table always makes a view


nonupdatable)

12) Multiple references to any column of a base table

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 48


CORPORATE TRAINING BOOK – MYSQL

15. REAL TIME EXAMPLE

Polling

Create Question Table Syntax:

Select Question Table Syntax:

Create Option1 Table Syntax:

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 49


CORPORATE TRAINING BOOK – MYSQL

Select Option1 Table Syntax:

Create vote2 Table Syntax:

Select vote2 Table Syntax:

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 50


CORPORATE TRAINING BOOK – MYSQL

Poll Result:

Copyrights © 2016 BigSpire Software Private Limited. All Rights Reserved 51

You might also like