SlideShare a Scribd company logo
1 of 57
Mysql PRO
By:-
Gaurav Gupta
Divanshu Nandwani
Agenda
● Basics
● Architecture
● Transaction
● Triggers
● PL/SQL
● Engines
BASICS
USING SELECT
The SELECT statement has the following general form:
SELECT columns
FROM tables
[WHERE conditions]
[GROUP BY group
[HAVING group_conditions]]
[ORDER BY sort_columns]
[LIMIT limits];
JOINS
● Running queries across multiple tables. This will involve the concept of joins—that is, how we join tables
together.
● Using joins to run queries over multiple tables, including:
○ Natural, inner, and cross joins
○ Straight joins
○ Left and right joins
● Writing subqueries
● Using SELECT statement options
USING SELECT
• The clause select * retrieves all columns; select columnname retrieves a particular column.
• Can specify tables as database.table and columns as table.column or database.table.column to avoid ambiguity.
• Aliases are alternative names for tables and columns. Specify them this way:
select column as column_alias from table as table_alias;
• WHERE clause: select rows matching search criteria.
• DISTINCT Keyword: removes duplicates from the result set.
• GROUP BY clause: treats the rows retrieved group by group.Used in conjunction with group functions like count().
• HAVING clause: like a WHERE clause for groups.
• ORDER BY clause: sorts result rows according to the columns you specify.
• LIMIT clause: used to control which rows are returned from the total possible result set.
JOINING TWO TABLES
● Consider the following query:
select employee.name, department.name
from employee, department
where employee.departmentID = department.departmentID;
select employee.name, department.name
from employee, department;
● Consider our original query:
select employee.name, department.name
from employee, department
where employee.departmentID = department.departmentID;
● Optionally, we could have used the keyword JOIN, instead of a comma:
select employee.name, department.name
from employee join department on employee.departmentID = department.departmentID;
● Instead of JOIN, we could have written CROSS JOIN or INNER JOIN.
USING SELECT STATEMENT OPTIONS
According to the MySQL manual, this is the form of a SELECT statement:
SELECT [STRAIGHT_JOIN] [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
[SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS] [HIGH_PRIORITY]
[DISTINCT | DISTINCTROW | ALL]
select_expression,...
[INTO {OUTFILE | DUMPFILE} 'file_name' export_options]
[ FROM table_references
[WHERE where_definition]
[GROUP BY {unsigned_integer | col_name | formula} [ASC | DESC], ...]
[HAVING where_definition]
[ORDER BY {unsigned_integer | col_name | formula} [ASC | DESC] ,...]
[LIMIT [offset,] rows | rows OFFSET offset]
[PROCEDURE procedure_name(argument_list)]
[FOR UPDATE | LOCK IN SHARE MODE]]
USING SELECT STATEMENT OPTIONS
● The STRAIGHT JOIN clause at the beginning used to force the query optimizer to join the tables in the order
you specify. This has the same effect as specifying STRAIGHT JOIN in the WHERE clause.
● Use SQL_SMALL_RESULT and SQL_BIG_RESULT to get the result set having either few rows or a large
number of them.
● SQL_BUFFER_RESULT tells MySQL to put the result set into a temporary table. Use this when it takes
significant time to send the results to the client to avoid having the queried tables locked for that time.
● SQL_CACHE and SQL_NOCACHE tell MySQL whether to cache the results.
USING SELECT STATEMENT OPTIONS
• SQL_CALC_FOUND_ROWS is used with the LIMIT clause to work out how many rows would have been returned
if there had been no LIMIT clause. We can then retrieve this number with select found_rows();
• HIGH PRIORITY gives priority to query over any UPDATE statements that are waiting to use the involved tables.
• DISTINCTROW is a synonym for DISTINCT. ALL (default option) return all duplicates.
• The SELECT INTO OUTFILE is the opposite of the LOAD DATA INFILE.
• The PROCEDURE clause specify a procedure ( must be written in C++) that can be applied to the result set before it
is sent to the client.
• The FOR UPDATE and LOCK IN SHARE MODE clauses affect only if storage engine uses page or row-level
locking (InnoDB and BDB). FOR UPDATE set an exclusive lock, and LOCK IN SHARE MODE set a shared lock.
INSERT
The general form of the INSERT statement from the MySQL manual is as follows:
INSERT [LOW_PRIORITY | DELAYED]
[IGNORE]
[INTO] tbl_name
SET col_name=(expression |
DEFAULT), ...
[ ON DUPLICATE KEY UPDATE
col_name=expression, ... ]
INSERT [LOW_PRIORITY | DELAYED]
[IGNORE]
[INTO] tbl_name [(col_name,...)]
VALUES ((expression |
DEFAULT),...),(...),...
[ ON DUPLICATE KEY UPDATE
col_name=expression, ... ]
INSERT [LOW_PRIORITY | DELAYED]
[IGNORE]
[INTO] tbl_name [(col_name,...)]
SELECT …
Clauses in the INSERT statement
● An INSERT should be specified as LOW PRIORITY or DELAYED. Both clauses will cause the insertion to
be delayed until no client is trying to read from the table.
● The difference between them is that LOW PRIORITY will block the inserting client and DELAYED will not.
● Specifying IGNORE is useful when you are inserting multiple rows. If one of the rows you are trying to insert
clashes with an existing row's PRIMARY KEY or UNIQUE value, an error will occur and the insert will be
aborted. But by specifying IGNORE, the error will be ignored and will attempt to insert the next row.
● A column should contain its default value by specifying DEFAULT as the value for that column.
● The ON DUPLICATE KEY UPDATE clause allows to deal with clashing primary key or unique values.
● Follow this clause with an update statement that can use to change the primary key or unique value in the row
already in the table so that it no longer clashes with the new row.
Clauses in the INSERT statement
● Example of use of ON DUPLICATE KEY UPDATE clause:
create table warning(
employeeID int primary key not null references employee(employeeID),
count int default 1
) ;
insert into warning (employeeID)
values (6651)
on duplicate key update count=count+1;
● This clause is useful for situations in which you want to not only record unique events, but also take some
action, such as incrementing a counter when non-unique events occur.
● Any sort of logging would be a good example, but in keeping with the employee database we have been
using, we will record employees who have been given a warning in the table warning.
USING REPLACE
The REPLACE statement is exactly like the INSERT statement except that if a key clash occurs, the new row you
are inserting will replace the old row.
This is the general form of REPLACE from the MySQL manual:
REPLACE [LOW_PRIORITY |
DELAYED]
[INTO] tbl_name
SET col_name=expression,
col_name=expression,...
REPLACE [LOW_PRIORITY |
DELAYED]
[INTO] tbl_name
[(col_name,...)]
VALUES
(expression,...),(...),...
REPLACE [LOW_PRIORITY |
DELAYED]
[INTO] tbl_name
[(col_name,...)]
SELECT ...
USING DELETE
This is the general form of the DELETE statement from the MySQL manual:
DELETE [LOW_PRIORITY]
[QUICK]
FROM table_name[.*] [,
table_name[.*] ...]
USING table-references
[WHERE
where_definition]
DELETE [LOW_PRIORITY]
[QUICK] FROM table_name
[WHERE
where_definition]
[ORDER BY ...]
[LIMIT rows]
DELETE [LOW_PRIORITY]
[QUICK] table_name[.*] [,
table_name[.*] ...]
FROM table-references
[WHERE
where_definition]
USING DELETE
The other two forms allow to delete rows from one or more tables with references to other tables.
For example:
delete employee, employeeSkills
from employee, employeeSkills, department
where employee.employeeID = employeeSkills.employeeID
and employee.departmentID = department.departmentID
and department.name='Finance';
The tables in the initial delete clause will have rows deleted from them, whereas the tables listed in the from clause
are used for searching for data and will not have rows deleted unless they are also listed in the delete clause.
USING DELETE
There are a couple of other optional clauses in the general form of the DELETE statement:
• The LOW_PRIORITY clause works in the same way as it does in the INSERT statement.
• Specifying QUICK may speed up the DELETE statement by telling MySQL not to do some of its housekeeping
on indexes while deleting from the table.
• The ORDER BY clause specifies the order in which to delete rows. This is most useful in conjunction with the
LIMIT clause (The LIMIT clause allows us to set a maximum number of rows that can be deleted by the DELETE
statement), for example, we may want to delete the oldest n rows from a table.
USING UPDATE
This is the general form of the UPDATE statement from the MySQL manual:
UPDATE [LOW_PRIORITY] [IGNORE]
tbl_name
SET col_name1=expr1 [,
col_name2=expr2 ...]
[WHERE where_definition]
[ORDER BY ...]
[LIMIT rows]
UPDATE [LOW_PRIORITY] [IGNORE]
tbl_name [, tbl_name ...]
SET col_name1=expr1 [,
col_name2=expr2 ...]
[WHERE where_definition]
USING UPDATE
● The UPDATE statement is similar in many respects to the DELETE statement.
● Can use an optional WHERE clause to update particular rows or leave it off to update all rows.
● Can fall into the trap of forgetting to specify a WHERE clause— for example
update user set password='test';
● This highlights the usefulness of --i-am-a-dummy mysql option, if you are forced to work with dummies.
● The second version of the UPDATE statement is a multi-table update. This works similarly to the multi-table
deletes. Only the columns you specifically list in the SET clause will be updated.
● Other clauses of the UPDATE statement are: The LOW_PRIORITY and IGNORE clauses work the same as
they do in INSERT. The ORDER BY and LIMIT clauses work the same as they do in DELETE.
--i-am-a-dummy
● A really useful option to mysql is the --i-am-a-dummy option.
● Can invoke this option in a less pejorative way using --safe-updates. For example:
mysql --i-am-a-dummy -u root -p
● It is unusual to want to delete all the rows from a table.
● However, because this is the shortest form of the delete statement, you may sometimes type it by accident
without a WHERE clause.
● You can save yourself this anguish by switching on the -–safe-updates or –-i-am-a-dummy command-line
options of the mysql client.
● These options prevent you from deleting (or updating) rows without specifying a key constraint in the WHERE
clause. That is, you need to specify that you want to delete only rows containing certain key values.
ARCHITECTURE
MySQL Architecture
Optimization and Execution
● MySQL parse queries to create an internal structure (the parse tree), and then applies a variety of
optimizations.
● These may include rewriting the query, determining the order in which it will read tables, choosing which
indexes to use, and so on.
● Before even parsing the query, though, the server consults the query cache, which can store only SELECT
statements, along with their result sets.
● If anyone issues a query that’s identical to one already in the cache, the server doesn’t need to parse, optimize,
or execute the query at all—it can simply pass back the stored result set!
Concurrency Control
● Anytime more than one query needs to change data at the same time, the problem of concurrency control
arises.
● MySQL has to do this at two levels: the server level and the storage engine level.
● Systems that deal with concurrent read/write access typically implement a locking system that consists of two
lock types.
● These locks are usually known as shared locks and exclusive locks, or read locks and write locks.
Read/Write Locks
● Read locks on a resource are shared, or mutually nonblocking: many clients may read from a resource at the
same time and not interfere with each other.
● Write locks, on the other hand, are exclusive—i.e., they block both read locks and other write locks—because
the only safe policy is to have a single client writing to the resource at given time and to prevent all reads
when a client is writing.
● MySQL performs this lock management internally in a way that is transparent much of the time.
● Two most important lock strategies are:
Read/Write Locks
Table locks
● The most basic locking strategy available in MySQL, and the one with the lowest overhead, is table locks.
● It locks the entire table. When a client wishes to write to a table (insert, delete, update), it acquires a write lock.This
keeps all other read and write operations at bay.
● When nobody is writing,readers can obtain read locks, which don’t conflict with other read locks.
● Write locks can advance past read locks in the queue, but read locks cannot advance past write locks.
● Although storage engines can manage their own locks, MySQL itself also uses a variety of locks. For instance, the
server uses a table-level lock for statements such as ALTER TABLE, regardless of the storage engine.
Read/Write Locks
ROW LOCKS
● The locking style that offers the greatest concurrency (and carries the greatest overhead) is the use of row
locks.
● Row-level locking is available in the InnoDB and Falcon storage engines.
● Row locks are implemented in the storage engine, not the server.
TRANSACTION
Using Transactions with InnoDB Tables
● A transaction is a sequence of related instructions that must be treated as one indivisible unit.
● All the work in the transaction must be done, or all of it must be left undone. This concept is known as atomicity.
● A transaction is atomic because it cannot be broken down into parts—it all gets processed or it all gets ignored.
● For example: Consider a simple database that records bank account details. Each account has, at minimum, a
unique identifier and a balance.Consider the following pair of statements intended to deposit $500 into account 2:
# first check balance
select balance from account where number = 2;
# query gives us a result of $1000
# now store updated balance
update account set balance = 1500 where number = 2;
● These queries are related and need to be run together.Otherwise not get the result as expected.
Using Transactions with InnoDB Tables
● If two clients were running pairs of queries like this at the same time, our final result would depend on timing. If
we were attempting to deposit $500 with these queries and another client was attempting to deposit $100 with the
following pair, the end result could be a balance of $1100 or $1500—neither of which is the right result.
# first check balance
select balance from account where number = 2;
# query gives us a result of $1000
# now store updated balance
update account set balance = 1100 where number = 2;
● To solve the problem, Make updates relative rather than absolute that make them into single, indivisible units The
following query will run correctly:
update account set balance = balance + 500 where number = 2;
Using Transactions with InnoDB Tables
● A single update statement in MySQL is always atomic. It cannot be interrupted by another query or half succeed. It
will complete or will completely fail on an error.
● Now, More complex scenarios is: Consider the following pair of queries intended to transfer $1000 from account 2
to account 1:
update account set balance = balance - 1000 where number = 2;
update account set balance = balance + 1000 where number = 1;
● Both updates are relative, but it is important that these two queries be run together for sensible results. The total
amount of money in the system should be the same after the queries as before.
● But, If a power failure happened between running the first query and running the second query, our data would no
longer be consistent.
Using Transactions with InnoDB Tables
● In this case we could write this:
update account as source, account as dest
set source.balance = source.balance – 1000,
dest.balance = dest.balance + 1000
where source.number = 2 and dest.number = 1;
● By using two aliases to the account table (source and dest), we have ensured that this is one atomic update.
● In this case the only casualty is readability. The combined query is harder to read and debug than our first
attempt.
Using Transactions with InnoDB Tables
● In many cases, it may not be possible to collapse all the related queries into one like this.
● The solution in those cases, and anytime you want more readable code, is to use MySQL's transaction syntax.
● By marking a set of statements as a transaction, you inform the database that they are a related, indivisible set.
● They should be treated as an atomic unit and either all succeed or all have no effect.
● You can run these two queries as a single transaction using the following SQL statements:
start transaction;
update account set balance = balance - 1000 where number = 2;
update account set balance = balance + 1000 where number = 1;
Commit;
● An important property of transactions is that they are not visible to other sessions until they are complete and
committed. No other thread can read inconsistent data from the table(s) while you are in the process of updating
it.
Using Transactions with InnoDB Tables
● In the case of transfer example, adding a SELECT statement to check the removal of more money from the source
account than it contained, use the keyword ROLLBACK to cancel the whole transaction. The syntax is:
start transaction;
update account set balance = balance - 1000 where number = 2;
update account set balance = balance + 1000 where number = 1;
select balance from account where number = 2;
# select tells us that account #2 has a negative balance!
# we'd better abort
rollback;
● Calling ROLLBACK aborts the transaction and undoes any changes it would have made.
● A transaction that was rolled back instead of committed leaves no trace in the data. Because partial results were
never visible to other sessions, it is exactly as though it never happened.
Using Transactions with InnoDB Tables
SETTING THE AUTOCOMMIT MODE
start transaction;
update account set balance = balance - 1000 where number = 2;
commit;
start transaction;
update account set balance = balance + 1000 where number = 1;
commit;
● Disable autocommit behavior using the SET command as follows:
set autocommit=0;
● Command to put MySQL back into autocommit mode:
set autocommit=1;
● The autocommit variable is local to a single session, so changing the mode will affect only queries run from your
session.
● Turning autocommit off will not need to call START TRANSACTION to start a transaction. It is very
important, to remember to call COMMIT periodically to commit any changes you have made to the database.
TRIGGERS
MySQL Triggers
● A trigger is a set of SQL statements that is invoked automatically when a change is made to the data on the
associated table.
● A trigger can be defined to be invoked either before or after the data is changed by INSERT, UPDATE or
DELETE statement.
○ BEFORE INSERT – activated before data is inserted into the table.
○ AFTER INSERT – activated after data is inserted into the table.
○ BEFORE UPDATE – activated before data in the table is updated.
○ AFTER UPDATE – activated after data in the table is updated.
○ BEFORE DELETE – activated before data is removed from the table.
○ AFTER DELETE – activated after data is removed from the table.
MySQL Triggers
MySQL trigger limitation
MySQL triggers cannot:
● Use SHOW, LOAD DATA, LOAD TABLE, BACKUP DATABASE, RESTORE, FLUSH and RETURN
statements.
● Use statements that commit or rollback implicitly or explicitly such as COMMIT , ROLLBACK , START
TRANSACTION , LOCK/UNLOCK TABLES , ALTER , CREATE , DROP , RENAME.
● Use prepared statements such as PREPARE and EXECUTE.
● Use dynamic SQL statements.
From MySQL version 5.1.4, a trigger can call a stored procedure or stored function,
MySQL Trigger Syntax
CREATE TRIGGER triggerTime_table Name_triggerEvent
ON table_name
FOR EACH ROW
BEGIN
...
END;
● The trigger name format is [trigger time]_[table name]_[trigger event], for example before_employees_update.
● Must specify the activation time (BEFORE or AFTER) when you define a trigger. Use the BEFORE keyword to
process action prior to the change is made on the table and AFTER to process action after the change is made.
● The trigger event (INSERT, UPDATE or DELETE) causes the trigger to be invoked. A trigger only can be
invoked by one event.
● A trigger must be associated with a specific table, specify the table name after the ON keyword.
● Place the SQL statements (logic for the trigger) between BEGIN and END block.
MySQL Trigger Example
DELIMITER $$
CREATE TRIGGER before_employee_update
BEFORE UPDATE ON employees
FOR EACH ROW
BEGIN
INSERT INTO employees_audit
SET action = 'update',
employeeNumber = OLD.employeeNumber,
lastname = OLD.lastname,
changedat = NOW();
END$$
DELIMITER ;
PL/SQL
PL/SQL - Introduction
● Procedural Language SQL provides the feature to write block of SQL statements which can be executed in
one go.
● Can call other Stored Procedure and Functions
● Stored Procedure can return the values via OUT variable
● Syntax
Create statement
CREATE PROCEDURE my_first_sp()
BEGIN
Select * from user;
END
Call statement
Call my_first_sp();
PL/SQL - Cursors and Handlers
Cursors
Cursor iterate over result set returned by select statement
Syntax:
DECLARE int id;
DECLARE my_first_cursor CURSOR FOR SELECT id from user;
OPEN my_first_cursor;
FETCH my_first_cursor INTO id;
CLOSE my_first_cursor;
Handlers
Handlers are statements that need specific handling
DECLARE int finished;
SET finished = 0;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
PL/SQL - Error Handling
Handlers can be of type CONTINUE, EXIT and UNDO(Not supported)
Condition value of the Handler can be SQLSTATE, SQLWARNING, NOT FOUND, SQLEXCEPTION and
mysql_error_code
Error Handling
● Exit on Error
○ DECLARE EXIT HANDLER FOR SQLEXCEPTION
○ DECLARE EXIT HANDLER FOR SQLSTATE '23000'
● Continue on Error
○ DECLARE CONTINUE HANDLER FOR 1062
○ DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1
PL/SQL - Transactions
Transaction is required when we need to run either all the statements or nothing at all
Components:
● Start Transaction
Starts a new Transaction
● Commit
Commit all the transactions in a Transaction block
● Rollback
Revert all the transactions in a transaction block e.g. when an exception occurs
● Autocommit
Disable or enable default autocommit for the current session
Syntax:
START TRANSACTION;
UPDATE user SET username=’abc’ WHERE id=1;
COMMIT;
ENGINES
MySQL’s Storage Engines
● MySQL stores each database (also called a schema) as a subdirectory of its data directory in the underlying
filesystem.
● When creating a table, MySQL stores the table definition in a .frm file with the same name as the table. For
example, for table named MyTable, the table definition is MyTable.frm.
● MySQL uses the filesystem to store database names and table definitions, case sensitivity depends on the platform.
On a Windows, they are case insensitive; on Unix-like systems, they are case sensitive.
● Each storage engine stores the table’s data and indexes differently, but the server itself handles the table definition.
UPLOADING DATA WITH LOAD DATA INFILE
The general form of the LOAD DATA INFILE statement is as follows:
LOAD DATA [LOW_PRIORITY | CONCURRENT] [LOCAL] INFILE
'fileName.txt'
[REPLACE | IGNORE]
INTO TABLE tbl_name
[FIELDS
[TERMINATED BY 't']
[[OPTIONALLY] ENCLOSED BY '']
[ESCAPED BY '' ]
]
[LINES TERMINATED BY 'n']
[IGNORE number LINES]
[(col_name,...)]
UPLOADING DATA WITH LOAD DATA INFILE
The optional clauses are as listed here:
● The LOW PRIORITY clause works the same way it does in the INSERT statement by waiting for other
clients to stop reading from the table.
● CONCURRENT allows other clients to read from the table while the bulk insert is going on.
● Optional keyword LOCAL, means data file is on the client machine. Otherwise, MySQL will look for the
infile on the server.
● To deal with key clashes while inserting data, REPLACE and IGNORE are two methods.
● REPLACE tells MySQL to replace the old row with the new row.
● IGNORE tells MySQL to keep the old row.
● The FIELDS and LINES clauses specify how the data in the infile is laid out.
● The IGNORE number LINES clause tells MySQL to ignore the first number lines in the infile.
● The final clause allows you to specify that you only want to read data into some of the table's columns.
Understanding MySQL's Table Types
● MySQL has six table types: ISAM, MyISAM, InnoDB, BDB, MERGE, and HEAP.
● Only InnoDB and BDB tables are transaction safe.
● Only MyISAM tables support full-text indexing and searching.
ISAM
● ISAM had been deprecated and superceded by MyISAM.
● ISAM tables have a hard size limit of 4GB.
● ISAM tables are not portable.
● Can have a maximum of 16 keys per table and a maximum key length of 256 bytes (characters).
Understanding MySQL's Table Types
MYISAM Table
● Default table type. It is very fast, but not transaction safe.
● Support table compression.
● Size of MyISAM tables is limited only by the operating system, and worked around with MERGE tables.
● The data files storing MyISAM tables are portable from system to system.
● Can have a maximum of 64 keys per table and a maximum key length of 1024 bytes.
● Can be one of three types: dynamic, static, or compressed.
● Automatically becomes dynamic or static depending on the definition of its columns.
● Compressed tables must be deliberately created with the myisampack tool.
Understanding MySQL's Table Types
MYISAM Table
● Tables with fixed-length rows created as static tables, and variable-length rows created as dynamic tables.
● A table with only char and numeric columns ( as all have a fixed size) will be created as a static table.
● A table containing any varchar, text, or blob columns (as all vary with the size of their contents) will be dynamic.
FULL-TEXT SEARCHING ON MYISAM TABLES
● One feature of MyISAM tables is full-text searching and indexing.
● Normal indexes are very good at finding rows where a value in the table matches a given value, but it is common
to want to search for words or strings within a block of text.
FULL-TEXT SEARCHING ON MYISAM TABLES
● Example:
create table article (
articleID int not null auto_increment primary key,
title varchar(255),
body text,
fulltext (title, body)
);
● Query retrieve records containing the word 'merger':
select title
from article
where match (title, body) against ('merger');
● Query retrieve records containing any of the words 'merge', 'acquisition', 'acquire', or 'takeover'.
select title from article
where match (title, body) against ('merge acquisition acquire takeover');
Understanding MySQL's Table Types
INNODB Tables
● Transaction safe.
● Supports row-level locking.
● No theoretical maximum table size because tables may be stored in more than one file.
● Provides consistent nonlocking reads in SELECT.
● Portable from system to system.
● Take more disk space than MyISAM tables.
● Foreign keys are supported between InnoDB tables.
Understanding MySQL's Table Types
BDB Tables
● Transaction safe.
● Not as widely used with MySQL as InnoDB.
● Supports page-level locking.
● Not portable.
MERGE Tables
● Used to treat multiple MyISAM tables as a single table, thus maximum file size limitation is removed from
MyISAM tables.
HEAP Tables
● Stored only in memory and need to be limited in size to avoid running out of memory.
● Data stored in a HEAP table is volatile and will be lost in the event of a power failure.
● Super fast, as long as you have enough physical memory to keep them.
● Notot support AUTO_INCREMENT, TEXT, or BLOB.
?
Thank You

More Related Content

What's hot (18)

Oracle SQL DML Statements
Oracle SQL DML StatementsOracle SQL DML Statements
Oracle SQL DML Statements
 
Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries Lecture
 
MySQL partitions tutorial
MySQL partitions tutorialMySQL partitions tutorial
MySQL partitions tutorial
 
SQL Tutorial - Basic Commands
SQL Tutorial - Basic CommandsSQL Tutorial - Basic Commands
SQL Tutorial - Basic Commands
 
Boost performance with MySQL 5.1 partitions
Boost performance with MySQL 5.1 partitionsBoost performance with MySQL 5.1 partitions
Boost performance with MySQL 5.1 partitions
 
Oracle: DML
Oracle: DMLOracle: DML
Oracle: DML
 
SQL Server Views
SQL Server ViewsSQL Server Views
SQL Server Views
 
Les10 Creating And Managing Tables
Les10 Creating And Managing TablesLes10 Creating And Managing Tables
Les10 Creating And Managing Tables
 
Les11 Including Constraints
Les11 Including ConstraintsLes11 Including Constraints
Les11 Including Constraints
 
Best sql plsql material
Best sql plsql materialBest sql plsql material
Best sql plsql material
 
Views and functions
Views and functionsViews and functions
Views and functions
 
Sql
SqlSql
Sql
 
Subqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactionsSubqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactions
 
Oracle sql material
Oracle sql materialOracle sql material
Oracle sql material
 
Trigger and cursor program using sql
Trigger and cursor program using sqlTrigger and cursor program using sql
Trigger and cursor program using sql
 
Les09
Les09Les09
Les09
 
Oracle: DDL
Oracle: DDLOracle: DDL
Oracle: DDL
 
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with ExamplesDML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
 

Similar to Mysql PRO: Basics, Architecture, Transactions, Triggers, PL/SQL and Engines

Its about a sql topic for basic structured query language
Its about a sql topic for basic structured query languageIts about a sql topic for basic structured query language
Its about a sql topic for basic structured query languageIMsKanchanaI
 
Creating other schema objects
Creating other schema objectsCreating other schema objects
Creating other schema objectsSyed Zaid Irshad
 
Les08 (manipulating data)
Les08 (manipulating data)Les08 (manipulating data)
Les08 (manipulating data)Achmad Solichin
 
PostgreSQL 9.5 Features
PostgreSQL 9.5 FeaturesPostgreSQL 9.5 Features
PostgreSQL 9.5 FeaturesSaiful
 
DBA Commands and Concepts That Every Developer Should Know
DBA Commands and Concepts That Every Developer Should KnowDBA Commands and Concepts That Every Developer Should Know
DBA Commands and Concepts That Every Developer Should KnowAlex Zaballa
 
Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020
Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020
Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020DmitryLenev
 
Oracle Database Advanced Querying
Oracle Database Advanced QueryingOracle Database Advanced Querying
Oracle Database Advanced QueryingZohar Elkayam
 

Similar to Mysql PRO: Basics, Architecture, Transactions, Triggers, PL/SQL and Engines (20)

Updat Dir
Updat DirUpdat Dir
Updat Dir
 
Les04
Les04Les04
Les04
 
SQL
SQLSQL
SQL
 
Les17
Les17Les17
Les17
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
Its about a sql topic for basic structured query language
Its about a sql topic for basic structured query languageIts about a sql topic for basic structured query language
Its about a sql topic for basic structured query language
 
Oraclesql
OraclesqlOraclesql
Oraclesql
 
Les02
Les02Les02
Les02
 
Creating other schema objects
Creating other schema objectsCreating other schema objects
Creating other schema objects
 
Les08 (manipulating data)
Les08 (manipulating data)Les08 (manipulating data)
Les08 (manipulating data)
 
Les08
Les08Les08
Les08
 
PostgreSQL 9.5 Features
PostgreSQL 9.5 FeaturesPostgreSQL 9.5 Features
PostgreSQL 9.5 Features
 
MYSql manage db
MYSql manage dbMYSql manage db
MYSql manage db
 
8. sql
8. sql8. sql
8. sql
 
MySQL Essential Training
MySQL Essential TrainingMySQL Essential Training
MySQL Essential Training
 
SQL Sort Notes
SQL Sort NotesSQL Sort Notes
SQL Sort Notes
 
DBA Commands and Concepts That Every Developer Should Know
DBA Commands and Concepts That Every Developer Should KnowDBA Commands and Concepts That Every Developer Should Know
DBA Commands and Concepts That Every Developer Should Know
 
Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020
Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020
Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020
 
5. Group Functions
5. Group Functions5. Group Functions
5. Group Functions
 
Oracle Database Advanced Querying
Oracle Database Advanced QueryingOracle Database Advanced Querying
Oracle Database Advanced Querying
 

More from NexThoughts Technologies (20)

Alexa skill
Alexa skillAlexa skill
Alexa skill
 
GraalVM
GraalVMGraalVM
GraalVM
 
Docker & kubernetes
Docker & kubernetesDocker & kubernetes
Docker & kubernetes
 
Apache commons
Apache commonsApache commons
Apache commons
 
HazelCast
HazelCastHazelCast
HazelCast
 
Microservice Architecture using Spring Boot with React & Redux
Microservice Architecture using Spring Boot with React & ReduxMicroservice Architecture using Spring Boot with React & Redux
Microservice Architecture using Spring Boot with React & Redux
 
Swagger
SwaggerSwagger
Swagger
 
Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
 
Arango DB
Arango DBArango DB
Arango DB
 
Jython
JythonJython
Jython
 
Introduction to TypeScript
Introduction to TypeScriptIntroduction to TypeScript
Introduction to TypeScript
 
Smart Contract samples
Smart Contract samplesSmart Contract samples
Smart Contract samples
 
My Doc of geth
My Doc of gethMy Doc of geth
My Doc of geth
 
Geth important commands
Geth important commandsGeth important commands
Geth important commands
 
Ethereum genesis
Ethereum genesisEthereum genesis
Ethereum genesis
 
Ethereum
EthereumEthereum
Ethereum
 
Springboot Microservices
Springboot MicroservicesSpringboot Microservices
Springboot Microservices
 
An Introduction to Redux
An Introduction to ReduxAn Introduction to Redux
An Introduction to Redux
 
Google authentication
Google authenticationGoogle authentication
Google authentication
 
Java 9 Features
Java 9 FeaturesJava 9 Features
Java 9 Features
 

Recently uploaded

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 

Recently uploaded (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 

Mysql PRO: Basics, Architecture, Transactions, Triggers, PL/SQL and Engines

  • 2. Agenda ● Basics ● Architecture ● Transaction ● Triggers ● PL/SQL ● Engines
  • 4. USING SELECT The SELECT statement has the following general form: SELECT columns FROM tables [WHERE conditions] [GROUP BY group [HAVING group_conditions]] [ORDER BY sort_columns] [LIMIT limits];
  • 5. JOINS ● Running queries across multiple tables. This will involve the concept of joins—that is, how we join tables together. ● Using joins to run queries over multiple tables, including: ○ Natural, inner, and cross joins ○ Straight joins ○ Left and right joins ● Writing subqueries ● Using SELECT statement options
  • 6. USING SELECT • The clause select * retrieves all columns; select columnname retrieves a particular column. • Can specify tables as database.table and columns as table.column or database.table.column to avoid ambiguity. • Aliases are alternative names for tables and columns. Specify them this way: select column as column_alias from table as table_alias; • WHERE clause: select rows matching search criteria. • DISTINCT Keyword: removes duplicates from the result set. • GROUP BY clause: treats the rows retrieved group by group.Used in conjunction with group functions like count(). • HAVING clause: like a WHERE clause for groups. • ORDER BY clause: sorts result rows according to the columns you specify. • LIMIT clause: used to control which rows are returned from the total possible result set.
  • 7. JOINING TWO TABLES ● Consider the following query: select employee.name, department.name from employee, department where employee.departmentID = department.departmentID; select employee.name, department.name from employee, department; ● Consider our original query: select employee.name, department.name from employee, department where employee.departmentID = department.departmentID; ● Optionally, we could have used the keyword JOIN, instead of a comma: select employee.name, department.name from employee join department on employee.departmentID = department.departmentID; ● Instead of JOIN, we could have written CROSS JOIN or INNER JOIN.
  • 8. USING SELECT STATEMENT OPTIONS According to the MySQL manual, this is the form of a SELECT statement: SELECT [STRAIGHT_JOIN] [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT] [SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS] [HIGH_PRIORITY] [DISTINCT | DISTINCTROW | ALL] select_expression,... [INTO {OUTFILE | DUMPFILE} 'file_name' export_options] [ FROM table_references [WHERE where_definition] [GROUP BY {unsigned_integer | col_name | formula} [ASC | DESC], ...] [HAVING where_definition] [ORDER BY {unsigned_integer | col_name | formula} [ASC | DESC] ,...] [LIMIT [offset,] rows | rows OFFSET offset] [PROCEDURE procedure_name(argument_list)] [FOR UPDATE | LOCK IN SHARE MODE]]
  • 9. USING SELECT STATEMENT OPTIONS ● The STRAIGHT JOIN clause at the beginning used to force the query optimizer to join the tables in the order you specify. This has the same effect as specifying STRAIGHT JOIN in the WHERE clause. ● Use SQL_SMALL_RESULT and SQL_BIG_RESULT to get the result set having either few rows or a large number of them. ● SQL_BUFFER_RESULT tells MySQL to put the result set into a temporary table. Use this when it takes significant time to send the results to the client to avoid having the queried tables locked for that time. ● SQL_CACHE and SQL_NOCACHE tell MySQL whether to cache the results.
  • 10. USING SELECT STATEMENT OPTIONS • SQL_CALC_FOUND_ROWS is used with the LIMIT clause to work out how many rows would have been returned if there had been no LIMIT clause. We can then retrieve this number with select found_rows(); • HIGH PRIORITY gives priority to query over any UPDATE statements that are waiting to use the involved tables. • DISTINCTROW is a synonym for DISTINCT. ALL (default option) return all duplicates. • The SELECT INTO OUTFILE is the opposite of the LOAD DATA INFILE. • The PROCEDURE clause specify a procedure ( must be written in C++) that can be applied to the result set before it is sent to the client. • The FOR UPDATE and LOCK IN SHARE MODE clauses affect only if storage engine uses page or row-level locking (InnoDB and BDB). FOR UPDATE set an exclusive lock, and LOCK IN SHARE MODE set a shared lock.
  • 11. INSERT The general form of the INSERT statement from the MySQL manual is as follows: INSERT [LOW_PRIORITY | DELAYED] [IGNORE] [INTO] tbl_name SET col_name=(expression | DEFAULT), ... [ ON DUPLICATE KEY UPDATE col_name=expression, ... ] INSERT [LOW_PRIORITY | DELAYED] [IGNORE] [INTO] tbl_name [(col_name,...)] VALUES ((expression | DEFAULT),...),(...),... [ ON DUPLICATE KEY UPDATE col_name=expression, ... ] INSERT [LOW_PRIORITY | DELAYED] [IGNORE] [INTO] tbl_name [(col_name,...)] SELECT …
  • 12. Clauses in the INSERT statement ● An INSERT should be specified as LOW PRIORITY or DELAYED. Both clauses will cause the insertion to be delayed until no client is trying to read from the table. ● The difference between them is that LOW PRIORITY will block the inserting client and DELAYED will not. ● Specifying IGNORE is useful when you are inserting multiple rows. If one of the rows you are trying to insert clashes with an existing row's PRIMARY KEY or UNIQUE value, an error will occur and the insert will be aborted. But by specifying IGNORE, the error will be ignored and will attempt to insert the next row. ● A column should contain its default value by specifying DEFAULT as the value for that column. ● The ON DUPLICATE KEY UPDATE clause allows to deal with clashing primary key or unique values. ● Follow this clause with an update statement that can use to change the primary key or unique value in the row already in the table so that it no longer clashes with the new row.
  • 13. Clauses in the INSERT statement ● Example of use of ON DUPLICATE KEY UPDATE clause: create table warning( employeeID int primary key not null references employee(employeeID), count int default 1 ) ; insert into warning (employeeID) values (6651) on duplicate key update count=count+1; ● This clause is useful for situations in which you want to not only record unique events, but also take some action, such as incrementing a counter when non-unique events occur. ● Any sort of logging would be a good example, but in keeping with the employee database we have been using, we will record employees who have been given a warning in the table warning.
  • 14. USING REPLACE The REPLACE statement is exactly like the INSERT statement except that if a key clash occurs, the new row you are inserting will replace the old row. This is the general form of REPLACE from the MySQL manual: REPLACE [LOW_PRIORITY | DELAYED] [INTO] tbl_name SET col_name=expression, col_name=expression,... REPLACE [LOW_PRIORITY | DELAYED] [INTO] tbl_name [(col_name,...)] VALUES (expression,...),(...),... REPLACE [LOW_PRIORITY | DELAYED] [INTO] tbl_name [(col_name,...)] SELECT ...
  • 15. USING DELETE This is the general form of the DELETE statement from the MySQL manual: DELETE [LOW_PRIORITY] [QUICK] FROM table_name[.*] [, table_name[.*] ...] USING table-references [WHERE where_definition] DELETE [LOW_PRIORITY] [QUICK] FROM table_name [WHERE where_definition] [ORDER BY ...] [LIMIT rows] DELETE [LOW_PRIORITY] [QUICK] table_name[.*] [, table_name[.*] ...] FROM table-references [WHERE where_definition]
  • 16. USING DELETE The other two forms allow to delete rows from one or more tables with references to other tables. For example: delete employee, employeeSkills from employee, employeeSkills, department where employee.employeeID = employeeSkills.employeeID and employee.departmentID = department.departmentID and department.name='Finance'; The tables in the initial delete clause will have rows deleted from them, whereas the tables listed in the from clause are used for searching for data and will not have rows deleted unless they are also listed in the delete clause.
  • 17. USING DELETE There are a couple of other optional clauses in the general form of the DELETE statement: • The LOW_PRIORITY clause works in the same way as it does in the INSERT statement. • Specifying QUICK may speed up the DELETE statement by telling MySQL not to do some of its housekeeping on indexes while deleting from the table. • The ORDER BY clause specifies the order in which to delete rows. This is most useful in conjunction with the LIMIT clause (The LIMIT clause allows us to set a maximum number of rows that can be deleted by the DELETE statement), for example, we may want to delete the oldest n rows from a table.
  • 18. USING UPDATE This is the general form of the UPDATE statement from the MySQL manual: UPDATE [LOW_PRIORITY] [IGNORE] tbl_name SET col_name1=expr1 [, col_name2=expr2 ...] [WHERE where_definition] [ORDER BY ...] [LIMIT rows] UPDATE [LOW_PRIORITY] [IGNORE] tbl_name [, tbl_name ...] SET col_name1=expr1 [, col_name2=expr2 ...] [WHERE where_definition]
  • 19. USING UPDATE ● The UPDATE statement is similar in many respects to the DELETE statement. ● Can use an optional WHERE clause to update particular rows or leave it off to update all rows. ● Can fall into the trap of forgetting to specify a WHERE clause— for example update user set password='test'; ● This highlights the usefulness of --i-am-a-dummy mysql option, if you are forced to work with dummies. ● The second version of the UPDATE statement is a multi-table update. This works similarly to the multi-table deletes. Only the columns you specifically list in the SET clause will be updated. ● Other clauses of the UPDATE statement are: The LOW_PRIORITY and IGNORE clauses work the same as they do in INSERT. The ORDER BY and LIMIT clauses work the same as they do in DELETE.
  • 20. --i-am-a-dummy ● A really useful option to mysql is the --i-am-a-dummy option. ● Can invoke this option in a less pejorative way using --safe-updates. For example: mysql --i-am-a-dummy -u root -p ● It is unusual to want to delete all the rows from a table. ● However, because this is the shortest form of the delete statement, you may sometimes type it by accident without a WHERE clause. ● You can save yourself this anguish by switching on the -–safe-updates or –-i-am-a-dummy command-line options of the mysql client. ● These options prevent you from deleting (or updating) rows without specifying a key constraint in the WHERE clause. That is, you need to specify that you want to delete only rows containing certain key values.
  • 23. Optimization and Execution ● MySQL parse queries to create an internal structure (the parse tree), and then applies a variety of optimizations. ● These may include rewriting the query, determining the order in which it will read tables, choosing which indexes to use, and so on. ● Before even parsing the query, though, the server consults the query cache, which can store only SELECT statements, along with their result sets. ● If anyone issues a query that’s identical to one already in the cache, the server doesn’t need to parse, optimize, or execute the query at all—it can simply pass back the stored result set!
  • 24. Concurrency Control ● Anytime more than one query needs to change data at the same time, the problem of concurrency control arises. ● MySQL has to do this at two levels: the server level and the storage engine level. ● Systems that deal with concurrent read/write access typically implement a locking system that consists of two lock types. ● These locks are usually known as shared locks and exclusive locks, or read locks and write locks.
  • 25. Read/Write Locks ● Read locks on a resource are shared, or mutually nonblocking: many clients may read from a resource at the same time and not interfere with each other. ● Write locks, on the other hand, are exclusive—i.e., they block both read locks and other write locks—because the only safe policy is to have a single client writing to the resource at given time and to prevent all reads when a client is writing. ● MySQL performs this lock management internally in a way that is transparent much of the time. ● Two most important lock strategies are:
  • 26. Read/Write Locks Table locks ● The most basic locking strategy available in MySQL, and the one with the lowest overhead, is table locks. ● It locks the entire table. When a client wishes to write to a table (insert, delete, update), it acquires a write lock.This keeps all other read and write operations at bay. ● When nobody is writing,readers can obtain read locks, which don’t conflict with other read locks. ● Write locks can advance past read locks in the queue, but read locks cannot advance past write locks. ● Although storage engines can manage their own locks, MySQL itself also uses a variety of locks. For instance, the server uses a table-level lock for statements such as ALTER TABLE, regardless of the storage engine.
  • 27. Read/Write Locks ROW LOCKS ● The locking style that offers the greatest concurrency (and carries the greatest overhead) is the use of row locks. ● Row-level locking is available in the InnoDB and Falcon storage engines. ● Row locks are implemented in the storage engine, not the server.
  • 29. Using Transactions with InnoDB Tables ● A transaction is a sequence of related instructions that must be treated as one indivisible unit. ● All the work in the transaction must be done, or all of it must be left undone. This concept is known as atomicity. ● A transaction is atomic because it cannot be broken down into parts—it all gets processed or it all gets ignored. ● For example: Consider a simple database that records bank account details. Each account has, at minimum, a unique identifier and a balance.Consider the following pair of statements intended to deposit $500 into account 2: # first check balance select balance from account where number = 2; # query gives us a result of $1000 # now store updated balance update account set balance = 1500 where number = 2; ● These queries are related and need to be run together.Otherwise not get the result as expected.
  • 30. Using Transactions with InnoDB Tables ● If two clients were running pairs of queries like this at the same time, our final result would depend on timing. If we were attempting to deposit $500 with these queries and another client was attempting to deposit $100 with the following pair, the end result could be a balance of $1100 or $1500—neither of which is the right result. # first check balance select balance from account where number = 2; # query gives us a result of $1000 # now store updated balance update account set balance = 1100 where number = 2; ● To solve the problem, Make updates relative rather than absolute that make them into single, indivisible units The following query will run correctly: update account set balance = balance + 500 where number = 2;
  • 31. Using Transactions with InnoDB Tables ● A single update statement in MySQL is always atomic. It cannot be interrupted by another query or half succeed. It will complete or will completely fail on an error. ● Now, More complex scenarios is: Consider the following pair of queries intended to transfer $1000 from account 2 to account 1: update account set balance = balance - 1000 where number = 2; update account set balance = balance + 1000 where number = 1; ● Both updates are relative, but it is important that these two queries be run together for sensible results. The total amount of money in the system should be the same after the queries as before. ● But, If a power failure happened between running the first query and running the second query, our data would no longer be consistent.
  • 32. Using Transactions with InnoDB Tables ● In this case we could write this: update account as source, account as dest set source.balance = source.balance – 1000, dest.balance = dest.balance + 1000 where source.number = 2 and dest.number = 1; ● By using two aliases to the account table (source and dest), we have ensured that this is one atomic update. ● In this case the only casualty is readability. The combined query is harder to read and debug than our first attempt.
  • 33. Using Transactions with InnoDB Tables ● In many cases, it may not be possible to collapse all the related queries into one like this. ● The solution in those cases, and anytime you want more readable code, is to use MySQL's transaction syntax. ● By marking a set of statements as a transaction, you inform the database that they are a related, indivisible set. ● They should be treated as an atomic unit and either all succeed or all have no effect. ● You can run these two queries as a single transaction using the following SQL statements: start transaction; update account set balance = balance - 1000 where number = 2; update account set balance = balance + 1000 where number = 1; Commit; ● An important property of transactions is that they are not visible to other sessions until they are complete and committed. No other thread can read inconsistent data from the table(s) while you are in the process of updating it.
  • 34. Using Transactions with InnoDB Tables ● In the case of transfer example, adding a SELECT statement to check the removal of more money from the source account than it contained, use the keyword ROLLBACK to cancel the whole transaction. The syntax is: start transaction; update account set balance = balance - 1000 where number = 2; update account set balance = balance + 1000 where number = 1; select balance from account where number = 2; # select tells us that account #2 has a negative balance! # we'd better abort rollback; ● Calling ROLLBACK aborts the transaction and undoes any changes it would have made. ● A transaction that was rolled back instead of committed leaves no trace in the data. Because partial results were never visible to other sessions, it is exactly as though it never happened.
  • 35. Using Transactions with InnoDB Tables SETTING THE AUTOCOMMIT MODE start transaction; update account set balance = balance - 1000 where number = 2; commit; start transaction; update account set balance = balance + 1000 where number = 1; commit; ● Disable autocommit behavior using the SET command as follows: set autocommit=0; ● Command to put MySQL back into autocommit mode: set autocommit=1; ● The autocommit variable is local to a single session, so changing the mode will affect only queries run from your session. ● Turning autocommit off will not need to call START TRANSACTION to start a transaction. It is very important, to remember to call COMMIT periodically to commit any changes you have made to the database.
  • 37. MySQL Triggers ● A trigger is a set of SQL statements that is invoked automatically when a change is made to the data on the associated table. ● A trigger can be defined to be invoked either before or after the data is changed by INSERT, UPDATE or DELETE statement. ○ BEFORE INSERT – activated before data is inserted into the table. ○ AFTER INSERT – activated after data is inserted into the table. ○ BEFORE UPDATE – activated before data in the table is updated. ○ AFTER UPDATE – activated after data in the table is updated. ○ BEFORE DELETE – activated before data is removed from the table. ○ AFTER DELETE – activated after data is removed from the table.
  • 38. MySQL Triggers MySQL trigger limitation MySQL triggers cannot: ● Use SHOW, LOAD DATA, LOAD TABLE, BACKUP DATABASE, RESTORE, FLUSH and RETURN statements. ● Use statements that commit or rollback implicitly or explicitly such as COMMIT , ROLLBACK , START TRANSACTION , LOCK/UNLOCK TABLES , ALTER , CREATE , DROP , RENAME. ● Use prepared statements such as PREPARE and EXECUTE. ● Use dynamic SQL statements. From MySQL version 5.1.4, a trigger can call a stored procedure or stored function,
  • 39. MySQL Trigger Syntax CREATE TRIGGER triggerTime_table Name_triggerEvent ON table_name FOR EACH ROW BEGIN ... END; ● The trigger name format is [trigger time]_[table name]_[trigger event], for example before_employees_update. ● Must specify the activation time (BEFORE or AFTER) when you define a trigger. Use the BEFORE keyword to process action prior to the change is made on the table and AFTER to process action after the change is made. ● The trigger event (INSERT, UPDATE or DELETE) causes the trigger to be invoked. A trigger only can be invoked by one event. ● A trigger must be associated with a specific table, specify the table name after the ON keyword. ● Place the SQL statements (logic for the trigger) between BEGIN and END block.
  • 40. MySQL Trigger Example DELIMITER $$ CREATE TRIGGER before_employee_update BEFORE UPDATE ON employees FOR EACH ROW BEGIN INSERT INTO employees_audit SET action = 'update', employeeNumber = OLD.employeeNumber, lastname = OLD.lastname, changedat = NOW(); END$$ DELIMITER ;
  • 42. PL/SQL - Introduction ● Procedural Language SQL provides the feature to write block of SQL statements which can be executed in one go. ● Can call other Stored Procedure and Functions ● Stored Procedure can return the values via OUT variable ● Syntax Create statement CREATE PROCEDURE my_first_sp() BEGIN Select * from user; END Call statement Call my_first_sp();
  • 43. PL/SQL - Cursors and Handlers Cursors Cursor iterate over result set returned by select statement Syntax: DECLARE int id; DECLARE my_first_cursor CURSOR FOR SELECT id from user; OPEN my_first_cursor; FETCH my_first_cursor INTO id; CLOSE my_first_cursor; Handlers Handlers are statements that need specific handling DECLARE int finished; SET finished = 0; DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
  • 44. PL/SQL - Error Handling Handlers can be of type CONTINUE, EXIT and UNDO(Not supported) Condition value of the Handler can be SQLSTATE, SQLWARNING, NOT FOUND, SQLEXCEPTION and mysql_error_code Error Handling ● Exit on Error ○ DECLARE EXIT HANDLER FOR SQLEXCEPTION ○ DECLARE EXIT HANDLER FOR SQLSTATE '23000' ● Continue on Error ○ DECLARE CONTINUE HANDLER FOR 1062 ○ DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1
  • 45. PL/SQL - Transactions Transaction is required when we need to run either all the statements or nothing at all Components: ● Start Transaction Starts a new Transaction ● Commit Commit all the transactions in a Transaction block ● Rollback Revert all the transactions in a transaction block e.g. when an exception occurs ● Autocommit Disable or enable default autocommit for the current session Syntax: START TRANSACTION; UPDATE user SET username=’abc’ WHERE id=1; COMMIT;
  • 47. MySQL’s Storage Engines ● MySQL stores each database (also called a schema) as a subdirectory of its data directory in the underlying filesystem. ● When creating a table, MySQL stores the table definition in a .frm file with the same name as the table. For example, for table named MyTable, the table definition is MyTable.frm. ● MySQL uses the filesystem to store database names and table definitions, case sensitivity depends on the platform. On a Windows, they are case insensitive; on Unix-like systems, they are case sensitive. ● Each storage engine stores the table’s data and indexes differently, but the server itself handles the table definition.
  • 48. UPLOADING DATA WITH LOAD DATA INFILE The general form of the LOAD DATA INFILE statement is as follows: LOAD DATA [LOW_PRIORITY | CONCURRENT] [LOCAL] INFILE 'fileName.txt' [REPLACE | IGNORE] INTO TABLE tbl_name [FIELDS [TERMINATED BY 't'] [[OPTIONALLY] ENCLOSED BY ''] [ESCAPED BY '' ] ] [LINES TERMINATED BY 'n'] [IGNORE number LINES] [(col_name,...)]
  • 49. UPLOADING DATA WITH LOAD DATA INFILE The optional clauses are as listed here: ● The LOW PRIORITY clause works the same way it does in the INSERT statement by waiting for other clients to stop reading from the table. ● CONCURRENT allows other clients to read from the table while the bulk insert is going on. ● Optional keyword LOCAL, means data file is on the client machine. Otherwise, MySQL will look for the infile on the server. ● To deal with key clashes while inserting data, REPLACE and IGNORE are two methods. ● REPLACE tells MySQL to replace the old row with the new row. ● IGNORE tells MySQL to keep the old row. ● The FIELDS and LINES clauses specify how the data in the infile is laid out. ● The IGNORE number LINES clause tells MySQL to ignore the first number lines in the infile. ● The final clause allows you to specify that you only want to read data into some of the table's columns.
  • 50. Understanding MySQL's Table Types ● MySQL has six table types: ISAM, MyISAM, InnoDB, BDB, MERGE, and HEAP. ● Only InnoDB and BDB tables are transaction safe. ● Only MyISAM tables support full-text indexing and searching. ISAM ● ISAM had been deprecated and superceded by MyISAM. ● ISAM tables have a hard size limit of 4GB. ● ISAM tables are not portable. ● Can have a maximum of 16 keys per table and a maximum key length of 256 bytes (characters).
  • 51. Understanding MySQL's Table Types MYISAM Table ● Default table type. It is very fast, but not transaction safe. ● Support table compression. ● Size of MyISAM tables is limited only by the operating system, and worked around with MERGE tables. ● The data files storing MyISAM tables are portable from system to system. ● Can have a maximum of 64 keys per table and a maximum key length of 1024 bytes. ● Can be one of three types: dynamic, static, or compressed. ● Automatically becomes dynamic or static depending on the definition of its columns. ● Compressed tables must be deliberately created with the myisampack tool.
  • 52. Understanding MySQL's Table Types MYISAM Table ● Tables with fixed-length rows created as static tables, and variable-length rows created as dynamic tables. ● A table with only char and numeric columns ( as all have a fixed size) will be created as a static table. ● A table containing any varchar, text, or blob columns (as all vary with the size of their contents) will be dynamic. FULL-TEXT SEARCHING ON MYISAM TABLES ● One feature of MyISAM tables is full-text searching and indexing. ● Normal indexes are very good at finding rows where a value in the table matches a given value, but it is common to want to search for words or strings within a block of text.
  • 53. FULL-TEXT SEARCHING ON MYISAM TABLES ● Example: create table article ( articleID int not null auto_increment primary key, title varchar(255), body text, fulltext (title, body) ); ● Query retrieve records containing the word 'merger': select title from article where match (title, body) against ('merger'); ● Query retrieve records containing any of the words 'merge', 'acquisition', 'acquire', or 'takeover'. select title from article where match (title, body) against ('merge acquisition acquire takeover');
  • 54. Understanding MySQL's Table Types INNODB Tables ● Transaction safe. ● Supports row-level locking. ● No theoretical maximum table size because tables may be stored in more than one file. ● Provides consistent nonlocking reads in SELECT. ● Portable from system to system. ● Take more disk space than MyISAM tables. ● Foreign keys are supported between InnoDB tables.
  • 55. Understanding MySQL's Table Types BDB Tables ● Transaction safe. ● Not as widely used with MySQL as InnoDB. ● Supports page-level locking. ● Not portable. MERGE Tables ● Used to treat multiple MyISAM tables as a single table, thus maximum file size limitation is removed from MyISAM tables. HEAP Tables ● Stored only in memory and need to be limited in size to avoid running out of memory. ● Data stored in a HEAP table is volatile and will be lost in the event of a power failure. ● Super fast, as long as you have enough physical memory to keep them. ● Notot support AUTO_INCREMENT, TEXT, or BLOB.
  • 56. ?

Editor's Notes

  1. The difference between them is that LOW PRIORITY will block the inserting client and DELAYED will not. What this means is that if you run a LOW PRIORITY insert, you may wait for some time before you can continue running queries in your client. With DELAYED, you will be told OK and can continue running queries, but you need to remember that the insert will not be performed until the table is not in use.
  2. Put the trigger name after the CREATE TRIGGER statement. The trigger name should follow the naming convention
  3. The FIELDS and LINES clauses specify how the data in the infile is laid out. The values in the general form are the defaults—each row on a new line, column values separated by tabs. We can also enclose column values in quotes and use the backslash character to escape any special characters (like single quotes) that might confuse MySQL.