SlideShare a Scribd company logo
SQL
2
Contents
 Table and SQL Variables
 Case/Condition
 Cursor
 Iteration
 Trigger
 View
 Procedure
 Function
3
SQL (User) Variable
 MySQL allows you to assign values to variables and refer to them later.
 This is useful when you want to save the results of calculations for use in subsequent
statements.
 If you refer to an uninitialized variable that has not been assigned a value explicitly, its
value is NULL.
 User variables are specific to the client connection within which they are used and exist
only for the duration of that connection.
 A user variable used within a connection cannot be accessed by other connections. When
a connection ends, all its user variables are lost.
SET @var1:="USA", @var2="GBR", @var3="CAN";
SELECT @var1, @var2, @var3, @var4;
Table Variable (Temporary table)
 It’s visible only to the client that created it and may be used only by that client. This means
that different clients can create TEMPORARY tables that have the same name and no
conflict occurs.
 A TEMPORARY table exists only for the duration of the connection in which it was created.
 A TEMPORARY table may have the same name as a non-TEMPORARY table.
 A TEMPORARY table can be renamed only with ALTER TABLE. You cannot use RENAME
TABLE.
CREATE TEMPORARY TABLE tmp_table
SELECT CountryCode, COUNT(*) AS LangCount FROM CountryLanguage GROUP BY CountryCode;
DROP TABLE tmp_table;
4
Iteration
 Compound statement syntax in MySQL provides for three kinds of loops.
 LOOP constructs an unconditional loop with no loop-termination syntax. For this reason, it must contain a
statement that explicitly exits the loop.
LOOP
statement_list
END LOOP
DECLARE i INT DEFAULT 0;
my_loop: LOOP
SET i = i + 1;
IF i >= 10 THEN
LEAVE my_loop;
END IF;
END LOOP my_loop;
 REPEAT and WHILE, the other two loop constructs, are conditional. They include a clause that determines
whether loop execution continues or terminates.
REPEAT
statement_list UNTIL expr
END REPEAT
DECLARE i INT DEFAULT 0;
REPEAT
SET i = i + 1;
UNTIL i >= 10
END REPEAT;
WHILE expr DO
statement_list
END WHILE
WHILE 1 = 0 DO
SET x = 1;
END WHILE;
5
Control Flow Functions [Case/Condition]
 Control flow functions enable you to choose between different values based on the result of
an expression.
 IF() tests the expression in its first argument and returns its second or third argument
depending on whether the expression is true or false:
SELECT IF(1 > 0, ‘yes’,’no’);
IF val IS NULL
THEN SELECT ‘val is NULL’;
ELSE SELECT ‘val is not NULL’;
END IF;
 The CASE construct is not a function, but it too provides flow control. It has two forms of
syntax.
mysql> SET @val = 1;
mysql> SELECT CASE @val
-> WHEN 0 THEN ‘@val is 0’
-> WHEN 1 THEN ‘@val is 1’
-> ELSE ‘@valisnot0or1’ -> END AS result;
mysql> SET @val = NULL;
mysql> SELECT CASE
-> WHEN @val IS NULL THEN ‘@val is NULL’
-> WHEN @val < 0 THEN ‘@val is less than 0’
-> WHEN @val > 0 THEN ‘@val is greater than 0’
-> ELSE ‘@val is 0’
-> END AS result;
6
Cursor
 A cursor enables you to access a result set one row at a time.
 Because of this row orientation, cursors often are used in loops that fetch and process a row within each
iteration of the loop.
 Asensitive: there are two kinds of cursors: asensitive cursor and insensitive cursor. An asensitive cursor
points to the actual data, whereas an insensitive cursor uses a temporary copy of the data. An asensitive
cursor performs faster than an insensitive cursor because it does not have to make a temporary copy of
data.
 Read only: Not updatable, You can not write cursor like declare curs1 cursor for Update test111 set id=2.
 Nonscrollable: Can be traversed only in one direction and cannot skip rows.
BEGIN DECLARE row_count INT DEFAULT 0;
DECLARE code_var CHAR(3);
DECLARE name_var CHAR(52);
DECLARE c CURSOR FOR
SELECT Code, Name FROM Country WHERE Continent = ‘Africa’;
OPEN c;
BEGIN
DECLARE EXIT HANDLER FOR SQLSTATE ‘02000’ BEGIN END;
LOOP
FETCH c INTO code_var, name_var;
SET row_count = row_count + 1;
END LOOP;
END;
CLOSE c;
SELECT ‘number of rows fetched =’, row_count;
END;
7
Cursor
Advantages:
No need to write business logic after fetching data from your code logic.
Gives you better flexibility for operating even on the single column of the row. Manipulation
become always easy.
Saves you from the simplex join structure.
Easy to maintain the business logic of your application at one place.
Disadvantages:
Slow down your stored procedure or function performance in cause of large record set in
cursor.
Debugging of your business logic become tough.
Hard to manage.
Need to consider locking of the database.
8
Trigger
 A trigger is an object that belongs to a database.
 Each trigger within the database must have a different name.
 A trigger is defined to activate when a particular kind of event occurs for a given table.
 The trigger definition includes a statement to be executed when the trigger activates.
 The events for which triggers can be defined are INSERT, DELETE, and UPDATE.
 A given trigger is defined for only one of these events, but you can define multiple triggers
for a table, one trigger per type of event.
 Triggers can be defined to activate either before or after the event. This means there can
be two triggers per event (for example, one trigger to activate before an UPDATE and one
to activate after).
 A trigger can change values before they are inserted into a table or used to update a table.
For example, you can check for out-of-bounds values and modify them to be within bounds.
This capability enables the use of triggers as data filters.
 You cannot create a trigger for a TEMPORARY table or a view.
CREATE TRIGGER trigger_name
{ BEFORE | AFTER }
{ INSERT | UPDATE | DELETE } ON table_name
FOR EACH ROW triggered_statement
CREATE TRIGGER Capital_bi
BEFORE INSERT
ON Capital
FOR EACH ROW
SET NEW.Population = IF(NEW.Population < 0, 0, TRUNCATE(NEW.Population,-3));
mysql> INSERT INTO Capital VALUES -> (‘CountryA’,’CityA’,-39),
-> (‘CountryB’,’CityB’,123456);
9
VIEW
 View is a DB object which is defined in terms of a SELECT statement that retrieves the
data you want the view to produce.
 Views are sometimes called “virtual tables”.
 A view can be used to select from regular tables (called “base tables”) or other views.
Creating Views : To create a view.
 CREATE VIEW CityView AS SELECT ID, Name FROM City;
 CREATE VIEW CountryLangCount (Name, LangCount) AS
-> SELECT Name, COUNT(Language)
-> FROM Country, CountryLanguage WHERE Code = CountryCode -> GROUP BY Name;
Altering Views : To change the definition of an existing view.
 ALTER VIEW LargePop AS SELECT Name, Population FROM CountryPop WHERE Population >= 100000000;
Dropping Views :
 DROP VIEW IF EXISTS v1, v2;
Advantages:
 Access to data becomes simplified because it contains subset of data from multiple tables.
 Views can be used to display table contents differently for different users, so that each user
sees only the data pertaining to that user’s activities.
 Join and simplify multiple tables into a single virtual table.
 Acts as aggregated tables, where aggregated data (sum, average etc.) are calculated and
presented as part of the data.
 Gives real time data.
10
VIEW
Disadvantages:
When table is dropped view becomes inactive, it depends on the table objects.
It affects performance, querying from view takes more time than directly querying from the
table
Restrictions on Views:
You cannot create a TEMPORARY view.
You cannot associate a trigger with a view.
The tables on which a view is to be based must already exist.
The SELECT statement in a view definition cannot contain any of these constructs:
 Subqueries in the FROM clause
 References to TEMPORARY tables
 References to user variables
 References to procedure parameters, if the view definition occurs within a stored routine
 References to prepared statement parameters
11
Benefits of Stored Routines (Procedure & Function)
 More flexible SQL syntax : Stored routines can be written using compound statements and
flow-control constructs, that make it easier to express complex logic.
 Error handling capabilities (Stored Procedure)
 Standards compliance.
 Code packaging and encapsulation, A routine allows the code that performs an operation to
be stored once on the server and accessed from multiple applications.
 Less “re-invention of the wheel.” A collection of stored routines acts as a library of solutions
to problems.
 Separation of logic.
 Ease of maintenance.
 Reduction in network bandwidth requirements.
 Better security.
Namespace for Stored Routines
 MySQL interprets an unqualified reference, routine_name, as a reference to a procedure or
function in the default database. To refer to a routine in a specific database, use a qualified
name of the form db_name.routine_name.
 Due to this association of a routine with a database, you must have access to that database
to be able to invoke the routine.
 When you drop a database, any stored routines in the database are also dropped.
12
Stored Procedure
Creating Stored Procedures:
CREATE PROCEDURE proc_name ([parameters]) [characteristics]
routine_body
CREATE PROCEDURE rect_area (width INT, height INT)
SELECT width * height AS area;
Stored Procedure with Compound Statements (Begins and ends with the BEGIN and END keywords and
creates a block).
mysql> delimiter //
mysql> CREATE PROCEDURE world_record_count ()
-> BEGIN
-> SELECT ‘Country’, COUNT(*) FROM Country;
-> SELECT ‘City’, COUNT(*) FROM City;
-> SELECT ‘CountryLanguage’, COUNT(*) FROM CountryLanguage;
-> END;
-> //
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
Declaring Parameters:
IN indicates an input parameter. The parameter value is passed in from the caller to the
procedure
OUT indicates an output parameter. The procedure sets its value, and after the proce- dure
terminates. The caller sees that value when it accesses the variable.
INOUT indicates a “two-way” parameter that can be used both for input and for output.
If no keyword is given before a procedure parameter name, it is an IN parameter by default.
13
Stored Procedure
Stored Procedure with Declared Parameters
CREATE PROCEDURE param_test (IN p_in INT, OUT p_out INT, INOUT p_inout INT)
BEGIN SELECT p_in, p_out, p_inout;
SET p_in = 100, p_out = 200, p_inout = 300;
END;
SET @v_in = 0, @v_out = 0, @v_inout = 0;
Calling(Invoking) Stored Procedure
CALL param_test(@v_in, @v_out, @v_inout);
The DECLARE Statement in Stored Procedure:
Local variables
Conditions, such as warnings or exceptions
Handlers for conditions
Cursors for accessing result sets row by row
Variables in Stored Procedure:
DECLARE var_name [, var_name] ... data_type [DEFAULT value]
Assigning Variable Values with SET:
DECLARE var1, var2, var3 INT;
SET var1 = 1, var2 = 2;
SET var3 = var1 + var2;
Variables in Stored Procedure:
DECLARE name_var CHAR(52);
DECLARE pop_var INT;
SELECT Name, Population INTO name_var, pop_var
FROM Country WHERE Code = ‘ESP’;
14
Function
Creating Function:
CREATE FUNCTION func_name ([parameters])
RETURNS data_type
[characteristics]
routine_body
CREATE FUNCTION circle_area (radius FLOAT)
RETURNS FLOAT
RETURN PI() * radius * radius;
Calling(Invoking) Function
SELECT circle_area(10);
Functions can have Compound Statements, Declared Parameters & Variables as Store Procedure has.
15
Difference Between Stored Procedure and Function
 Function is not pre-compiled object it will execute every time whenever it was called.
 Function must return a value but in Stored Procedure it is optional (Procedure can return
zero or n values).
 Functions can have only input parameters for it whereas Procedures can have input/output
parameters .
 Function takes one input parameter it is mandatory but Stored Procedure may take o to n
input parameters.
 Functions can be called from Procedure whereas Procedures cannot be called from
Function.
 Procedure allows SELECT as well as DML(INSERT/UPDATE/DELETE) statement in it
whereas Function allows only SELECT statement in it.
 Procedures can not be utilized in a SELECT statement whereas Function can be
embedded in a SELECT statement.
 Stored Procedures cannot be used in the SQL statements anywhere in the
WHERE/HAVING/SELECT section whereas Function can be.
 Exception can be handled by try-catch block in a Procedure whereas try-catch block cannot
be used in a Function.
 We can go for Transaction Management in Procedure whereas we can't go in Function.
http://tutoriz.com/Thread-Difference-between-Stored-Procedure-and-Function-in-Sql-with-Example

More Related Content

What's hot

Oracle: DDL
Oracle: DDLOracle: DDL
Oracle: DDL
DataminingTools Inc
 
8. sql
8. sql8. sql
8. sql
khoahuy82
 
Sql server ___________session_16(views)
Sql server  ___________session_16(views)Sql server  ___________session_16(views)
Sql server ___________session_16(views)
Ehtisham Ali
 
SQL Tutorial - Basic Commands
SQL Tutorial - Basic CommandsSQL Tutorial - Basic Commands
SQL Tutorial - Basic Commands
1keydata
 
Les13
Les13Les13
Babitha2.mysql
Babitha2.mysqlBabitha2.mysql
Babitha2.mysql
banubabitha
 
Oracle: PLSQL Introduction
Oracle: PLSQL IntroductionOracle: PLSQL Introduction
Oracle: PLSQL Introduction
DataminingTools Inc
 
Database Management System 1
Database Management System 1Database Management System 1
Database Management System 1
Swapnali Pawar
 
Oracle: DML
Oracle: DMLOracle: DML
Oracle: DML
DataminingTools Inc
 
Database Management - Lecture 2 - SQL select, insert, update and delete
Database Management - Lecture 2 - SQL select, insert, update and deleteDatabase Management - Lecture 2 - SQL select, insert, update and delete
Database Management - Lecture 2 - SQL select, insert, update and delete
Al-Mamun Sarkar
 
Cursors, triggers, procedures
Cursors, triggers, proceduresCursors, triggers, procedures
Cursors, triggers, procedures
Vaibhav Kathuria
 
Oracle Database DML DDL and TCL
Oracle Database DML DDL and TCL Oracle Database DML DDL and TCL
Oracle Database DML DDL and TCL
Abdul Rehman
 
Assignment#02
Assignment#02Assignment#02
Assignment#02
Sunita Milind Dol
 
Sql basics and DDL statements
Sql basics and DDL statementsSql basics and DDL statements
Sql basics and DDL statements
Mohd Tousif
 
Mysql
MysqlMysql
Mysql
TSUBHASHRI
 
Ddl commands
Ddl commandsDdl commands
Ddl commands
Vasudeva Rao
 
Oracle SQL Advanced
Oracle SQL AdvancedOracle SQL Advanced
Oracle SQL Advanced
Dhananjay Goel
 

What's hot (17)

Oracle: DDL
Oracle: DDLOracle: DDL
Oracle: DDL
 
8. sql
8. sql8. sql
8. sql
 
Sql server ___________session_16(views)
Sql server  ___________session_16(views)Sql server  ___________session_16(views)
Sql server ___________session_16(views)
 
SQL Tutorial - Basic Commands
SQL Tutorial - Basic CommandsSQL Tutorial - Basic Commands
SQL Tutorial - Basic Commands
 
Les13
Les13Les13
Les13
 
Babitha2.mysql
Babitha2.mysqlBabitha2.mysql
Babitha2.mysql
 
Oracle: PLSQL Introduction
Oracle: PLSQL IntroductionOracle: PLSQL Introduction
Oracle: PLSQL Introduction
 
Database Management System 1
Database Management System 1Database Management System 1
Database Management System 1
 
Oracle: DML
Oracle: DMLOracle: DML
Oracle: DML
 
Database Management - Lecture 2 - SQL select, insert, update and delete
Database Management - Lecture 2 - SQL select, insert, update and deleteDatabase Management - Lecture 2 - SQL select, insert, update and delete
Database Management - Lecture 2 - SQL select, insert, update and delete
 
Cursors, triggers, procedures
Cursors, triggers, proceduresCursors, triggers, procedures
Cursors, triggers, procedures
 
Oracle Database DML DDL and TCL
Oracle Database DML DDL and TCL Oracle Database DML DDL and TCL
Oracle Database DML DDL and TCL
 
Assignment#02
Assignment#02Assignment#02
Assignment#02
 
Sql basics and DDL statements
Sql basics and DDL statementsSql basics and DDL statements
Sql basics and DDL statements
 
Mysql
MysqlMysql
Mysql
 
Ddl commands
Ddl commandsDdl commands
Ddl commands
 
Oracle SQL Advanced
Oracle SQL AdvancedOracle SQL Advanced
Oracle SQL Advanced
 

Viewers also liked

talent-trends-southafrica (1)
talent-trends-southafrica (1)talent-trends-southafrica (1)
talent-trends-southafrica (1)
Julien Manguette
 
Stuffed animal sleepover 2015.12.29
Stuffed animal sleepover 2015.12.29Stuffed animal sleepover 2015.12.29
Stuffed animal sleepover 2015.12.29
Andreea Dobrescu
 
Results
ResultsResults
Results
DIDI1998sdf
 
Talous ja Yhteiskunta 2/2013
Talous ja Yhteiskunta 2/2013Talous ja Yhteiskunta 2/2013
Talous ja Yhteiskunta 2/2013
Palkansaajien tutkimuslaitos
 
Audience Research
Audience ResearchAudience Research
Audience Research
DIDI1998sdf
 
Jero Asia Smart Policy
Jero Asia Smart PolicyJero Asia Smart Policy
Jero Asia Smart Policy
Jero Wijaya
 
Jero asia smartadventure 49 days
Jero asia smartadventure 49 daysJero asia smartadventure 49 days
Jero asia smartadventure 49 days
Jero Wijaya
 
Mount agung bali
Mount agung baliMount agung bali
Mount agung bali
Jero Wijaya
 
Practica#10
Practica#10Practica#10
Practica#10
padilla_24
 
Maigret et la grande perche
Maigret et la grande percheMaigret et la grande perche
Maigret et la grande perche
Surendra Shukla
 
Final draft
Final draftFinal draft
Final draft
Marizel Soro
 
Results
ResultsResults
Results
DIDI1998sdf
 
Bab 1 PENDAHULUAN
Bab 1 PENDAHULUANBab 1 PENDAHULUAN
Bab 1 PENDAHULUAN
Masdar Aripin
 
Innehåll först med innehållsprototyper
Innehåll först med innehållsprototyperInnehåll först med innehållsprototyper
Innehåll först med innehållsprototyper
Per Axbom
 

Viewers also liked (14)

talent-trends-southafrica (1)
talent-trends-southafrica (1)talent-trends-southafrica (1)
talent-trends-southafrica (1)
 
Stuffed animal sleepover 2015.12.29
Stuffed animal sleepover 2015.12.29Stuffed animal sleepover 2015.12.29
Stuffed animal sleepover 2015.12.29
 
Results
ResultsResults
Results
 
Talous ja Yhteiskunta 2/2013
Talous ja Yhteiskunta 2/2013Talous ja Yhteiskunta 2/2013
Talous ja Yhteiskunta 2/2013
 
Audience Research
Audience ResearchAudience Research
Audience Research
 
Jero Asia Smart Policy
Jero Asia Smart PolicyJero Asia Smart Policy
Jero Asia Smart Policy
 
Jero asia smartadventure 49 days
Jero asia smartadventure 49 daysJero asia smartadventure 49 days
Jero asia smartadventure 49 days
 
Mount agung bali
Mount agung baliMount agung bali
Mount agung bali
 
Practica#10
Practica#10Practica#10
Practica#10
 
Maigret et la grande perche
Maigret et la grande percheMaigret et la grande perche
Maigret et la grande perche
 
Final draft
Final draftFinal draft
Final draft
 
Results
ResultsResults
Results
 
Bab 1 PENDAHULUAN
Bab 1 PENDAHULUANBab 1 PENDAHULUAN
Bab 1 PENDAHULUAN
 
Innehåll först med innehållsprototyper
Innehåll först med innehållsprototyperInnehåll först med innehållsprototyper
Innehåll först med innehållsprototyper
 

Similar to SQL

3963066 pl-sql-notes-only
3963066 pl-sql-notes-only3963066 pl-sql-notes-only
3963066 pl-sql-notes-only
Ashwin Kumar
 
Subqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactionsSubqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactions
maxpane
 
SQL Tunning
SQL TunningSQL Tunning
SQL Tunning
Dhananjay Goel
 
Adbms
AdbmsAdbms
Adbms
jass12345
 
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
Alex Zaballa
 
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
Alex Zaballa
 
PostgreSQL Database Slides
PostgreSQL Database SlidesPostgreSQL Database Slides
PostgreSQL Database Slides
metsarin
 
Database COMPLETE
Database COMPLETEDatabase COMPLETE
Database COMPLETE
Abrar ali
 
Dbms important questions and answers
Dbms important questions and answersDbms important questions and answers
Dbms important questions and answers
LakshmiSarvani6
 
MULTIPLE TABLES
MULTIPLE TABLES MULTIPLE TABLES
MULTIPLE TABLES
ASHABOOPATHY
 
Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Training
bixxman
 
Oracle:Cursors
Oracle:CursorsOracle:Cursors
Oracle:Cursors
oracle content
 
Oracle sql material
Oracle sql materialOracle sql material
Oracle sql material
prathap kumar
 
SQL Query
SQL QuerySQL Query
SQL Query
Imam340267
 
Sq lite
Sq liteSq lite
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
PavithSingh
 
Relational Database Language.pptx
Relational Database Language.pptxRelational Database Language.pptx
Relational Database Language.pptx
Sheethal Aji Mani
 
DOODB_LAB.pptx
DOODB_LAB.pptxDOODB_LAB.pptx
DOODB_LAB.pptx
FilestreamFilestream
 
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
TAISEEREISA
 
Performance tuning
Performance tuningPerformance tuning
Performance tuning
ami111
 

Similar to SQL (20)

3963066 pl-sql-notes-only
3963066 pl-sql-notes-only3963066 pl-sql-notes-only
3963066 pl-sql-notes-only
 
Subqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactionsSubqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactions
 
SQL Tunning
SQL TunningSQL Tunning
SQL Tunning
 
Adbms
AdbmsAdbms
Adbms
 
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
 
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
 
PostgreSQL Database Slides
PostgreSQL Database SlidesPostgreSQL Database Slides
PostgreSQL Database Slides
 
Database COMPLETE
Database COMPLETEDatabase COMPLETE
Database COMPLETE
 
Dbms important questions and answers
Dbms important questions and answersDbms important questions and answers
Dbms important questions and answers
 
MULTIPLE TABLES
MULTIPLE TABLES MULTIPLE TABLES
MULTIPLE TABLES
 
Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Training
 
Oracle:Cursors
Oracle:CursorsOracle:Cursors
Oracle:Cursors
 
Oracle sql material
Oracle sql materialOracle sql material
Oracle sql material
 
SQL Query
SQL QuerySQL Query
SQL Query
 
Sq lite
Sq liteSq lite
Sq lite
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
 
Relational Database Language.pptx
Relational Database Language.pptxRelational Database Language.pptx
Relational Database Language.pptx
 
DOODB_LAB.pptx
DOODB_LAB.pptxDOODB_LAB.pptx
DOODB_LAB.pptx
 
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
 
Performance tuning
Performance tuningPerformance tuning
Performance tuning
 

SQL

  • 1. SQL
  • 2. 2 Contents  Table and SQL Variables  Case/Condition  Cursor  Iteration  Trigger  View  Procedure  Function
  • 3. 3 SQL (User) Variable  MySQL allows you to assign values to variables and refer to them later.  This is useful when you want to save the results of calculations for use in subsequent statements.  If you refer to an uninitialized variable that has not been assigned a value explicitly, its value is NULL.  User variables are specific to the client connection within which they are used and exist only for the duration of that connection.  A user variable used within a connection cannot be accessed by other connections. When a connection ends, all its user variables are lost. SET @var1:="USA", @var2="GBR", @var3="CAN"; SELECT @var1, @var2, @var3, @var4; Table Variable (Temporary table)  It’s visible only to the client that created it and may be used only by that client. This means that different clients can create TEMPORARY tables that have the same name and no conflict occurs.  A TEMPORARY table exists only for the duration of the connection in which it was created.  A TEMPORARY table may have the same name as a non-TEMPORARY table.  A TEMPORARY table can be renamed only with ALTER TABLE. You cannot use RENAME TABLE. CREATE TEMPORARY TABLE tmp_table SELECT CountryCode, COUNT(*) AS LangCount FROM CountryLanguage GROUP BY CountryCode; DROP TABLE tmp_table;
  • 4. 4 Iteration  Compound statement syntax in MySQL provides for three kinds of loops.  LOOP constructs an unconditional loop with no loop-termination syntax. For this reason, it must contain a statement that explicitly exits the loop. LOOP statement_list END LOOP DECLARE i INT DEFAULT 0; my_loop: LOOP SET i = i + 1; IF i >= 10 THEN LEAVE my_loop; END IF; END LOOP my_loop;  REPEAT and WHILE, the other two loop constructs, are conditional. They include a clause that determines whether loop execution continues or terminates. REPEAT statement_list UNTIL expr END REPEAT DECLARE i INT DEFAULT 0; REPEAT SET i = i + 1; UNTIL i >= 10 END REPEAT; WHILE expr DO statement_list END WHILE WHILE 1 = 0 DO SET x = 1; END WHILE;
  • 5. 5 Control Flow Functions [Case/Condition]  Control flow functions enable you to choose between different values based on the result of an expression.  IF() tests the expression in its first argument and returns its second or third argument depending on whether the expression is true or false: SELECT IF(1 > 0, ‘yes’,’no’); IF val IS NULL THEN SELECT ‘val is NULL’; ELSE SELECT ‘val is not NULL’; END IF;  The CASE construct is not a function, but it too provides flow control. It has two forms of syntax. mysql> SET @val = 1; mysql> SELECT CASE @val -> WHEN 0 THEN ‘@val is 0’ -> WHEN 1 THEN ‘@val is 1’ -> ELSE ‘@valisnot0or1’ -> END AS result; mysql> SET @val = NULL; mysql> SELECT CASE -> WHEN @val IS NULL THEN ‘@val is NULL’ -> WHEN @val < 0 THEN ‘@val is less than 0’ -> WHEN @val > 0 THEN ‘@val is greater than 0’ -> ELSE ‘@val is 0’ -> END AS result;
  • 6. 6 Cursor  A cursor enables you to access a result set one row at a time.  Because of this row orientation, cursors often are used in loops that fetch and process a row within each iteration of the loop.  Asensitive: there are two kinds of cursors: asensitive cursor and insensitive cursor. An asensitive cursor points to the actual data, whereas an insensitive cursor uses a temporary copy of the data. An asensitive cursor performs faster than an insensitive cursor because it does not have to make a temporary copy of data.  Read only: Not updatable, You can not write cursor like declare curs1 cursor for Update test111 set id=2.  Nonscrollable: Can be traversed only in one direction and cannot skip rows. BEGIN DECLARE row_count INT DEFAULT 0; DECLARE code_var CHAR(3); DECLARE name_var CHAR(52); DECLARE c CURSOR FOR SELECT Code, Name FROM Country WHERE Continent = ‘Africa’; OPEN c; BEGIN DECLARE EXIT HANDLER FOR SQLSTATE ‘02000’ BEGIN END; LOOP FETCH c INTO code_var, name_var; SET row_count = row_count + 1; END LOOP; END; CLOSE c; SELECT ‘number of rows fetched =’, row_count; END;
  • 7. 7 Cursor Advantages: No need to write business logic after fetching data from your code logic. Gives you better flexibility for operating even on the single column of the row. Manipulation become always easy. Saves you from the simplex join structure. Easy to maintain the business logic of your application at one place. Disadvantages: Slow down your stored procedure or function performance in cause of large record set in cursor. Debugging of your business logic become tough. Hard to manage. Need to consider locking of the database.
  • 8. 8 Trigger  A trigger is an object that belongs to a database.  Each trigger within the database must have a different name.  A trigger is defined to activate when a particular kind of event occurs for a given table.  The trigger definition includes a statement to be executed when the trigger activates.  The events for which triggers can be defined are INSERT, DELETE, and UPDATE.  A given trigger is defined for only one of these events, but you can define multiple triggers for a table, one trigger per type of event.  Triggers can be defined to activate either before or after the event. This means there can be two triggers per event (for example, one trigger to activate before an UPDATE and one to activate after).  A trigger can change values before they are inserted into a table or used to update a table. For example, you can check for out-of-bounds values and modify them to be within bounds. This capability enables the use of triggers as data filters.  You cannot create a trigger for a TEMPORARY table or a view. CREATE TRIGGER trigger_name { BEFORE | AFTER } { INSERT | UPDATE | DELETE } ON table_name FOR EACH ROW triggered_statement CREATE TRIGGER Capital_bi BEFORE INSERT ON Capital FOR EACH ROW SET NEW.Population = IF(NEW.Population < 0, 0, TRUNCATE(NEW.Population,-3)); mysql> INSERT INTO Capital VALUES -> (‘CountryA’,’CityA’,-39), -> (‘CountryB’,’CityB’,123456);
  • 9. 9 VIEW  View is a DB object which is defined in terms of a SELECT statement that retrieves the data you want the view to produce.  Views are sometimes called “virtual tables”.  A view can be used to select from regular tables (called “base tables”) or other views. Creating Views : To create a view.  CREATE VIEW CityView AS SELECT ID, Name FROM City;  CREATE VIEW CountryLangCount (Name, LangCount) AS -> SELECT Name, COUNT(Language) -> FROM Country, CountryLanguage WHERE Code = CountryCode -> GROUP BY Name; Altering Views : To change the definition of an existing view.  ALTER VIEW LargePop AS SELECT Name, Population FROM CountryPop WHERE Population >= 100000000; Dropping Views :  DROP VIEW IF EXISTS v1, v2; Advantages:  Access to data becomes simplified because it contains subset of data from multiple tables.  Views can be used to display table contents differently for different users, so that each user sees only the data pertaining to that user’s activities.  Join and simplify multiple tables into a single virtual table.  Acts as aggregated tables, where aggregated data (sum, average etc.) are calculated and presented as part of the data.  Gives real time data.
  • 10. 10 VIEW Disadvantages: When table is dropped view becomes inactive, it depends on the table objects. It affects performance, querying from view takes more time than directly querying from the table Restrictions on Views: You cannot create a TEMPORARY view. You cannot associate a trigger with a view. The tables on which a view is to be based must already exist. The SELECT statement in a view definition cannot contain any of these constructs:  Subqueries in the FROM clause  References to TEMPORARY tables  References to user variables  References to procedure parameters, if the view definition occurs within a stored routine  References to prepared statement parameters
  • 11. 11 Benefits of Stored Routines (Procedure & Function)  More flexible SQL syntax : Stored routines can be written using compound statements and flow-control constructs, that make it easier to express complex logic.  Error handling capabilities (Stored Procedure)  Standards compliance.  Code packaging and encapsulation, A routine allows the code that performs an operation to be stored once on the server and accessed from multiple applications.  Less “re-invention of the wheel.” A collection of stored routines acts as a library of solutions to problems.  Separation of logic.  Ease of maintenance.  Reduction in network bandwidth requirements.  Better security. Namespace for Stored Routines  MySQL interprets an unqualified reference, routine_name, as a reference to a procedure or function in the default database. To refer to a routine in a specific database, use a qualified name of the form db_name.routine_name.  Due to this association of a routine with a database, you must have access to that database to be able to invoke the routine.  When you drop a database, any stored routines in the database are also dropped.
  • 12. 12 Stored Procedure Creating Stored Procedures: CREATE PROCEDURE proc_name ([parameters]) [characteristics] routine_body CREATE PROCEDURE rect_area (width INT, height INT) SELECT width * height AS area; Stored Procedure with Compound Statements (Begins and ends with the BEGIN and END keywords and creates a block). mysql> delimiter // mysql> CREATE PROCEDURE world_record_count () -> BEGIN -> SELECT ‘Country’, COUNT(*) FROM Country; -> SELECT ‘City’, COUNT(*) FROM City; -> SELECT ‘CountryLanguage’, COUNT(*) FROM CountryLanguage; -> END; -> // Query OK, 0 rows affected (0.00 sec) mysql> delimiter ; Declaring Parameters: IN indicates an input parameter. The parameter value is passed in from the caller to the procedure OUT indicates an output parameter. The procedure sets its value, and after the proce- dure terminates. The caller sees that value when it accesses the variable. INOUT indicates a “two-way” parameter that can be used both for input and for output. If no keyword is given before a procedure parameter name, it is an IN parameter by default.
  • 13. 13 Stored Procedure Stored Procedure with Declared Parameters CREATE PROCEDURE param_test (IN p_in INT, OUT p_out INT, INOUT p_inout INT) BEGIN SELECT p_in, p_out, p_inout; SET p_in = 100, p_out = 200, p_inout = 300; END; SET @v_in = 0, @v_out = 0, @v_inout = 0; Calling(Invoking) Stored Procedure CALL param_test(@v_in, @v_out, @v_inout); The DECLARE Statement in Stored Procedure: Local variables Conditions, such as warnings or exceptions Handlers for conditions Cursors for accessing result sets row by row Variables in Stored Procedure: DECLARE var_name [, var_name] ... data_type [DEFAULT value] Assigning Variable Values with SET: DECLARE var1, var2, var3 INT; SET var1 = 1, var2 = 2; SET var3 = var1 + var2; Variables in Stored Procedure: DECLARE name_var CHAR(52); DECLARE pop_var INT; SELECT Name, Population INTO name_var, pop_var FROM Country WHERE Code = ‘ESP’;
  • 14. 14 Function Creating Function: CREATE FUNCTION func_name ([parameters]) RETURNS data_type [characteristics] routine_body CREATE FUNCTION circle_area (radius FLOAT) RETURNS FLOAT RETURN PI() * radius * radius; Calling(Invoking) Function SELECT circle_area(10); Functions can have Compound Statements, Declared Parameters & Variables as Store Procedure has.
  • 15. 15 Difference Between Stored Procedure and Function  Function is not pre-compiled object it will execute every time whenever it was called.  Function must return a value but in Stored Procedure it is optional (Procedure can return zero or n values).  Functions can have only input parameters for it whereas Procedures can have input/output parameters .  Function takes one input parameter it is mandatory but Stored Procedure may take o to n input parameters.  Functions can be called from Procedure whereas Procedures cannot be called from Function.  Procedure allows SELECT as well as DML(INSERT/UPDATE/DELETE) statement in it whereas Function allows only SELECT statement in it.  Procedures can not be utilized in a SELECT statement whereas Function can be embedded in a SELECT statement.  Stored Procedures cannot be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section whereas Function can be.  Exception can be handled by try-catch block in a Procedure whereas try-catch block cannot be used in a Function.  We can go for Transaction Management in Procedure whereas we can't go in Function. http://tutoriz.com/Thread-Difference-between-Stored-Procedure-and-Function-in-Sql-with-Example