UE20CS301 Unit3 Slides
UE20CS301 Unit3 Slides
SYSTEM
Dr.Vinodha & Dr.Geetha
Department of Computer Science and Engineering
9/1/2021 1
DATABASE MANAGEMENT SYSTEM
Basics of SQL
■ SQL language
■ Considered one of the major reasons for the commercial success of relational
databases
■ SQL
■ SQL Actually comes from the word “SEQUEL” which was the original term used in the paper:
“SEQUEL TO SQUARE” by Chamberlin and Boyce. IBM could not copyright that term, so they
abbreviated to SQL and copyrighted the term SQL.
■ Now popularly known as “Structured Query language”.
■ SQL is a practical rendering of the relational data model with syntax
Database Management Systems
SQL Data Definition, Data Types, Standards
■ Terminology:
■ Table, row, and column used for relational model terms relation,
■ SQL schema
■ Identified by a schema name
■ Catalog
■ Named collection of schemas in an SQL environment
Data Definition Language (DDL) statements are used to define the database structure or schema.
Data Manipulation Language (DML) statements are used for managing data within schema objects
DCL is the abstract of Data Control Language. Data Control Language includes commands such as
GRANT, and is concerned with rights, permissions, and other controls of the database system.
Transaction Control Language (TCL) is used to run the changes made by the DML statement.
Database Management Systems
Types of Database Languages: DDL
DDL includes commands such as CREATE, ALTER, and DROP statements. DDL is used to
CREATE, ALTER, OR DROP the database objects (Table, Views, Users).
CREATE TABLE
Syntax:
CREATE TABLE table_name(
Col_name1 datatype(),
Col_name2 datatype(),…
Col_namen datatype(),
);
Example:
1) ADD
3) RENAME
Syntax: Syntax:
2) MODIFY 4) DROP
Syntax: Syntax:
C) DESCRIBE TABLE
Syntax:
DESCRIBE TABLE NAME;
D) DROP TABLE
Syntax:
DROP Table name; // Complete table structure will be dropped
E) RENAME
Rename a table
Syntax:
RENAME table table_name to new table_name
F) TRUNCATE
Syntax:
TRUNCATE TABLE table_name; // delete complete data from an existing table. Table Structure remains
Database Management Systems
Types of Database Languages: DML
Data Manipulation Language (DML) statements are used for managing data within schema objects
DML deals with data manipulation, and therefore includes most common SQL statements such as
SELECT, INSERT, etc. DML allows adding / modifying / deleting data itself.
DML Commands
1.INSERT
2.SELECT
3.UPDATE
4.DELETE
Database Management Systems
Types of Database Languages: DML
1) INSERT
Syntax-1:
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN) VALUES (value1, value2, value3,...valueN);
Syntax-2
Syntax:
SELECT * FROM <table_name>;
3) UPDATE
Syntax:
UPDATE table_name SET column1 = value1, column2 = value2...., columnN = valueN WHERE [condition];
4) DELETE
Syntax:
DELETE FROM table_name WHERE [condition];
Database Management Systems
Types of Database Languages: DCL & TCL
Data Control Language includes commands such as GRANT, and is concerned with rights,
permissions, and other controls of the database system.
1) GRANT
2) Revoke :
Revoke command withdraw user privileges on database objects if any granted.
Syntax:
REVOKE privilege_name on object_name from {user_name | public | role_name}
Database Management Systems
Types of Database Languages: DCL & TCL
TCL is used to run the changes made by the DML statement. TCL can be grouped into a logical transaction.
TCL Commands:
Commit
COMMIT is the SQL command that is used for storing changes performed by a transaction. When a COMMIT command is
issued it saves all the changes since last COMMIT or ROLLBACK.
Syntax for SQL Commit
COMMIT;
RollBack
ROLLBACK is the SQL command that is used for reverting changes performed by a transaction.
When a ROLLBACK command is issued it reverts all the changes since last COMMIT or ROLLBACK.
Syntax for SQL Rollback
ROLLBACK;
SAVEPOINT
A SAVEPOINT is a point in a transaction when you can roll the transaction back to a certain point without
rolling back the entire transaction.
Syntax:
SAVEPOINT SAVEPOINT_NAME;
Database Management Systems
Attribute Data Types in SQL
VARYING(n)
Database Management Systems
Attribute Data Types in SQL
formats
Database Management Systems
Attribute Data Types in SQL
Large-Object Types
Many cu rrent-generation d atabase applications need to store attribu tes that can
be large (of the ord er of m any kilobytes), su ch as a photograp h, or very large
(of the ord er of m any m egabytes or even gigabytes), such as a high-resolu tion
m ed ical im age or vid eo clip .
SQL therefore provid es large-object d ata types for character d ata (clob) and binary
d ata (blob). The letters “lob” in these d ata types stand for “Large OBject.”
Database Management Systems
Attribute Data Types in SQL
Large-Object Types
.
Database Management Systems
Attribute Data Types in SQL
Advanced Data Types like CLOB, BLOB
LOBs in the database are stored in a way that optimizes the space and provides efficient
access within the database tablespaces.
Internal LOBs (BLOBs, CLOBs) also provide transactional support (Commit, Rollback, and
so on) of the database server.
• BLOBs (Binary LOBs) used to store unstructured binary (also called “raw”) data,
such as video clips.
• CLOBs (Character LOBs) used to store large blocks of character data from the
database character set.
Binary Large Object Stores any kind of data in binary format such as images,
(BLOB) audio, and video.
Stores string data in the database having character set
Character Large Object
format. Used for large set of characters/strings or
(CLOB)
documents that use the database character.
Database Management Systems
Attribute Data Types in SQL
Advanced Data Types like CLOB, BLOB
Blob and Clob together are known as LOB(Large Object Type). The following are the major differences
between Blob and Clob data types.
Blob Clob
The full form of Blob is a Binary Large Object. The full form of Clob is Character Large Object.
This is used to store large binary data. This is used to store large textual data.
This stores values in the form of binary streams. This stores values in the form of character streams.
Using this you can stores files like videos, images, Using this you can store files like text files, PDF
gifs, and audio files. documents, word documents etc.
•MySQL supports this with the following •MySQL supports this with the following
datatypes:TINYBLOB datatypes:TINYTEXT
•BLOB •TEXT
•MEDIUMBLOB •MEDIUMTEXT
•LONGBLOB •LONGTEXT
Database Management Systems
Attribute Data Types in SQL
Advanced Data Types like CLOB, BLOB
Blob and Clob together are known as LOB(Large Object Type). The following are the major differences
between Blob and Clob data types.
■ Makes it easier to change the data type for a domain that is used by
numerous attributes
■ Improves schema readability
■ Example:
■ TYPE
■ User Defined Types (UDTs) are supported for object-oriented
1.Union
2.UnionAll
3.Intersect
4.Minus
5.Except
Database Management Systems
SET Operators in SQL
1. Union
The SQL Union operation is used to combine the result of two or more SQL SELECT queries.
In the union operation, all the number of datatype and columns must be same in both the tables on which
UNION operation is being applied.
The union operation eliminates the duplicate rows from its resultset.
Syntax
SELECT column_name FROM table1
UNION
SELECT column_name FROM table2;
2. Union All
Union All operation is equal to the Union operation. It returns the set without removing duplication and sorting
the data.
Syntax:
SELECT column_name FROM table1
UNION ALL
SELECT column_name FROM table2;
Database Management Systems
SET Operators in SQL
3. Intersect
It is used to combine two SELECT statements. The Intersect operation returns the common
rows from both the SELECT statements.
In the Intersect operation, the number of datatype and columns must be the same.
It has no duplicates and it arranges the data in ascending order by default.
Syntax
SELECT column_name FROM table1
INTERSECT
SELECT column_name FROM table2;
4. Minus
It combines the result of two SELECT statements. Minus operator is used to display the rows
which are present in the first query but absent in the second query.
It has no duplicates and data arranged in ascending order by default.
Syntax:
SELECT column_name FROM table1
MINUS
SELECT column_name FROM table2;
Database Management Systems
SET Operators in SQL
5) EXCEPT
Syntax
The basic syntax of EXCEPT is as follows.
SELECT column1 [, column2 ] FROM table1 [, table2 ]
[WHERE condition]
EXCEPT
SELECT column1 [, column2 ] FROM table1 [, table2 ]
[WHERE condition]
Here, the given condition could be any given expression based on user requirement.
Database Management Systems
Summary
■ Introduction to SQL Commands
■ SQL Data Definition, Data Types, Standards
■ Schema Concepts in SQL
■ The CREATE TABLE Command in SQL
■ Attribute Data Types in SQL
■ Advanced Data Types like CLOB, BLOB
THANK YOU
1
DATABASE MANAGEMENT SYSTEM
T1:6.2 -6.4,7.4
Basic constraints:
Relational Model has 3 basic constraint types that are supported in SQL:
21);
Database Management Systems
Specifying Constraints in SQL
UNIQUE clause
Specifies alternate (secondary) keys (called CANDIDATE
keys in the relational model).
Dname VARCHAR(15) UNIQUE;
Database Management Systems
Specifying Constraints in SQL
database is operational
Does not require recompilation of the database schema
Database Management Systems
The DROP Command
DROP command
Used to drop named schema elements, such as tables, domains, or
constraint
Drop behavior options:
CASCADE and RESTRICT
Example:
DROP SCHEMA COMPANY CASCADE;
This removes the schema and all its elements including tables,views,
constraints, etc.
Database Management Systems
The DROP Command
SQL> create table gender_tab (
2 gender_id char(1),
3 gender_nm varchar2(6),
4 constraint gender_pk primary key (gender_id),
5 constraint gender_id_ck check (gender_id in ('M',
'F'))
6 );
Table created.
SQL>
SQL> insert into gender_tab values ('F', 'Female');
1 row created.
SQL> insert into gender_tab values ('M', 'Male');
1 row created.
SQL>
Database Management Systems
The DROP Command
SQL> create table people (
first_name varchar2(20),
last_name varchar2(25),
gender char(1)
);
Table created.
SQL>
SQL> alter table people
add constraint people_gender_fk
foreign key (gender)
references gender_tab;
Table altered.
Database Management Systems
The DROP Command
SQL> insert into people values ('S', 'Dillon', 'M');
1 row created.
SQL> insert into people values ('C', 'Beck', 'M');
1 row created.
SQL> insert into people values ('N', 'Ellis', 'F');
1 row created.
SQL>
SQL> drop table gender_tab;
drop table gender_tab
*
ERROR at line 1:
ORA-02449: unique/primary keys in table referenced by foreign keys
SQL>
SQL> drop table gender_tab cascade constraints;
Table dropped.
Database Management Systems
MySql Commands
To create a new database in MySQL use the CREATE DATABASE statement with the
below syntax:
CREATE DATABASE [IF NOT EXISTS] database_name
Example:
ALTER TABLE people ADD COLUMN Job
VARCHAR(12);
Database Management Systems
The ALTER table command
To drop a column
Choose either CASCADE or RESTRICT
CASCADE would drop the column from views etc. RESTRICT is
possible if no views refer to it.
ALTER TABLE EMPLOYEE DROP COLUMN Address CASCADE;
Default values can be dropped and altered :
ALTER TABLE DEPARTMENT ALTER COLUMN Mgr_ssn DROP DEFAULT;
ALTER TABLE DEPARTMENT ALTER COLUMN Mgr_ssn SET DEFAULT ‘333445555’;
Database Management Systems
Basic Retrieval Queries in SQL
SELECT statement
One basic statement for retrieving information from a database
SQL allows a table to have two or more tuples that are identical in all
their attribute values
Relational model is strictly set-theory based
Projection attributes
Attributes whose values are to be retrieved
Selection condition
Boolean condition that must be true for any retrieved tuple.
Query 8. For each employee, retrieve the employee’s first and last name and the first and
last name of his or her immediate supervisor.
SELECT E.Fname, E.Lname, S.Fname, S.Lname
FROM EMPLOYEE AS E, EMPLOYEE AS S
WHERE E.Super_ssn=S.Ssn;
Recommended practice to abbreviate names and to prefix
same or similar attribute from multiple tables.
Database Management Systems
Aliasing, Renaming and Tuple Variables
(contd.)
The attribute names can also be renamed
EMPLOYEE AS E(Fn, Mi, Ln, Ssn, Bd, Addr, Sex, Sal, Sssn,
Dno)
Note that the relation EMPLOYEE now has a variable name E which
corresponds to a tuple variable
The “AS” may be dropped in most SQL implementations
Database Management Systems
Unspecified WHERE Clause and Use of the Asterisk
Set operations
UNION, EXCEPT (difference), INTERSECT
Corresponding multiset operations: UNION ALL,
EXCEPT ALL, INTERSECT ALL)
Type compatibility is needed for these operations to
be valid
Database Management Systems
Substring Pattern Matching and Arithmetic Operators
Query 13. Show the resulting salaries if every employee working on the ‘ProductX’ project
is given a 10 percent raise.
Specify the relation name and a list of values for the tuple. All
values including nulls are supplied.
Tuples are deleted from only one table at a time (unless CASCADE is
SQL
A Comprehensive language for Schema Modification for the
relational database management DBAs using ALTER TABLE ,
Data definition, queries, updates, ADD and DROP COLUMN,
constraint specification, and view ALTER CONSTRAINT etc.
definition
Covered :
Data definition commands for creating
tables
Commands for constraint specification
Simple retrieval queries
Database update commands
THANK YOU
1
DATABASE MANAGEMENT SYSTEM
Slides adapted from Author Slides of Fundamentals of Database Systems”, Ramez Elamsri,
Shamkant B Navathe, Pearson, 7th Edition, 2017.
2
DATABASE MANAGEMENT SYSTEM
Unit 3 : Advanced SQL Queries, Nested Queries
T1:7.1.1,7.1.2
■ Meanings of NULL
■ Unknown value
■ Unavailable or withheld value
■ Not applicable attribute
■ Each individual NULL value considered to be different from
every other NULL value
■ SQL uses a three-valued logic:
■ TRUE, FALSE, and UNKNOWN (like Maybe)
■ NULL = NULL comparison is avoided
Database Management Systems
Comparisons Involving NULL and Three-Valued Logic (cont’d.)
Database Management Systems
Comparisons Involving NULL and Three-Valued Logic (cont’d.)
■ Nested queries
■ complete select-from-where blocks within another SQL query.
■ That other query is called the outer query.
■ These nested queries can also appear in the WHERE clause or the
FROM clause or the SELECT clause or other SQL clauses as needed.
■ Comparison operator IN
■ Compares value v with a set (or multiset) of values V
■ Evaluates to TRUE if v is one of the elements in V
Database Management Systems
Nested Queries (cont’d.)
Database Management Systems
Nested Queries (cont’d.)
1
DATABASE MANAGEMENT SYSTEM
2
DATABASE MANAGEMENT SYSTEM
Unit 3 : Advanced SQL Queries, Nested Queries
T1 :7.1.3 -7.1.5
Sub- queries, Correlated sub-queries
Database Management Systems
Correlated Nested Queries
■ Correlated nested query
■ Queries that are nested using the = or IN comparison operator can be collapsed
into one single block.
■ E.g., For each employee tuple, evaluate the nested query, which retrieves the Essn values for all DEPENDENT
tuples with the same sex and name as that EMPLOYEE tuple; if the Ssn value of the
■ EMPLOYEE tuple is in the result of the nested query, then select that EMPLOYEE tuple.
Q16A: SELECT E.Fname, E.Lname
FROM EMPLOYEE AS E, DEPENDENT AS D
WHERE E.Ssn=D.Essn AND E.Sex=D.Sex
AND E.Fname=D.Dependent_name;
Database Management Systems
The EXISTS and UNIQUE Functions in SQL for correlating queries
■ EXISTS function
■ EXISTS and UNIQUE are Boolean functions that return TRUE or FALSE;
hence, they can be used in a WHERE clause condition
■ The result of EXISTS is a Boolean value TRUE if the nested query result
contains at least one tuple, or FALSE if the nested query result contains no
tuples
Database Management Systems
The EXISTS and UNIQUE Functions in SQL for correlating queries
The above is equivalent to double negation: List names of those employees for whom there does NOT exist a project managed by
department no. 5 that they do NOT work on.
Database Management Systems
Double Negation to accomplish “for all” in SQL
In Q3B, the outer nested query selects any WORKS_ON (B) tuples whose Pno is of a project controlled by department 5, if
there is not a WORKS_ON (C) tuple with the same Pno and the same Ssn as that of the EMPLOYEE tuple under consideration
in the outer query. If no such tuple exists, we select the EMPLOYEE tuple.
Database Management Systems
Explicit Sets and Renaming of Attributes in SQL
■ Can use explicit set of values in WHERE clause
Q17: SELECT DISTINCT Essn
FROM WORKS_ON
WHERE Pno IN (1, 2, 3);
1
DATABASE MANAGEMENT SYSTEM
Outer join, Aggregation function and group, having clause
T1:7.1.6 - 7.1.8
Outer join, Aggregation function and group, having clause
DATABASE MANAGEMENT SYSTEM
Unit 3 : Outer join, Aggregation function and group, having clause
■ Joined table
■ Permits users to specify a table resulting from a join operation in the
FROM clause of a query
■ The FROM clause in Q1A
■ Contains a single joined table. JOIN may also be called INNER JOIN
Database Management Systems
Different Types of JOINed Tables in SQL
ALTERNATE SYNTAX:
■ FULL OUTER JOIN – combines result of LEFT and RIGHT OUTER JOIN
■ Can nest JOIN specifications for a multiway join:
Q19: SELECT SUM (Salary), MAX (Salary), MIN (Salary), AVG (Salary)
FROM EMPLOYEE;
■ The result can be presented with new names:
■ If the grouping attribute has NULL as a possible value, then a separate group is
created for the null value (e.g., null Dno in the above query)
■ GROUP BY may be applied to the result of a JOIN:
■ Query 25. For each project, retrieve the project number, the project name,
and
the number of employees who work on that project.
■ HAVING clause
■ Provides a condition to select or reject an entire group:
■ Query 26. For each project on which more than two employees work, retrieve the
project number, the project name, and the number of employees who work on the
project.
■ Consider the query: we want to count the total number of employees whose
salaries exceed $40,000 in each department, but only for departments where more
than five employees work.
■ INCORRECT QUERY:
SELECT Dno, COUNT (*)
FROM EMPLOYEE
WHERE Salary>40000
GROUP BY Dno
HAVING COUNT (*) > 5;
Database Management Systems
Combining the WHERE and the HAVING Clause (continued)
of tuples
THANK YOU
1
DATABASE MANAGEMENT SYSTEM
Slides adapted from Author Slides of Fundamentals of Database Systems”, Ramez Elamsri,
Shamkant B Navathe, Pearson, 7th Edition, 2017.
T1:7.1.9,7.1.10
The WITH clause allows a user to define a table that will only
be used in a particular query (not available in all SQL
implementations)
Used for convenience to create a temporary “View” and use
that immediately in a query
Allows a more straightforward way of looking a step-by-step
query
Database Management Systems
Example of WITH
The above query starts with an empty SUP_EMP and successively builds
SUP_EMP table by computing immediate supervisees first, then second
level supervisees, etc. until a fixed point is reached and no more
supervisees can be added
THANK YOU
1
DATABASE MANAGEMENT SYSTEM
R1 : CHAPTER 5.6
OLAP Implementation
• The earliest OLAP systems used multidimensional arrays in memory to store data
cubes, and are referred to as multidimensional OLAP (MOLAP) systems.
• Hybrid systems, which store some summaries in memory and store the base
data and other summaries in a relational database, are called hybrid OLAP
(HOLAP) systems.
DATABASE MANAGEMENT SYSTEM
CUBE, PIVOT, ROLLUP OLAP Implementation (Cont.)
The data in a data cube cannot be generated by a single SQL query, using
the basic group by constructs, since aggregates are computed for several
different groupings of the dimension attributes.
For this reason, SQL includes functions to form the grouping needed for
OLAP.
SQL supports generalizations of the group by construct to perform the cube
and rollup operations. The cube and rollup constructs in the group by
clause
allow multiple group by queries to be run in a single query with the result
returned as a single relation
DATABASE MANAGEMENT SYSTEM
CUBE, PIVOT, ROLLUP OLAP Implementation (Cont.)
Query result
DATABASE MANAGEMENT SYSTEM
CUBE, PIVOT, ROLLUP OLAP Implementation (Cont.)
• Relational representation of cross-tab that we saw earlier, but with null in place of
all, can be computed by
select item-name, color, sum(number)
from sales
group by cube(item-name, color)
• The function grouping() can be applied on an attribute
• Returns 1 if the value is a null value representing all, and returns 0 in all other cases.
select item-name, color, size, sum(number),
grouping(item-name) as item-name-flag,
grouping(color) as color-flag,
grouping(size) as size-flag,
from sales
group by cube(item-name, color, size)
• Can use the function decode() in the select clause to replace
such nulls by a value such as all
• E.g. replace item-name in first query by
decode( grouping(item-name), 1, ‘all’, item-name)
DATABASE MANAGEMENT SYSTEM
CUBE, PIVOT, ROLLUP: Extended Aggregation (Cont.)
• The rollup construct generates union on every prefix of specified list of attributes
• E.g.
select item-name, color, size, sum(number)
from sales
group by rollup(item-name, color, size)
Generates union of four groupings:
{ (item-name, color, size), (item-name, color), (item-name), ( ) }
• Rollup can be used to generate aggregates at multiple levels of a
hierarchy.
• E.g., suppose table itemcategory(item-name, category) gives the category of each
item. Then
select category, item-name, sum(number)
from sales, itemcategory
where sales.item-name = itemcategory.item-name
group by rollup(category, item-name)
would give a hierarchical summary by item-name and by category.
DATABASE MANAGEMENT SYSTEM
CUBE, PIVOT, ROLLUP Extended Aggregation (Cont.)
• Multiple rollups and cubes can be used in a single group by clause
• Each generates set of group by lists, cross product of sets gives overall set of
group by lists
• E.g.,
select item-name, color, size, sum(number)
from sales
group by rollup(item-name), rollup(color, size)
generates the groupings
{item-name, ()} X {(color, size), (color), ()}
= { (item-name, color, size), (item-name, color), (item-name),
(color, size), (color), ( ) }
THANK YOU
1
DATABASE MANAGEMENT SYSTEM
2
DATABASE MANAGEMENT SYSTEM
Unit 3 : Specifying Constraints as Assertions and Actions as Triggers
T1 : CHAPTER 7.2
■ Semantic Constraints: The following are beyond the scope of the EER
and relational model
■ CREATE ASSERTION
■ Specify additional types of constraints outside scope of built-in
relational model constraints
■ CREATE TRIGGER
■ Specify automatic actions that database system will perform when
certain events and conditions occur
Database Management Systems
Specifying General Constraints as Assertions in SQL
■ CREATE ASSERTION
■ Specify a query that selects any tuples that violate the desired
condition
■ Use only in cases where it goes beyond a simple CHECK which
applies to individual attributes and domains
Database Management Systems
Introduction to Triggers in SQL
■ CREATE TRIGGER statement
■ Used to monitor the database
■ Typical trigger has three components which make it a rule for an
“active database “
Event(s)
Condition
Action
Database Management Systems
USE OF TRIGGERS
■ AN EXAMPLE with standard Syntax.(Note : other SQL
implementations like PostgreSQL use a different syntax.)
R5:
CREATE TRIGGER SALARY_VIOLATION
BEFORE INSERT OR UPDATE OF Salary, Supervisor_ssn ON EMPLOYEE
1
DATABASE MANAGEMENT SYSTEM
T1 : CHAPTER 7.3
■ Once a View is defined, SQL queries can use the View relation in
the FROM clause
■ View is always up-to-date
■ Responsibility of the DBMS and not the user
■ DROP VIEW command
■ Dispose of a view
Database Management Systems
View Implementation, View Update, and Inline Views
■ The problem of efficiently implementing a view for querying is complex. Two main
approaches are suggested :
■ Strategy1: Query modification approach
■ This approach involves modifying the view query into query on underlying base
tables.
■ Disadvantage: inefficient for views defined via complex queries that are time-
consuming to execute
Strategy1: Query modification approach
Database Management Systems
View Materialization
1
DATABASE MANAGEMENT SYSTEM
Programming Techniques
Slides adapted from Author Slides of Fundamentals of Database Systems”, Ramez Elamsri,
Shamkant B Navathe, Pearson, 7th Edition, 2017.
2
DATABASE MANAGEMENT SYSTEM
Unit 3 : Database Programming - functions,
In MYSQL we use the CREATE FUNCTION statement to create a new function that will be stored and this function can be further
called by supplying any number of parameters and returning the required value.
Syntax:
The following is the syntax of CREATE FUNCTION statement –
• DELIMITER $$
CREATE FUNCTION name_of_function(
parameter1,
parameter2,…
)
RETURNS datatype
[NOT] DETERMINISTIC
BEGIN
-- code of statements to be executed
END $$
DELIMITER ;
4
DATABASE MANAGEMENT SYSTEM
Database Programming - functions
• name_of_ function – It is the name of the function that needs to be created in MySQL.
• parameter1, parameter2,… – We can pass the optional parameters to the functions that need to be declared
while creating it in the () brackets. A function can contain none, one or more than one parameter. These
parameters can belong to either of the three types –
• IN – These types of parameters are assigned the values while calling the function and the value cannot be
modified or overwritten inside the function but only referenced and used by the function.
• OUT – These are the parameters that can be assigned the values and overridden in the function but cannot be
referenced by it.
• IN OUT – These types of parameters are assigned the values while calling the function and the value can be
modified or overwritten inside the function as well as referenced and used by the function.
• BEGIN and END – BEGIN keyword marks the beginning of the function while END marks the completion of
function in MYSQL.
5
DATABASE MANAGEMENT SYSTEM
Database Programming - functions
• RETURN Datatype – We can return any type of value from the execution of the function. The type of value
that will be returned needs to be specified after the RETURN clause. Once, MySQL finds the RETURN statement
while execution of the function, execution of the function is terminated and the value is returned.
• DETERMINISTIC – The function can be either deterministic or non-deterministic which needs to be specified
here. When the function returns the same value for the same values of parameter then it is called
deterministic. However, if the function returns a different value for the same values of functions then we can
call that function to be nondeterministic. When none of the types of function is mentioned, then MySQL will
consider function to be NON-DETERMINISTIC by default.
6
;
• DELIMITER $$
CREATE FUNCTION isEligible(
age INTEGER
)
RETURNS VARCHAR(20)
DETERMINISTIC
BEGIN
IF age > 18 THEN
RETURN ("yes");
ELSE
RETURN ("No");
END IF;
END$$
DELIMITER
7
DATABASE MANAGEMENT SYSTEM
Database Programming - functions
To check the eligibility for a 20-year-old guy call the function in the following way –
8
DATABASE MANAGEMENT SYSTEM
Database Programming - functions
Example that involves returning the number of months between the current date and the supplied date
DELIMITER $$
CREATE FUNCTION getMonths(sampledate date) RETURNS int DETERMINISTIC
BEGIN
DECLARE currentDate DATE;
Select current_date()into currentDate;
RETURN (12 * (YEAR(currentDate)
- YEAR(sampledate))
+ (MONTH(currentDate)
- MONTH(sampledate)));
END
$$
DELIMITER ;
9
DATABASE MANAGEMENT SYSTEM
Database Programming - functions
10
DATABASE MANAGEMENT SYSTEM
Database Programming - functions
To retrieve the name of the developer and total months that he/she has worked in the company
the following query statement is used in which a call to getMonths() function is invoked as follows–
11
THANK YOU
1
DATABASE MANAGEMENT SYSTEM
Programming Techniques
Slides adapted from Author Slides of Fundamentals of Database Systems”, Ramez Elamsri,
Shamkant B Navathe, Pearson, 7th Edition, 2017.
A procedure (often called a stored procedure) is a collection of pre-compiled SQL statements stored inside the
database. It is a subroutine or a subprogram in the regular computing language. A procedure always contains a
name, parameter lists, and SQL statements. We can invoke the procedures by using triggers, other procedures and
applications such as Java , Python , PHP , etc. The following syntax is used for creating a stored procedure in
MySQL.
DELIMITER &&
CREATE PROCEDURE procedure_name [[IN | OUT | INOUT] parameter_name datatype [, parameter datatype]) ]
BEGIN
Declaration_section
Executable_section
END &&
4
DELIMITER ;
DATABASE MANAGEMENT SYSTEM
IN parameter
It is the default mode. It takes a parameter as input, such as an attribute. When we define it, the calling program has to pass an
argument to the stored procedure. This parameter's value is always protected.
OUT parameters
It is used to pass a parameter as output. Its value can be changed inside the stored procedure, and the changed (new) value is
passed back to the calling program. It is noted that a procedure cannot access the OUT parameter's initial value when it starts.
INOUT parameters
It is a combination of IN and OUT parameters. It means the calling program can pass the argument, and the procedure can
modify the INOUT parameter, and then passes the new value back to the calling program.
6
DATABASE MANAGEMENT SYSTEM
8
DATABASE MANAGEMENT SYSTEM
DELIMITER &&
CREATE PROCEDURE get_student (IN var1 INT)
BEGIN
SELECT * FROM student_info LIMIT var1;
SELECT COUNT(stud_code) AS Total_Student FROM student_info;
END &&
DELIMITER ;
9
DATABASE MANAGEMENT SYSTEM
DELIMITER &&
CREATE PROCEDURE display_max_mark (OUT highestmark INT)
BEGIN
SELECT MAX(marks) INTO highestmark FROM student_info;
END &&
DELIMITER ;
10
DATABASE MANAGEMENT SYSTEM
DELIMITER &&
CREATE PROCEDURE display_marks (INOUT var1 INT)
BEGIN
SELECT marks INTO var1 FROM student_info WHERE stud_id = var1;
END &&
DELIMITER ;
11
DATABASE MANAGEMENT SYSTEM
We can verify it by listing the procedure in the specified database using the SHOW PROCEDURE STATUS
command.
SHOW PROCEDURE STATUS [LIKE 'pattern' | WHERE search_condition]
Ex: mysql> SHOW PROCEDURE STATUS WHERE db = 'mystudentdb';
12
DATABASE MANAGEMENT SYSTEM
STORED PROCEDURE Vs FUNCTION
13
THANK YOU
9/1/2021 1
DATABASE MANAGEMENT SYSTEM
Programming Techniques
Slides adapted from Author Slides of Fundamentals of Database Systems”, Ramez Elamsri,
Shamkant B Navathe, Pearson, 7th Edition, 2017.
A database cursor is a mechanism that enables traversal over the records in a database. Cursors
facilitate subsequent processing in conjunction with the traversal, such as retrieval, addition and
removal of database records.
A cursor in SQL is a temporary work area created in system memory when a SQL statement is
executed. A SQL cursor is a set of rows together with a pointer that identifies a current row. It is a
database object to retrieve data from a result set one row at a time. It is useful when we want to
manipulate the record of a table in a singleton method, in other words, one row at a time. In other
words, a cursor can hold more than one row but can process only one row at a time. The set of rows
the cursor holds is called the active set.
4
DATABASE MANAGEMENT SYSTEM
Cursors in MySQL
1. Implicit Cursors
Auto-created by Oracle when SQL is executed if there is no explicit cursor used.
Users or programmers cannot control the information or programs in it
Associated with INSERT, UPDATE and DELETE types of DML operation statements
Attributes: SQL%FOUND, SQL%NOTFOUND, %ISOPEN, %ROWCOUNT
2. Explicit Cursors
User-defined cursors which help to gain more control over the context part.
It is defined in the declaration area of the SQL block.
Created on SELECT statements that returns multiple records.
Attributes: SQL%FOUND, SQL%NOTFOUND, %ISOPEN, %ROWCOUNT.
5
DATABASE MANAGEMENT SYSTEM
Cursors
Properties:
•READ ONLY − Using these cursors you cannot update any table.
•Non-Scrollable − Using these cursors you can retrieve records from a table in one
direction i.e., from top to bottom.
•Asensitive − These cursors are insensitive to the changes that are made in the table i.e.
the modifications done in the table are not reflected in the cursor, i.e. if we have created a
cursor holding all the records in a table and, meanwhile if we add some more records to
the table, these recent changes will not be reflected in the cursor we previously obtained.
6
DATABASE MANAGEMENT SYSTEM
Cursors
7
DATABASE MANAGEMENT SYSTEM
Cursors
8
DATABASE MANAGEMENT SYSTEM
Cursors
Syntax
DECLARE cursor_name CURSOR FOR select_statement
OPEN cursor_name
FETCH [[NEXT] FROM] cursor_name INTO var_name [, var_name] ...
CLOSE cursor_name
9
DATABASE MANAGEMENT SYSTEM
Cursors
When the FETCH statement is called, the next row is read in the result set each time.
But a time comes when it reaches to the end of the set and no data is found there, so to
handle this condition with MYSQL cursor we need to use a NOT FOUND handler.
Syntax:
DECLARE CONTINUE HANDLER FOR NOT FOUND SET variable_name = 1;
Attribute Description
It will return TRUE in case an INSERT, UPDATE, or DELETE statement affects one or
%FOUND more rows or a SELECT INTO statement returns one or more rows. In other cases, it will
return FALSE.
It is technically the opposite of %FOUND attribute. It returns TRUE in case an INSERT,
%NOTFOUND UPDATE, or DELETE statement doesn’t affect any rows or a SELECT INTO statement
returns no rows. Else it returns just FALSE.
This attribute will always return FALSE for implicit cursors as the SQL cursor is
%ISOPEN
automatically closed immediately after the associated SQL statement is executed.
It returns the total number of affected rows by an INSERT, UPDATE, or DELETE
%ROWCOUNT
statement, or the rows returned by a SELECT INTO statement.
10
DATABASE MANAGEMENT SYSTEM
Cursors
Example: Consider the following Tutorials table
11
DATABASE MANAGEMENT SYSTEM
Cursors
Write procedure that backups the contents of the tutorials table to the
backup table using cursors −
12
DATABASE MANAGEMENT SYSTEM
Cursors
DELIMITER //
CREATE PROCEDURE ExampleProc()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE tutorialID INTEGER;
DECLARE tutorialTitle, tutorialAuthor, tutorialDate VARCHAR(20);
DECLARE cur CURSOR FOR SELECT * FROM tutorials;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur;
label: LOOP
FETCH cur INTO tutorialID, tutorialTitle, tutorialAuthor, tutorialDate;
INSERT INTO backup VALUES(tutorialID, tutorialTitle, tutorialAuthor, tutorialDate);
IF done = 1 THEN LEAVE label;
END IF;
END LOOP;
CLOSE cur;
END//
13
DELIMITER ;
DATABASE MANAGEMENT SYSTEM
Cursors
call the above procedure as shown below −
14
DATABASE MANAGEMENT SYSTEM
Cursors
Consider the following table of employees. Using the stored procedure and cursors concatenate name and salary of the employees
15
THANK YOU
Dr.Vinodha K & Dr.Geetha
Department of Computer Science and Engineering
DATABASE MANAGEMENT
SYSTEM
Dr.Geetha & Dr.Vinodha K
Department of Computer Science and Engineering
1
DATABASE MANAGEMENT SYSTEM
Programming Techniques
Slides adapted from Author Slides of Fundamentals of Database Systems”, Ramez Elamsri,
Shamkant B Navathe, Pearson, 7th Edition, 2017.
5
DATABASE MANAGEMENT SYSTEM
6
DATABASE MANAGEMENT SYSTEM
Python with MySQL Database Connection
Example to connect to MySQL Database in Python
import mysql.connector
from mysql.connector import Error
try:
conn = mysql.connector.connect(host='localhost’,
database='Electronics',
user=‘root',
password='')
if conn.is_connected():
cursor=conn.cursor()
cursor.execute("drop table if exists empdetails");
cursor.execute("create table empdetails(empno int,empname varchar(20))")
print"**Table created**"
cursor.execute("insert into empdetails values(1,'Reena')")
cursor.execute("insert into empdetails values(2,'Reetta')")
7
cursor.execute("insert into empdetails values(3,'Rekha')")
DATABASE MANAGEMENT SYSTEM
Python with MySQL Database Connection