Joins
Joins
Constraints are the rules enforced on the data columns of a table. These are
used to limit the type of data that can go into a table. This ensures the
accuracy and reliability of the data in the database.
Constraints could be either on a column level or a table level. The column level
constraints are applied only to one column, whereas the table level constraints
are applied to the whole table.
Following are some of the most commonly used constraints available in SQL.
These constraints have already been discussed in SQL - RDBMS Concepts
chapter, but it’s worth to revise them at this point.
NOT NULL Constraint − Ensures that a column cannot have NULL value.
CHECK Constraint − The CHECK constraint ensures that all the values in a
column satisfies certain conditions.
INDEX − Used to create and retrieve data from the database very quickly.
Constraints can be specified when a table is created with the CREATE TABLE
statement or you can use the ALTER TABLE statement to create constraints
even after the table is created.
Dropping Constraints
Any constraint that you have defined can be dropped using the ALTER TABLE
command with the DROP CONSTRAINT option.
For example, to drop the primary key constraint in the EMPLOYEES table, you
can use the following command.
There are many types of integrity constraints that play a role in Referential
Integrity (RI). These constraints include Primary Key, Foreign Key, Unique
Constraints and other constraints which are mentioned above.
The DEFAULT constraint provides a default value to a column when the INSERT
For example, the following SQL creates a new table called CUSTOMERS and
adds five columns. Here, the SALARY column is set to 5000.00 by default, so in
case the INSERT INTO statement does not provide a value for this column,
);
If the CUSTOMERS table has already been created, then to add a DEFAULT
constraint to the SALARY column, you would write a query like the one which is
If the CUSTOMERS table has already been created, then to add a UNIQUE
constraint to the AGE column. You would write a statement like the query that
is given in the code block below.
You can also use the following syntax, which supports naming the constraint in
multiple columns as well.
If you are using MySQL, then you can use the following syntax −
A column or columns is called primary key (PK) that uniquely identifies each
row in the table.
If you want to create a primary key, you should define a PRIMARY KEY
constraint when you create or modify a table.
In designing the composite primary key, you should use as few columns as
possible. It is good for storage and performance both, the more columns you
use for primary key the more storage space you require.
Inn terms of performance, less data means the database can process faster.
When we specify a primary key constraint for a table, database engine automatically
creates a unique index for the primary key column.
In oracle, it is not allowed for a primary key to contain more than 32 columns.
SQL primary key for one column:
The following SQL command creates a PRIMARY KEY on the "S_Id" column
when the "students" table is created.
MySQL:
Note:you should note that in the above example there is only one PRIMARY
KEY (pk_StudentID). However it is made up of two columns (S_Id and
LastName).
When you use ALTER TABLE statement to add a primary key, the primary key columns
must not contain NULL values (when the table was first created).
If you want to DROP (remove) a primary key constraint, you should use
following syntax:
MySQL:
1. ALTER TABLE students
2. DROP PRIMARY KEY
next>><<prev
SQL FOREIGN KEY
In simple words you can say that, a foreign key in one table used to point
primary key in another table.
Here are two tables first one is students table and second is orders table.
Here orders are given by students.
First table:
1 MAURYA AJEET
2 JAISWAL RATAN
3 ARORA SAUMYA
Second table:
O_Id OrderNo
1 99586465
2 78466588
3 22354846
4 57698656
Here you see that "S_Id" column in the "Orders" table points to the "S_Id" column in
"Students" table.
o The "S_Id" column in the "Students" table is the PRIMARY KEY in the
"Students" table.
To create a foreign key on the "S_Id" column when the "Orders" table is
created:
MySQL:
If you want to drop a FOREIGN KEY constraint, use the following syntax:
MySQL:
These are some important difference between primary key and foreign key
in SQL-
Primary key cannot be null on the other hand foreign key can be null.
Primary key uniquely identify a record in a table while foreign key is a field
in a table that is primary key in another table.
There is only one primary key in the table on the other hand we can have
more than one foreign key in the table.
By default primary key adds a clustered index on the other hand foreign key
does not automatically create an index, clustered or non-clustered. You
must manually create an index for foreign key.
Sometimes more than one attributes are needed to uniquely identify an entity.
A primary key that is made by the combination of more than one attribute is
known as a composite key.
Columns that make up the composite key can be of different data types.
MySQL:
SQL INDEXES
Indexes are special lookup tables that the database search engine can use
to speed up data retrieval. Simply put, an index is a pointer to data in a table.
An index in a database is very similar to an index in the back of a book.
For example, if you want to reference all pages in a book that discusses a
certain topic, you first refer to the index, which lists all the topics alphabetically
and are then referred to one or more specific page numbers.
An index helps to speed up SELECT queries and WHERE clauses, but it slows
down data input, with the UPDATE and the INSERT statements. Indexes can
be created or dropped with no effect on the data.
Imagine you have a table called users and you want to search for all the users
which have the last name 'Smith'. Without an index, the database would have
to go through all the records of the table: this is slow, because the more
records you have in your database, the more work it has to do to find the
result. On the other hand, an index will help the database skip quickly to the
relevant pages where the 'Smith' records are held. This is very similar to how
we, humans, go through a phone book directory to find someone by the last
name: We don't start searching through the directory from cover to cover, as
long we inserted the information in some order that we can use to skip quickly
to the 'S' pages.
Primary keys and unique keys are similar. A primary key is a column, or a
combination of columns, that can uniquely identify a row. It is a special case of
unique key. A table can have at most one primary key, but more than one
unique key. When you specify a unique key on a column, no two distinct rows
in a table can have the same value.
Also note that columns defined as primary keys or unique keys are
automatically indexed in MySQL.
So
All tables must have a primary key, which is used to uniquely identify each of
the relation's entries. It may also have foreign keys, which link tables
together.
Indexes are used to make searching by keys faster, and to help enforce
constraints. Constraints might be used to ensure that the primary key is
unique, or that the foreign key references a valid entry in its target table.
Creating an index involves the CREATE INDEX statement, which allows you to
name the index, to specify the table and which column or columns to index,
and to indicate whether the index is in an ascending or descending order.
Indexes can also be unique, like the UNIQUE constraint, in that the index
prevents duplicate entries in the column or combination of columns on which
there is an index.
The CREATE INDEX Command
The basic syntax of a CREATE INDEX is as follows.
If the CUSTOMERS table has already been created, then to add a CHECK
constraint to AGE column, you would write a statement like the one given
below.
SQL JOINS
As the name shows, JOIN means to combine something. In case of SQL, JOIN means "to
combine two or more tables".
The SQL JOIN clause takes records from two or more tables in a database and combines it
together.
ANSI standard SQL defines five types of JOIN :
1.inner join,
2.left outer join,
3.right outer join,
4.full outer join, and
5.cross join.
In the process of joining, rows of both tables are combined in a single table.
Why SQL JOIN is used?
If you want to access more than one table through a select statement.
If you want to combine two or more table then SQL JOIN statement is used .it combines
rows of that tables in one table and one can retrieve the information by a SELECT
statement.
The joining of two or more tables is based on common field between them.
SQL INNER JOIN also known as simple join is the most common type of join.
2.Payment table
Payment_IDDATE Staff_ID AMOUNT
3 MONTY 25 2500
1 ARYAN 22 3000
4 AMIT 25 3500
1 ARYAN 51 56000
2 AROHI 21 25000
3 VINEET 24 31000
4 AJEET 23 32000
5 RAVI 23 42000
This is second table
ORDER TABLE:
O_ID DATE CUSTOMER_ID AMOUNT
This will list all customers, whether they placed any order or not.
The ORDER BY TotalAmount shows the customers without orders first (i.e. TotalMount is
NULL).
The SQL right join returns all the values from the rows of right table. It also includes the
matched values from left table but if there is no matching in both tables, it returns NULL.
Basic syntax for right join:
SELECT table1.column1, table2.column2.....
FROM table1
RIGHT JOIN table2
ON table1.column_field = table2.column_field;
let us take an example with 2 tables table1 is CUSTOMERS table and table2 is ORDERS
table.
CUSTOMER TABLE:
ID NAME AGE SALARY
1 ARYAN 51 56000
2 AROHI 21 25000
3 VINEET 24 31000
4 AJEET 23 32000
5 RAVI 23 42000
Here we will join these two tables with SQL RIGHT JOIN:
SELECT ID,NAME,AMOUNT,DATE
FROM CUSTOMER
RIGHT JOIN ORDER
ON CUSTOMER.ID = ORDER.CUSTOMER_ID;
//////////
DEPARTMENT AND EMP
RIGH OUTER JOIN EG
LIST OF ALL STUDENTS WEATHER DEPT IS ASSIGNED OR NOT
DEPT
1 HR
2 FINANCE
3 DEV
EMPLOYEE
1 PARIMAL 1
2 ANIKET 1
3 VIDYABHUSHAN 2
4 SHUBHAM
5 PRANAV
PARIMAL HR
ANIKET HR
VIDYABHUSHAN FINANCE
SHUBHAM NULL
PRANAV NULL
if innert join
PARIMAL HR
ANIKET HR
VIDYABHUSHAN FINANCE
IF LEFT JOIN
HR PARIMAL
HR ANIKET
FINANCE VIDYABHUSHAN
/////////
ID NAME AMOUNT DATE
Results: 2 records
TotalAmount FirstName LastName City Country
FULL JOIN returns all matching records from both tables whether the other table
matches or not.
FULL JOIN can potentially return very large datasets.
FULL JOIN and FULL OUTER JOIN are the same.
Let us take two tables to demonstrate full outer join:
table_A
A M
1 m
2 n
4 o
table_B
A N
2 p
3 q
5 r
Resulting table
A M A N
2 n 2 p
1 m - -
4 o - -
- - 3 q
- - 5 r
Because this is a full outer join so all rows (both matching and non-matching) from both
tables are included in the output. Here only one row of output displays values in all columns
because there is only one match between table_A and table_B.
MySQL does not support FULL JOIN, you can use UNION ALL clause to
combine these two JOINS as shown below.
The CARTESIAN JOIN or CROSS JOIN returns the Cartesian product of the sets
of records from two or more joined tables. Thus, it equates to an inner join
where the join-condition always evaluates to either True or where the join-
condition is absent from the statement.
Syntax
The basic syntax of the CARTESIAN JOIN or the CROSS JOIN is as follows −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Table 2: ORDERS Table is as follows −
+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables using INNER JOIN as follows −
Results: 88 records
1. SELECT column-names
2. FROM table-name
3. UNION
4. SELECT column-names
5. FROM table-name
SUPPLIER
Id
CompanyName
ContactName
City
Country
Phone
Fax
CUSTOMER
Id
FirstName
LastName
City
Country
Phone
Results:
SQL Subqueries
There is no general syntax; subqueries are regular queries placed inside parenthesis.
Subqueries can be used in different ways and at different locations inside a query:
Here is an subquery with the IN operator
1. SELECT column-names
2. FROM table-name1
3. WHERE value IN (SELECT column-name
4. FROM table-name2
5. WHERE condition)
PRODUCT
Id
ProductName
SupplierId
UnitPrice
Package
IsDiscontinued
SQL Subquery Examples
1. SELECT ProductName
2. FROM Product
3. WHERE Id IN (SELECT ProductId
4. FROM OrderItem
5. WHERE Quantity > 100)
Results: 12 records
PoductName
Guaraná Fantástica
Schoggi Schokolade
Chartreuse verte
Rogede sild
Perth Pasties
CUSTOMER
Id
FirstName
LastName
City
Country
Phone
ORDER
Id
OrderDate
OrderNumber
CustomerId
TotalAmount
This is a correlated subquery because the subquery references the enclosing query (i.e.
the C.Id in the WHERE clause).
Results: 91 records
Maria Anders 6
Ana Trujillo 4
Antonio Moreno 7
Thomas Hardy 13
Christina Berglund 18
Hanna Moos 7
Frédérique Citeaux 11
Martín Sommer 3
1. SELECT column-names
2. FROM table-name
3. WHERE EXISTS
4. (SELECT column-name
5. FROM table-name
6. WHERE condition)
SUPPLIER
Id
CompanyName
ContactName
City
Country
Phone
Fax
PRODUCT
Id
ProductName
SupplierId
UnitPrice
Package
IsDiscontinued
1. SELECT CompanyName
2. FROM Supplier A
3. WHERE EXISTS
4. (SELECT ProductName
5. FROM Product B
6. WHERE B.SupplierId = A.Supplier.Id
7. AND UnitPrice > 100)
This is a correlated subquery because the subquery references the enclosing query (with
Supplier.Id).
Results: 2 records
CompanyName
Plutzer Lebensmittelgroßmärkte AG
Aux joyeux ecclésiastiques
price
1 c1 1 o1 c1 5
2 c2 2 o2 c2 5
3 c3 3 o3 c3 5
4 o4 c1 101
5 o5 c2 5
c1 1 6 o6 c3 5
4 c1,9
2 c1 7 o7 c4 5
c3 3 8 c3 8 o8 c3 232
9 o9 c1 104
c1 1 10 o10 c4 5
2
c3 3
Views
A view can be simply thought of as a SQL query stored permanently on the server.
Whatever indices the query optimizes to will be used. In that sense, there is no difference
between the SQL query or a view. It does not affect performance any more negatively than
the actual SQL query. If anything, since it is stored on the server, and does not need to be
evaluated at run time, it is actually faster.
It does afford you these additional advantages
reusability
a single source for optimization
Data is auto refreshed when view query is fired.
Creating simple views
Let’s take a look at the orderDetails table. We can create a view that represents total
sales per order.
The table_type column in the result set specifies which object is view and which
object is a table (base table).
If we want to query total sales for each sales order, you just need to execute a
simple SELECT statement against the SalePerOrder view as follows:
1 SELECT
2 *
3 FROM
4 salePerOrder;
Creating a view based on another view
MySQL allows you to create a view based on another view. For example, you can create
a view called big sales order based on the SalesPerOrder view to show every sales
order whose total is greater than 60,000 as follows:
1 SELECT
2 orderNumber, total
3 FROM
4 BigSalesOrder;
The following is an example of creating a view with INNER JOIN . The view contains
the order number, customer name, and total sales per order.
1 SELECT
2 *
3 FROM
4 customerOrders;
The following illustrates how to create a view with a subquery. The view contains
products whose buy prices are higher than the average price of all products.
1 SELECT
2 *
3 FROM
4 aboveAvgProducts;
SQL - Transactions
A transaction is a unit of work that is performed against a database.
Transactions are units or sequences of work accomplished in a logical order,
whether in a manual fashion by a user or automatically by some sort of a
database program.
Practically, you will club many SQL queries into a group and you will execute
all of them together as a part of a transaction.
Properties of Transactions
Transactions have the following four standard properties, usually referred to by
the acronym ACID.
Atomicity − ensures that all operations within the work unit are
completed successfully. Otherwise, the transaction is aborted at the point
of failure and all the previous operations are rolled back to their former
state.
COMMIT;
Example
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example which would delete those records from the table which
have age = 25 and then COMMIT the changes in the database.
Thus, two rows from the table would be deleted and the SELECT statement
would produce the following result.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
The ROLLBACK Command
The ROLLBACK command is the transactional command used to undo
transactions that have not already been saved to the database. This command
can only be used to undo transactions since the last COMMIT or ROLLBACK
command was issued.
ROLLBACK;
Example
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example, which would delete those records from the table
which have the age = 25 and then ROLLBACK the changes in the database.
Thus, the delete operation would not impact the table and the SELECT
statement would produce the following result.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
The SAVEPOINT Command
A SAVEPOINT is a point in a transaction when you can roll the transaction back
to a certain point without rolling back the entire transaction.
SAVEPOINT SAVEPOINT_NAME;
This command serves only in the creation of a SAVEPOINT among all the
transactional statements. The ROLLBACK command is used to undo a group of
transactions.
ROLLBACK TO SAVEPOINT_NAME;
Following is an example where you plan to delete the three different records
from the CUSTOMERS table. You want to create a SAVEPOINT before each
delete, so that you can ROLLBACK to any SAVEPOINT at any time to return the
appropriate data to its original state.
Example
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Now that the three deletions have taken place, let us assume that you have
changed your mind and decided to ROLLBACK to the SAVEPOINT that you
identified as SP2. Because SP2 was created after the first deletion, the last two
deletions are undone −
Notice that only the first deletion took place since you rolled back to SP2.
SQL Injection
SQL Injection is an attack that poisons dynamic SQL statements to comment out certain
parts of the statement or appending a condition that will always be true. It takes advantage
of the design flaws in poorly designed web applications to exploit SQL statements to
execute malicious SQL code.
Look at the example above again. The original purpose of the code was to
create an SQL statement to select a user, with a given user id.
If there is nothing to prevent a user from entering "wrong" input, the user can
enter some "smart" input like this:
UserId: 105 OR
105 OR 1=1
The SQL above is valid and will return ALL rows from the "Users" table,
since OR 1=1 is always TRUE.
Does the example above look dangerous? What if the "Users" table contains
names and passwords?
A hacker might get access to all the user names and passwords in a database,
by simply inserting 105 OR 1=1 into the input field.
SQL Injection Based on ""="" is Always True
Username:
John Doe
Password:
myPass
Example
uName = getRequestString("username");
uPass = getRequestString("userpassword");
sql = 'SELECT * FROM Users WHERE Name ="' + uName + '" AND Pass ="' +
uPass + '"'
Result
SELECT * FROM Users WHERE Name ="John Doe" AND Pass ="myPass"
User Name:
Password:
The code at the server will create a valid SQL statement like this:
Result
SELECT * FROM Users WHERE Name ="" or ""="" AND Pass ="" or ""=""
The SQL above is valid and will return all rows from the "Users" table, since OR
""="" is always TRUE.
The SQL statement below will return all rows from the "Users" table, then
delete the "Suppliers" table.
Example
SELECT * FROM Users; DROP TABLE Suppliers
Example
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
Result
SELECT * FROM Users WHERE UserId = 105; DROP TABLE Suppliers;
[mysqld]
autocommit=0
or
changed to
max_connections = 1000
MySQL SERVER
It is multithreaded.
It (usually) acts as a TCP/IP server, accepting connections.
Each connection gets a dedicated thread.
You can show MySQL open database connections (and other MySQL database parameters)
using the MySQL show status command, like this:
+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| Aborted_connects |0 |
| Connections |8 |
| Max_used_connections |4 |
| Ssl_client_connects |0 |
| Ssl_connect_renegotiates | 0 |
| Ssl_finished_connects |0 |
| Threads_connected |4 |
+--------------------------+-------+
All those rows and values that are printed out correspond to MySQL variables that you can
look at. Notice that I use like 'Conn%'in the first example to show variables that look
like "Connection", then got a little wiser in my second MySQL show status query.
Here's what my MySQL processlist looks like when I had my Java application actively
running under Tomcat:
+----+------+-----------------+--------+---------+------+-------+------------------+
| Id | User | Host | db | Command | Time | State | Info |
+----+------+-----------------+--------+---------+------+-------+------------------+
+----+------+-----------------+--------+---------+------+-------+------------------+
+----+------+-----------+--------+---------+------+-------+------------------+
| Id | User | Host | db | Command | Time | State | Info |
+----+------+-----------+--------+---------+------+-------+------------------+
+----+------+-----------+--------+---------+------+-------+------------------+
MySQL comes with a handy little diagnostic tool called mysqlslap that's been around since
version 5.1.4. It's a benchmarking tool that can help DBAs and developers load test their
database servers.
mysqlslap can emulate a large number of client connections hitting the database server at
the same time. The load testing parameters are fully configurable and the results from
different test runs can be used to fine-tune database design or hardware resources.
In this tutorial we will learn how to use mysqlslap to load test a MySQL database with some
basic queries and see how benchmarking can help us fine-tune those queries. After some
basic demonstrations, we will run through a fairly realistic test scenario where we create a
copy of an existing database for testing, glean queries from a log, and run the test from a
script.
Using mysqlslap
We can now start using mysqlslap. mysqlslap can be invoked from a regular shell prompt
so there's no need to explicitly log in to MySQL. For this tutorial, though, we will open
another terminal connection to our Linux server and start a new MySQL session from there
with the sysadmin user we created before, so we can check and update a few things in
MySQL more easily. So, we'll have one prompt open with our sudo user, and one prompt
logged into MySQL.
Before we get into specific commands for testing, you may want to take a look at this list of
the most useful mysqlslap options. This can help you design your own mysqlslap
commands later.
--password Password for the user account. It's best to leave it blank in command line
--port Port number for connecting to MySQL if the default is not used
The query to execute. This can either be a SQL query string or a path to
--query
a SQL script file
The query to create a table. Again, this can be a query string or a path to
--create
a SQL file
--auto-generate- Lets MySQL perform load testing with its own auto-generated SQL
sql command
or
Benchmark
BEGIN
END;
$$
call eexam.mybranch();
Why Stored Procedures?
Stored procedures are fast. MySQL server takes some advantage of caching, just as
prepared statements do. The main speed gain comes from reduction of network traffic.
If you have a repetitive task that requires checking, looping, multiple statements, and no
user interaction, do it with a single call to a procedure that's stored on the server.
Stored procedures are portable. When you write your stored procedure in SQL, you
know that it will run on every platform that MySQL runs on, without obliging you to install
an additional runtime-environment package, or set permissions for program execution in
the operating system, or deploy different packages if you have different computer types.
That's the advantage of writing in SQL rather than in an external language like Java or
C or PHP.
Stored procedures are always available as 'source code' in the database itself. And it
makes sense to link the data with the processes that operate on the data.
Stored procedures are migratory! MySQL adheres fairly closely to the SQL:2003
standard. Others (DB2, Mimer) also adhere.
Create Procedure
Following statements create a stored procedure. By default, a procedure is associated with
the default database (currently used database). To associate the procedure with a given
database, specify the name as database_name.stored_procedure_name when you create
it. Here is the complete syntax :
Syntax :
CREATE [DEFINER = { user | CURRENT_USER }]
type:
characteristic:
COMMENT 'string'
| LANGUAGE SQL
| [NOT] DETERMINISTIC
routine_body:
Before create a procedure we need some information which are described in this section :
Check the MySQL version :
Following command displays the version of MySQL :
mysql>SELECT VERSION();
+-----------+
| VERSION() |
+-----------+
| 5.6.12 |
+-----------+
1 row in set (0.00 sec)
Check the privileges of the current user :
CREATE PROCEDURE and CREATE FUNCTION require the CREATE ROUTINE
privilege. They might also require the SUPER privilege, depending on the DEFINER value,
as described later in this section. If binary logging is enabled, CREATE FUNCTION might
require the SUPER privilege. By default, MySQL automatically grants the ALTER
ROUTINE and EXECUTE privileges to the routine creator. This behavior can be changed
by disabling the automatic_sp_privileges system variable.
mysql> SHOW PRIVILEGES;
+-----------------+----------------------------+-------------------------------------------------------+
| Privilege | Context | Comment |
+-----------------+----------------------------+-------------------------------------------------------+
| Alter | Tables | To alter the table |
| Alter routine | Functions,Procedures | To alter or drop stored
functions/procedures |
| Create | Databases,Tables,Indexes | To create new databases and tables
|
| Create routine | Databases | To use CREATE FUNCTION/PROCEDURE
|
| Create temporary| Databases | To use CREATE TEMPORARY TABLE
|
| tables | | |
| Create view | Tables | To create new views |
| Create user | Server Admin | To create new users |
| Delete | Tables | To delete existing rows |
| Drop | Databases,Tables | To drop databases, tables, and views |
| Event | Server Admin | To create, alter, drop and execute events |
| Execute | Functions,Procedures | To execute stored routines |
| File | File access on server | To read and write files on the server |
| Grant option | Databases,Tables, | To give to other users those privileges you
possess |
| | Functions,Procedures | |
| Index | Tables | To create or drop indexes |
| Insert | Tables | To insert data into tables |
| Lock tables | Databases | To use LOCK TABLES (together with SELECT
privilege) |
| Process | Server Admin | To view the plain text of currently executing
queries |
| Proxy | Server Admin | To make proxy user possible |
| References | Databases,Tables | To have references on tables |
| Reload | Server Admin | To reload or refresh tables, logs and privileges |
| Replication | Server Admin | To ask where the slave or master servers are
|
| client | | |
| Replication | Server Admin | To read binary log events from the master
|
| slave | | |
| Select | Tables | To retrieve rows from table |
| Show databases | Server Admin | To see all databases with SHOW
DATABASES |
| Show view | Tables | To see views with SHOW CREATE VIEW
|
| Shutdown | Server Admin | To shut down the server |
| Super | Server Admin | To use KILL thread, SET GLOBAL, CHANGE
MASTER, etc. |
| Trigger | Tables | To use triggers |
| Create | Server Admin | To create/alter/drop tablespaces |
| tablespace | | |
| Update | Tables | To update existing rows |
| Usage | Server Admin | No privileges - allow connect only |
+-------------------------+--------------------+-------------------------------------------------------+
31 rows in set (0.00 sec)
Select a database :
Before creates a procedure we must select a database. Let see the list of databases and
choose one of them.
mysql> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| hr |
| mysql |
| performance_schema |
| sakila |
| test |
| world |
+--------------------+
7 rows in set (0.06 sec))
Now select the database 'hr' and list the tables :
mysql> USE hr;
Database changed
mysql> SHOW TABLES;
+--------------+
| Tables_in_hr |
+--------------+
| alluser |
| departments |
| emp_details |
| job_history |
| jobs |
| locations |
| regions |
| user |
| user_details |
+--------------+
9 rows in set (0.00 sec)
Pick a Delimiter
The delimiter is the character or string of characters which is used to complete an SQL
statement. By default we use semicolon (;) as a delimiter. But this causes problem in stored
procedure because a procedure can have many statements, and everyone must end with a
semicolon. So for your delimiter, pick a string which is rarely occur within statement or
within procedure. Here we have used double dollar sign i.e. $$.You can use whatever you
want. To resume using ";" as a delimiter later, say "DELIMITER ; $$". See here how to
change the delimiter :
mysql> DELIMITER $$ ;
Now the default DELIMITER is "$$". Let execute a simple SQL command :
mysql> SELECT * FROM user $$
+----------+-----------+--------+
| userid | password | name |
+----------+-----------+--------+
| scott123 | 123@sco | Scott |
| ferp6734 | dloeiu@&3 | Palash |
| diana094 | ku$j@23 | Diana |
+----------+-----------+--------+
3 rows in set (0.00 sec)
Now you write and run your own procedure, see the following example :
MySQL workbench (5.3 CE) : -
Select MySQL workbench from Start menu :
After selecting MySQL workbench following login screen will come :
Now input the login details :
After successful login a new screen will come and from the object browser panel select a
database :
After selecting the database right click on Routines a new popup will come :
After selecting "Create Procedure" following screen will come where you can write your
own procedure.
After writing the procedure click on Apply button and the following screen will come :
Next screen will be to review the script and apply on the database.
Now click on Finish button and run the procedure :
Call a procedure
The CALL statement is used to invoke a procedure that is stored in a DATABASE. Here is
the syntax :
CALL sp_name([parameter[,...]])
CALL sp_name[()]
Stored procedures which do not accept arguments can be invoked without parentheses.
Therefore CALL job_data() and CALL job_data are equivalent. Let execute the procedure.
mysql> CALL job_data$$
+------------+---------------------------------+------------+------------+
| JOB_ID | JOB_TITLE | MIN_SALARY | MAX_SALARY |
+------------+---------------------------------+------------+------------+
| AD_PRES | President | 20000 | 40000 |
| AD_VP | Administration Vice President | 15000 | 30000 |
| AD_ASST | Administration Assistant | 3000 | 6000 |
| FI_MGR | Finance Manager | 8200 | 16000 |
| FI_ACCOUNT | Accountant | 4200 | 9000 |
| AC_MGR | Accounting Manager | 8200 | 16000 |
| AC_ACCOUNT | Public Accountant | 4200 | 9000 |
| SA_MAN | Sales Manager | 10000 | 20000 |
| SA_REP | Sales Representative | 6000 | 12000 |
| PU_MAN | Purchasing Manager | 8000 | 15000 |
| PU_CLERK | Purchasing Clerk | 2500 | 5500 |
| ST_MAN | Stock Manager | 5500 | 8500 |
| ST_CLERK | Stock Clerk | 2000 | 5000 |
| SH_CLERK | Shipping Clerk | 2500 | 5500 |
| IT_PROG | Programmer | 4000 | 10000 |
| MK_MAN | Marketing Manager | 9000 | 15000 |
| MK_REP | Marketing Representative | 4000 | 9000 |
| HR_REP | Human Resources Representative | 4000 | 9000 |
| PR_REP | Public Relations Representative | 4500 | 10500 |
+------------+---------------------------------+------------+------------+
19 rows in set (0.00 sec)Query OK, 0 rows affected (0.15 sec)
SHOW CREATE PROCEDURE
This statement is a MySQL extension. It returns the exact string that can be used to re-
create the named stored procedure. Both statement require that you be the owner of the
routine. Here is the syntax :
SHOW CREATE PROCEDURE proc_name
BEGIN
[statement_list]
END
[end_label])
+------+------+------+
|a |b |c |
+------+------+------+
| 110 | 2 | 112 |
+------+------+------+
1 row in set (0.01 sec)
Query OK, 0 rows affected (0.03 sec)
Example : User variables
In MySQL stored procedures, user variables are referenced with an ampersand (@)
prefixed to the user variable name (for example, @x and @y). The following example
shows the use of user variables within the stored procedure :
DELIMITER $$
CREATE PROCEDURE my_procedure_User_Variables()
BEGIN
SET @x = 15;
SET @y = 10;
SELECT @x, @y, @x-@y;
END$$
Now execute the procedure :
mysql> CALL my_procedure_User_Variables() ;
+------+------+-------+
| @x | @y | @x-@y |
+------+------+-------+
| 15 | 10 | 5|
+------+------+-------+
1 row in set (0.04 sec)
Query OK, 0 rows affected (0.05 sec)
MySQL : Procedure Parameters
Here is the parameter part of CREATE PROCEDURE syntax :
CREATE
We can divide the above CREATE PROCEDURE statement in the following ways :
In the third example, an OUT parameter passes a value from the procedure back to the
caller. Its initial value is NULL within the procedure, and its value is visible to the caller
when the procedure returns.
In the fourth example, an INOUT parameter is initialized by the caller, can be modified by
the procedure, and any change made by the procedure is visible to the caller when the
procedure returns.
In a procedure, each parameter is an IN parameter by default. To specify otherwise for a
parameter, use the keyword OUT or INOUT before the parameter name.
MySQL Procedure : Parameter IN example
In the following procedure, we have used a IN parameter 'var1' (type integer) which accept
a number from the user. Within the body of the procedure, there is a SELECT statement
which fetches rows from 'jobs' table and the number of rows will be supplied by the user.
Here is the procedure :
mysql> CREATE PROCEDURE my_proc_IN (IN var1 INT)
-> BEGIN
-> SELECT * FROM jobs LIMIT var1;
-> END$$
Query OK, 0 rows affected (0.00 sec)
To execute the first 2 rows from the 'jobs' table execute the following command :
mysql> CALL my_proc_in(2)$$
+---------+-------------------------------+------------+------------+
| JOB_ID | JOB_TITLE | MIN_SALARY | MAX_SALARY |
+---------+-------------------------------+------------+------------+
| AD_PRES | President | 20000 | 40000 |
| AD_VP | Administration Vice President | 15000 | 30000 |
+---------+-------------------------------+------------+------------+
2 rows in set (0.00 sec)Query OK, 0 rows affected (0.03 sec)
Now execute the first 5 rows from the 'jobs' table :
mysql>
CALL my_proc_in(5)$$
+------------+-------------------------------+------------+------------+
| JOB_ID | JOB_TITLE | MIN_SALARY | MAX_SALARY |
+------------+-------------------------------+------------+------------+
| AD_PRES | President | 20000 | 40000 |
| AD_VP | Administration Vice President | 15000 | 30000 |
| AD_ASST | Administration Assistant | 3000 | 6000 |
| FI_MGR | Finance Manager | 8200 | 16000 |
| FI_ACCOUNT | Accountant | 4200 | 9000 |
+------------+-------------------------------+------------+------------+
5 rows in set (0.00 sec)Query OK, 0 rows affected (0.05 sec)
MySQL Procedure : Parameter OUT example
The following example shows a simple stored procedure that uses an OUT parameter.
Within the procedure MySQL MAX() function retrieves maximum salary from
MAX_SALARY of jobs table.
mysql> CREATE PROCEDURE my_proc_OUT (OUT highest_salary INT)
-> BEGIN
-> SELECT MAX(MAX_SALARY) INTO highest_salary FROM JOBS;
-> END$$
Query OK, 0 rows affected (0.00 sec)
In the body of the procedure, the parameter will get the highest salary from MAX_SALARY
column. After calling the procedure the word OUT tells the DBMS that the value goes out
from the procedure. Here highest_salary is the name of the output parameter and we have
passed its value to a session variable named @M, in the CALL statement.
mysql> CALL my_proc_OUT(@M)$$
Query OK, 1 row affected (0.03 sec)
or
CASE
WHEN search_condition THEN statement_list
LOOP
statement_list
END LOOP
[end_label]
Open a cursor :
The following statement opens a previously declared cursor.
OPEN cursor_name
Fetch the data into variables :
This statement fetches the next row for the SELECT statement associated with the
specified cursor (which must be open) and advances the cursor pointer. If a row exists, the
fetched columns are stored in the named variables. The number of columns retrieved by
the SELECT statement must match the number of output variables specified in the FETCH
statement.
FETCH [[NEXT] FROM] cursor_name
INTO var_name [, var_name] ...
Close the cursor when done :
This statement closes a previously opened cursor. An error occurs if the cursor is not open.
CLOSE cursor_name
Example :
The procedure starts with three variable declarations. Incidentally, the order is important.
First, declare variables. Then declare conditions. Then declare cursors. Then, declare
handlers. If you put them in the wrong order, you will get an error message.
DELIMITER $$
CREATE PROCEDURE my_procedure_cursors(INOUT return_val INT)
BEGIN
DECLARE a,b INT;
DECLARE cur_1 CURSOR FOR
SELECT max_salary FROM jobs;
DECLARE CONTINUE HANDLER FOR NOT FOUNDSET b = 1;
OPEN cur_1;REPEATFETCH cur_1 INTO a;
UNTIL b = 1END REPEAT;
CLOSE cur_1;
SET return_val = a;
END;
$$
Now execute the procedure :
mysql>
CALL my_procedure_cursors(@R);
Query OK, 0 rows affected (0.00 sec)
MySQL Triggers
Introduction on Triggers
A trigger is a set of actions that are run automatically when a specified change operation
(SQL INSERT, UPDATE, or DELETE statement) is performed on a specified table. Triggers
are useful for tasks such as enforcing business rules, validating input data, and keeping an
audit trail.
Uses for triggers :
Enforce business rules
TRIGGER trigger_name
trigger_time trigger_event
trigger_body
trigger_time: { BEFORE | AFTER }
Explanation :
DEFINER clause : The DEFINER clause specifies the MySQL account to be used when
checking access privileges at trigger activation time. If a user value is given, it should be a
MySQL account specified as 'user_name'@'host_name' (the same format used in the
GRANT statement), CURRENT_USER, or CURRENT_USER().
The default DEFINER value is the user who executes the CREATE TRIGGER statement.
This is the same as specifying DEFINER = CURRENT_USER explicitly.
If you specify the DEFINER clause, these rules determine the valid DEFINER user values :
If you do not have the SUPER privilege, the only permitted user value is your own
account, either specified literally or by using CURRENT_USER. You cannot set the
definer to some other account.
If you have the SUPER privilege, you can specify any syntactically valid account name.
If the account does not actually exist, a warning is generated.
Although it is possible to create a trigger with a nonexistent DEFINER account, it is not
a good idea for such triggers to be activated until the account actually does exist.
Otherwise, the behavior with respect to privilege checking is undefined.
trigger_name : All triggers must have unique names within a schema. Triggers in different
schemas can have the same name.
trigger_time : trigger_time is the trigger action time. It can be BEFORE or AFTER to
indicate that the trigger activates before or after each row to be modified.
trigger_event : trigger_event indicates the kind of operation that activates the trigger.
These trigger_event values are permitted:
The trigger activates whenever a new row is inserted into the table; for example,
through INSERT, LOAD DATA, and REPLACE statements.
The trigger activates whenever a row is modified; for example, through UPDATE
statements.
The trigger activates whenever a row is deleted from the table; for example, through
DELETE and REPLACE statements. DROP TABLE and TRUNCATE TABLE
statements on the table do not activate this trigger, because they do not use DELETE.
Dropping a partition does not activate DELETE triggers, either.
tbl_name : The trigger becomes associated with the table named tbl_name, which must
refer to a permanent table. You cannot associate a trigger with a TEMPORARY table or a
view.
trigger_body : trigger_body is the statement to execute when the trigger activates. To
execute multiple statements, use the BEGIN ... END compound statement construct. This
also enables you to use the same statements that are permissible within stored routines.
Here is a simple example :
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)
In the above example, there is new keyword 'NEW' which is a MySQL extension to triggers.
There is two MySQL extension to triggers 'OLD' and 'NEW'. OLD and NEW are not case
sensitive.
Within the trigger body, the OLD and NEW keywords enable you to access columns in
the rows affected by a trigger
In an INSERT trigger, only NEW.col_name can be used.
In a UPDATE trigger, you can use OLD.col_name to refer to the columns of a row
before it is updated and NEW.col_name to refer to the columns of the row after it is
updated.
In a DELETE trigger, only OLD.col_name can be used; there is no new row.
A column named with OLD is read only. You can refer to it (if you have the SELECT
privilege), but not modify it. You can refer to a column named with NEW if you have the
SELECT privilege for it. In a BEFORE trigger, you can also change its value with SET
NEW.col_name = value if you have the UPDATE privilege for it. This means you can use a
trigger to modify the values to be inserted into a new row or used to update a row. (Such a
SET statement has no effect in an AFTER trigger because the row change will have
already occurred.)
Sample database, table, table structure, table records for various examples
Database Name : hr
Host Name : localhost
Database user : root
Password : ' '
Structure of the table : emp_details
After a successful login, you can access the MySQL command prompt :
Now you can write your own trigger on a specific table, see the following example :
+-------------+------------+-----------+---------+----------+----------------+
| EMPLOYEE_ID | FIRST_NAME | LAST_NAME | JOB_ID | SALARY |
COMMISSION_PCT |
+-------------+------------+-----------+---------+----------+----------------+
+-------------+------------+-----------+---------+----------+----------------+
+-------------+----------+---------------------+
| emp_details | SALARY | EDTTIME |
+-------------+----------+---------------------+
+-------------+----------+---------------------+
Now insert one record in emp_details table see the records both in emp_details and
log_emp_details tables :
mysql> INSERT INTO emp_details VALUES(236, 'RABI', 'CHANDRA',
'RABI','590.423.45700', '2013-01-12', 'AD_VP', 15000, .5);
Query OK, 1 row affected (0.07 sec)
mysql> SELECT EMPLOYEE_ID, FIRST_NAME, LAST_NAME, JOB_ID, SALARY,
COMMISSION_PCT FROM emp_details;
+-------------+------------+-----------+---------+----------+----------------+
+-------------+------------+-----------+---------+----------+----------------+
A BEFORE trigger is activated by the attempt to insert or modify the row, regardless of
whether the attempt subsequently succeeds.
An AFTER trigger is executed only if any BEFORE triggers and the row operation
execute successfully.
An error during either a BEFORE or AFTER trigger results in failure of the entire
statement that caused trigger invocation.
For transactional tables, failure of a statement should cause a rollback of all changes
performed by the statement.
Delete a MySQL trigger
To delete or destroy a trigger, use a DROP TRIGGER statement. You must specify the
schema name if the trigger is not in the default (current) schema :
DROP TRIGGER [IF EXISTS] [schema_name.]trigger_nam
if you drop a table, any triggers for the table are also dropped.
What is Partitioning?
Partitioning (a database design technique) improves performance,
manageability, simplifies maintenance and reduce the cost of storing large
amounts of data. Partitioning can be achieved without splitting tables by
physically putting tables on individual disk drives. Partitioning allows tables,
indexes, and index-organized tables to be subdivided into smaller pieces,
therefore queries that access only a fraction of the data can run faster because
there is fewer data to scan. There are two major forms of partitioning :
Horizontal Partitioning : Horizontal partitioning divides table rows into multiple partitions
(based on a logic). All columns defined to a table are found in each partition, so no actual
table attributes are missing. All the partition can be addressed individually or collectively. For
example, a table that contains whole year sale transaction being partitioned horizontally into
twelve distinct partitions, where each partition contains one month's data.
Vertical Partitioning : Vertical partitioning divides a table into multiple tables that contain fewer
columns. Like horizontal partitioning, in vertical partitioning a query scan fewer data which
increases query performance. For example, a table that contains a number of very wide text
or BLOB columns that aren't addressed often being broken into two tables that have the most
referenced columns in one table and the text or BLOB data in another.
MySQL partitioning
Version : MySQL 5.6
MySQL supports basic table partitioning but does not support vertical
partitioning ( MySQL 5.6). This section describes in detail how to implement
partitioning as part of your database.
How to partition a table?
In MySQL you can partition a table using CREATE TABLE or ALTER TABLE
command. See the following CREATE TABLE syntax :
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
(create_definition,...)
[table_options]
[partition_options]
partition_options :
PARTITION BY
{ [LINEAR] HASH(expr)
| [LINEAR] KEY(column_list)
| RANGE(expr)
| LIST(expr) }
[PARTITIONS num]
[SUBPARTITION BY
{ [LINEAR] HASH(expr)
| [LINEAR] KEY(column_list) }
[SUBPARTITIONS num]
[VALUES
IN (value_list)}]
bill_no INT,
bill_date DATETIME
);
This table can be partitioned by HASH (or in another type), using the bill_no
column as the partitioning key, into 6 (or other) partitions using ALTER TABLE
statement :
ALTER TABLE t1
PARTITION BY HASH(id)
PARTITIONS 6;
Partition naming :
Names of partitions follow the rules of other MySQL identifiers such as
databases, tables, constraint, stored procedure etc. Partition names are not
case-sensitive.
Advantages of partitioning
During the scan operation, MySQL optimizer accesses those partitions that will satisfy a
particular query. For example, a whole year sale records table may be broken up into 4
partitions (i.e. sale data from of Apr-Jun (partition p0), Jul-Sep (partition p1) , Oct-Dec
(partition p2), Jan-Mar (partition p0)) . If a query is issued that contains sale data between
Jul-Sep quarter, then it scans the partition p1 only instead of total table records and the query
will complete much sooner.
Partitioning allows you to have more control over how data is managed inside the database.
For example, you can drop specific partitions in a partitioned table where data loses its
usefulness. The process of adding new data, in some cases, be greatly facilitated by adding
one or more new partitions for storing that data using ALTER TABLE command.
In partitioning, it is possible to store more data in one table than can be held on a single disk
or file system partition.
MySQL 5.6 supports explicit partition selection for queries. For example, SELECT * FROM
table1 PARTITION (p0,p1) WHERE col1< 10 selects only those rows in partitions p0 and p1
that match the WHERE condition, this can greatly speed up queries
Partition selection also supports the data modification statements DELETE, INSERT,
REPLACE, UPDATE, and LOAD DATA, LOAD XML.
+---------+---------------------+-----------+--------+
+---------+---------------------+-----------+--------+
+---------+---------------------+-----------+--------+
+----------------+------------+
| PARTITION_NAME | TABLE_ROWS |
+----------------+------------+
| p0 | 4|
| p1 | 3|
| p2 | 2|
| p3 | 0|
+----------------+------------+
In the above way you can partition the table based on sale amount (amount. In
these partitions the range of the sale amount (amount) are as of follow :
partition p0 ( sale amount < 100 )
partition p1 ( sale amount < 500 )
partition p2 ( sale amount <1000 )
partition p3 ( sale amount<1500 )
+---------+---------------------+-----------+--------+
+---------+---------------------+-----------+--------+
+---------+---------------------+-----------+--------+
WHERE TABLE_NAME='sale_mast';
+----------------+------------+
| PARTITION_NAME | TABLE_ROWS |
+----------------+------------+
| p0 | 0|
| p1 | 3|
| p2 | 2|
| p3 | 0|
+----------------+------------+
4 rows in set (0.05 sec)
MySQL LIST Partitioning
List partition allows us to segment data based on a pre-defined set of values
(e.g. 1, 2, 3). This is done by using PARTITION BY LIST(expr) where expr is a
column value and then defining each partition by means of a VALUES IN
(value_list), where value_list is a comma-separated list of integers. In MySQL
5.6, it is possible to match against only a list of integers (and possibly NULL)
when partitioning by LIST. In the following example, sale_mast2 table contains
four columns bill_no, bill_date, agent_code, and amount. Suppose there are 11
agents represent three cities A, B, C these can be arranged in three partitions
with LIST Partitioning as follows :
City Agent ID
A 1, 2, 3
B 4, 5, 6
C 7, 8, 9, 10, 11
PARTITION BY LIST(agent_code) (
PARTITION pA VALUES IN (1,2,3),
...]
)
column_list:
value_list:
Here is an example :
mysql> CREATE TABLE table3 (col1 INT, col2 INT, col3 CHAR(5), col4 INT)
City Agent ID
A A1, A2, A3
B B1, B2, B3
Let create a table with LIST COLUMNS partitioning based on the above
information :
mysql> CREATE TABLE salemast ( agent_id VARCHAR(15), agent_name VARCHAR(50),
You can use DATE and DATETIME columns in LIST COLUMNS partitioning,
see the following example :
CREATE TABLE sale_master (bill_no INT NOT NULL, bill_date DATE,
PARTITION BY HASH(student_id)
PARTITIONS 4;
It is also possible to make a partition based on the year in which a student was
admitted. See the following statement :
MySQL> CREATE TABLE student (student_id INT NOT NULL,
PARTITION BY HASH(YEAR(date_of_admission))
PARTITIONS 4;
PARTITION BY KEY()
PARTITIONS 2;
If there is no primary key but there is a unique key in a table, then the unique
key is used for the partitioning key :
MySQL> CREATE TABLE table2 ( id INT NOT NULL, fname VARCHAR(25),
lname VARCHAR(25),
PARTITION BY KEY()
PARTITIONS 2;
Query OK, 0 rows affected (0.77 sec)
MySQL Subpartitioning
Subpartitioning is a method to divide each partition further in a partitioned
table. See the following CREATE TABLE statement :
CREATE TABLE table10 (BILL_NO INT, sale_date DATE, cust_code VARCHAR(15),
AMOUNT DECIMAL(8,2))
PARTITION BY RANGE(YEAR(sale_date) )
SUBPARTITION BY HASH(TO_DAYS(sale_date))
SUBPARTITIONS 4 (
+----------------+------------+
| PARTITION_NAME | TABLE_ROWS |
+----------------+------------+
| p0 | 0|
| p0 | 0|
| p0 | 0|
| p0 | 0|
| p1 | 0|
| p1 | 0|
| p1 | 0|
| p1 | 0|
| p2 | 0|
| p2 | 0|
| p2 | 0|
| p2 | 0|
| p3 | 0|
| p3 | 0|
| p3 | 0|
| p3 | 0|
+----------------+------------+
procedure function
trigger