0% found this document useful (0 votes)
17 views45 pages

DBMS M2 Final

This document provides an overview of SQL, including its basic structure, data types, and various commands for database operations such as creating, updating, and deleting records. It also covers advanced topics like triggers, set operations, and aggregate functions, detailing their syntax and usage in SQL queries. Overall, it serves as a comprehensive guide for understanding and utilizing SQL in relational database management systems.

Uploaded by

sahanakm8867
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views45 pages

DBMS M2 Final

This document provides an overview of SQL, including its basic structure, data types, and various commands for database operations such as creating, updating, and deleting records. It also covers advanced topics like triggers, set operations, and aggregate functions, detailing their syntax and usage in SQL queries. Overall, it serves as a comprehensive guide for understanding and utilizing SQL in relational database management systems.

Uploaded by

sahanakm8867
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

DBMS

MODULE 2
OVERVIEW OF THE SQL QUERY
LANGUAGE
Basic structure of SQL Queries

• SQL stands for Structured Query Language.


• SQL is used to perform operation on Relational
DBMS
• SQL is declarative, hence easy to learn
• SQL provides multiple commands to perform various
operations like create, update, retrieve and delete
the data
Data Types in SQL
• Numeric Datatypes

• Character and String Data Types

• Date and Time Data Types

• Binary Data Types

• Boolean Data Types

• Special Data Types


Data Types
• Numeric Data Types
Numeric data types are fundamental to database design and are
used to store numbers, whether they are integers, decimals, or floating-
point numbers. These data types allow for mathematical operations like
addition, subtraction, multiplication, and division, which makes them
essential for managing financial, scientific, and analytical data.
• Int, float, double
Data Types
• String Data Types
Character data types are used to store text or character-based data
Data Types
• Unicode Character String Datatype : Unicode data types are used to store
characters from any language, supporting a wider variety of characters. These
are given in below table
Data Types
• Date and Time Data Type in SQL
SQL provides several data types for storing date and time information. These
are given in the below table.
Data Types
• Binary Data Types in SQL : Binary data types are used to store binary data such as images,
videos, or other file types.

• Boolean Data Type in SQL : Boolean data types are used to store logical values, typically
TRUE or FALSE
Creating a database
CREATE DATABASE
• The CREATE DATABASE command establishes a new database within your SQL ecosystem. A database is a
repository that organizes data in structured formats through tables, views, stored procedures, and other
components.

• The syntax for CREATE DATABASE command in SQL is: CREATE DATABASE database_name;

• We use the SHOW DATABASES command and it will return a list of databases that exist in our system.

• The syntax for to show the database: SHOW DATABASES;

• To remove a database, the DROP DATABASE command can be used to delete the database and all its
contents:

• The syntax for deleting or dropping a database: DROP DATABASE database_name;


Creating a Table
• CREATE TABLE
• To create a new table in the database, use the SQL CREATE TABLE statement. A table’s structure, including column
names, data types, and constraints like NOT NULL, PRIMARY KEY, and CHECK, are defined when it is created in SQL.
• Syntax:
• CREATE table table_name
(
Column1 datatype (size),
column2 datatype (size),
.
.
columnN datatype(size)
);
• table_name: The name you assign to the new table.

• column1, column2, … : The names of the columns in the table.

• datatype(size): Defines the data type and size of each column.


Drop table
• A SQL DROP TABLE statement is used to delete a table definition and all data from a table.
• This is very important to know that once a table is deleted all the information available in
the table is lost forever, so we have to be very careful when using this command.

• Syntax:
DROP TABLE table_name;
Select Table
• The SELECT statement is the most commonly used command in Structured Query Language. It is used to
access the records from one or more database tables and views. It also retrieves the selected data that
follow the conditions we want.
• Syntax :
• SELECT Column_Name_1, Column_Name_2, ....., Column_Name_N FROM Table_Name;
• In this SELECT syntax, Column_Name_1, Column_Name_2, ….., Column_Name_N are the name of those
columns in the table whose data we want to read.
• If you want to access all rows from all fields of the table, use the following SQL SELECT syntax with * asterisk
sign:
• Syntax : SELECT * FROM table_name;
Insert a Record
You can insert a row in the table by using SQL INSERT INTO command.
• In the first method there is no need to specify the column name where the data will be
inserted, you need only their values.
INSERT INTO table_name VALUES (value1, value2, value3....);

• The second method specifies both the column name and values which you want to
insert.

INSERT INTO table_name (column1, column2, column3....) VALUES (value1, value2, value3
.....);
Update a Record

• The update statement is used to modify the existing records in a table

• UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

• UPDATE Table -The following SQL statement updates the first customer (CustomerID = 1) with a
new contact person and a ne
• UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
Delete a Record
The delete statement is used to delete existing records in a table.

• Syntax :
DELETE FROM table_name WHERE condition;

• Example :
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
Order by
• The order by keyword is used to sort the result-set in ascending or descending order.
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
• DESC – keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
SELECT * FROM Products
ORDER BY Price DESC;
• Order Alphabetically - For string values the ORDER BY keyword will order alphabetically.
SELECT * FROM Products
ORDER BY ProductName;
• ORDER BY Several Columns - The following SQL statement selects all customers from the "Customers" table, sorted by the "Country" and the
"CustomerName" column. This means that it orders by Country, but if some rows have the same Country, it orders them by CustomerName
SELECT * FROM Customers
ORDER BY Country, CustomerName;
• Using Both ASC and DESC - The following SQL statement selects all customers from the "Customers" table, sorted ascending by the "Country" and
descending by the "CustomerName" column.
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
Group by
• The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each
country".
• The GROUP BY statement is often used with aggregate functions (COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or
more columns.
• GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
• Example 1
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
• Example 2
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
Triggers
• Another important statement in SQL is CREATE TRIGGER. In many cases it is convenient to specify the type of
action to be taken when certain events occur and when certain conditions are satisfied.
• The condition is thus used to monitor the database. Other actions may be specified, such as executing a
specific stored procedure or triggering other updates. The CREATE TRIGGER statement is used to implement
such actions in SQL.
• CREATE TRIGGER SALARY_VIOLATION BEFORE INSERT OR UPDATE OF SALARY, SUPERVISOR_SSN ON EMPLOYEE
FOR EACH ROW WHEN ( NEW.SALARY > ( SELECT SALARY FROM EMPLOYEE WHERE SSN =
NEW.SUPERVISOR_SSN ) ) INFORM_SUPERVISOR (NEW.Supervisor_ssn, NEW.Ssn );
• The trigger is given the name SALARY_VIOLATION, which can be used to remove or deactivate the trigger later.
• The event(s): These are usually database update operations that are explicitly applied to the database. In this
example the events are: inserting a new employee record, changing an employee’s salary, or changing an
employee’s supervisor. The person who writes the trigger must make sure that all possible events are
accounted for. In some cases, it may be necessary to write more than one trigger to cover all possible cases.
• BEFORE - which means that the trigger should be executed before the triggering operation is executed.
• AFTER - which specifies that the trigger should be executed after the operation specified in the event is
completed.
Triggers
• The condition that determines whether the rule action should be executed: Once the triggering event has
occurred, an optional condition may be evaluated. If no condition is specified, the action will be executed
once the event occurs. If a condition is specified, it is first evaluated, and only if it evaluates to true will the
rule action be executed. The condition is specified in the WHEN clause of the trigger.
• The action to be taken: The action is usually a sequence of SQL statements, but it could also be a database
transaction or an external program that will be automatically executed. In this example, the action is to
execute the stored procedure INFORM_SUPERVISOR.
• Triggers can be used in various applications, such as maintaining database consistency, monitoring database
updates, and updating derived data automatically.
• The four triggers (active rules) R1, R2, R3, and R4 illustrate a number of features of active rules. First, the
basic events that can be specified for triggering the rules are the standard SQL update commands: INSERT,
DELETE, and UPDATE.
• Thus, rule R1 is triggered after an INSERT operation is applied to the EMPLOYEE relation. In R1, the
condition (NEW.Dno IS NOT NULL) is checked, and if it evaluates to true, meaning that the newly inserted
employee tuple is related to a department, then the action is executed. The action updates the
DEPARTMENT tuple(s) related to the newly inserted employee by adding their salary (NEW.Salary) to the
Total_sal attribute of their related department.
Triggers
• Rule R2 is similar to R1, but it is triggered by an UPDATE operation that updates the SALARY of an employee
rather than by an INSERT. Rule R3 is triggered by an update to the Dno attribute of EMPLOYEE, which
signifies changing an employee’s assignment from one department to another. There is no condition to
check in R3, so the action is executed whenever the triggering event occurs.
• This operation would be an event that triggers rule R2:
• UPDATE EMPLOYEE SET Salary = 1.1 * Salary WHERE Dno = 5;

• It is important to note the effect of the optional FOR EACH ROW clause, which signifies that the rule is
triggered separately for each tuple. This is known as a row-level trigger. If this clause was left out, the trigger
would be known as a statement-level trigger and would be triggered once for each triggering statement. To
see the difference, consider the following update operation, which gives a 10 percent raise to all employees
assigned to department 5. This operation would be an event that triggers rule R2:
• UPDATE EMPLOYEE SET Salary = 1.1 * Salary WHERE Dno = 5;
Set Operations
• The set of all courses taught in the Fall 2009 semester:
select course_id from section where semester = ’Fall’ and year= 2009; 
• The set of all courses taught in the Spring2010 semester:
select course_id from section where semester = ’Spring’ and year= 2010;

The Union Operation :To find the set of all courses taught either in Fall 2009 or in Spring 2010, or both, we
write:
(select course_id from section where semester = ’Fall’ and year= 2009)
union
(select course_id from section where semester = ‘Spring’ and year = 2010);
• The union operation automatically eliminates duplicates, unlike the select clause. If we want to retain all
duplicates, we must write union all in place of union.
Set Operations
The Intersect Operation
• To find the set of all courses taught in the Fall 2009 as well as in Spring 2010 we write:
(select course_id from section where semester = ’Fall’ and year= 2009)
intersect
(select course_id from section where semester = ’Spring’ and year= 2010);
• The intersect operation automatically eliminates duplicates. If we want to retain all duplicates, we must
write intersect all in place of intersect.
The Except Operation
• To find all courses taught in the Fall 2009 semester but not in the Spring 2010 semester, we write:
(select course_id from section where semester = ’Fall’ and year= 2009)
except
(select course_id from section where semester = ’Spring’ and year= 2010);
• The except operation outputs all tuples from its first input that do not occur in the second input; that is, it
performs set difference. The operation automatically eliminates duplicates in the inputs before performing
set difference. If we want to retain duplicates, we must write except all in place of except.
Set Operations
Null values
• The result of an arithmetic expression (involving, for example +, −, ∗, or /)is null if any of the input values is
null. For example, if a query has an expression r. A+5, and r. A is null for a particular tuple, then the
expression result must also be null for that tuple.
• Since the predicate in a where clause can involve Boolean operations such as and, or, and not on the results
of comparisons, the definitions of the Boolean operations are extended to deal with the value unknown.
• and: The result of true and unknown is unknown, false and unknown is false, while unknown and
unknown is unknown.
• or: The result of true or unknown is true, false or unknown is unknown, while unknown or unknown
is unknown.
• not: The result of not unknown is unknown.
• You can verify that if r.A is null, then “1 < r.A” as well as “not (1 < r.A)” evaluate to unknown. If the where
clause predicate evaluates to either false or unknown for a tuple, that tuple is not added to the result.
• SQL uses the special keyword null in a predicate to test for a null value. Thus, to find all instructors who
appear in the instructor relation with null values for salary, we write:
select name from instructor where salary is null;
Aggregate Functions
• Aggregate functions are functions that take a collection (a set or multiset) of values as
input and return a single value. SQL offers five built-in aggregate functions:

• Average: avg
• Minimum: min
• Maximum: max
• Total: sum
• Count: count

• The input to sum and avg must be a collection of numbers, but the other operators can
operate on collections of nonnumeric data types, such as strings, as well.
Aggregate Functions
Basic Aggregation
• Consider the query “Find the average salary of instructors in the Computer Science
department.” We write this query as follows:
select avg (salary) from instructor where dept_name= ’Comp.Sci.’;
• The result of this query is a relation with a single attribute, containing a single tuple with
a numerical value corresponding to the average salary of instructors in the Computer
Science department.
• select count(distinct ID) from teaches where semester = ’Spring’ and year= 2010;
• Because of the keyword distinct preceding ID, even if an instructor teaches more than
one course, she is counted only once in the result. We use the aggregate function count
frequently to count the number of tuples in a relation. The notation for this function in
SQL is count (*).
• Thus, to find the number of tuples in the course relation, we write
• select count(*) from course;
Aggregate Functions
Aggregation with Grouping
• There are circumstances where we would like to apply the aggregate
function not only to a single set of tuples, but also to a group of sets of
tuples; we specify this wish in SQL using the group by clause.
• The attribute or attributes given in the group by clause are used to form
groups. Tuples with the same value on all attributes in the group by clause
are placed in one group.
• As an illustration, consider the query “Find the average salary in each
department.” We write this query as follows:
• Select dept_name, avg(salary) as avg_salary From instructor Group by
dept_name;
Aggregate Functions
The Having Clause

• This condition does not apply to a single tuple; rather, it applies to each
group constructed by the group by clause. To express such a query, we use
the having clause of SQL.
• SQL applies predicates in the having clause after groups have been formed,
so aggregate functions may be used.
• We express this query in SQL as follows:
select dept_name, avg(salary) as avg_salary from instructor group by
dept_name having avg(salary)> 42000;
Aggregate Functions
• The meaning of a query containing aggregation, group by, or having clauses is
defined by the following sequence of operations:
• 1. As was the case for queries without aggregation, the from clause is first evaluated
to get a relation.
• 2. If a where clause is present, the predicate in the where clause is applied on the
result relation of the from clause.
• 3. Tuples satisfying the where predicate are then placed into groups by the group by
clause if it is present. If the group by clause is absent, the entire set of tuples
satisfying the where predicate is treated as being in one group.
• 4. The having clause, if it is present, is applied to each group; the groups that do not
satisfy the having clause predicate are removed.
• 5. The select clause uses the remaining groups to generate tuples of the result of the
query, applying the aggregate functions to get a single result tuple for each group.
Aggregate Functions
Aggregation with Null and Boolean Values
• Null values, when they exist, complicate the processing of aggregate operators. For
example, assume that some tuples in the instructor relation have a null value for salary.
Consider the following query to total all salary amounts:
select sum (salary) from instructor;
• The values to be summed in the preceeding query include null values, since some tuples
have a null value for salary. Rather than say that the overall sum is itself null, the SQL
standard says that the sum operator should ignore null values in its input.
• In general, aggregate functions treat nulls according to the following rule: All aggregate
functions except count (*) ignore null values in their input collection. As a result of null
values being ignored, the collection of values may be empty.
• The count of an empty collection is defined to be 0, and all other aggregate operations
return a value of null when applied on an empty collection. The effect of null values on
some of the more complicated SQL constructs can be subtle.
Nested Subqueries
Set Membership
• SQL allows testing tuples for membership in a relation. The in connective tests for set
membership, where the set is a collection of values produced by a select clause. The not in
connective tests for the absence of set membership.
• We begin by finding all courses taught in Spring2010, and we write the subquery
(select course_id From section Where semester =’Spring’ and year= 2010)
• We then need to find those courses that were taught in the Fall 2009 and that appear in the set
of courses obtained in the subquery. We do so by nesting the subquery in the where clause of
an outer query. The resulting query is
Select distinct course_id From section Where semester = ’Fall’ and year= 2009 and
course_id in (select course_id From section Where semester =’Spring’ and year= 2010);
• We use the not in construct in a way similar to the in construct. For example, to find all the
courses taught in the Fall 2009 semester but not in the Spring 2010 semester, we can write:
select distinct course_id from section where semester= ’Fall’ and year= 2009 and course_id
not in (select course_id from section where semester = ’Spring’ and year= 2010);
Nested Subqueries
Set Comparison
• consider the query “Find the names of all instructors whose salary is greater than at least
one instructor in the Biology department.” Before, we wrote this query as follows:
select distinct T.name from instructor as T, instructor as S where T.salary > S.salary
and S.dept_name = ’Biology’;
• The > some comparison in the where clause of the outer select is true if the salary value
of the tuple is greater than at least one member of the set of all salary values for
instructors in Biology.
• Now we modify our query slightly. Let us find the names of all instructors that have a
salary value greater than that of each instructor in the Biology department. The construct
> all corresponds to the phrase “greater than all.”
• Using this construct, we write the query as follows:
Select name From instructor Where salary > all (select salary From instructor Where
dept_name =’Biology’);
• SQL also allows< all, < = all, >= all, = all, and<> all comparisons.
Nested Subqueries
Test for Empty Relations
• SQL includes a feature for testing whether a subquery has any tuples in its result. The
exists construct returns the value true if the argument subquery is nonempty.
• Using the exists construct, we can write the query “Find all courses taught in both the Fall
2009 semester and in the Spring 2010 semester” in still another way:
Select course_id From section as S Where semester = ‘Fall and year = 2009 and Exists
(select * From section as T Where semester = ‘Spring’ and year = 2010 and S.course_id =
T.course_id);
• The above query also illustrates a feature of SQL where a correlation name from an outer
query (S in the above query), can be used in a subquery in the where clause. A subquery
that uses a correlation name from an outer query is called a correlated subquery.
(select T.course_id From takes as T Where S.ID=T.ID)
• finds all the courses that student.ID has taken. Thus, the outer select takes each student
and tests whether the set of all courses that the student has taken contains the set of all
courses offered in the Biology department.
Nested Subqueries
Test for the Absence of Duplicate Tuples
• SQL includes a boolean function for testing whether a subquery has duplicate
tuples in its result. The unique construct returns the value true if the
argument subquery contains no duplicate tuples.
• Using the unique construct, we can write the query “Find all courses that
were offered at most once in 2009” as follows:
Select T.course_id From course as T Where unique (select R.course_id
From section as R Where T.course_id = R.course_id and R.year = 2009);
Nested Subqueries
Subqueries in the From Clause
• SQL allows a subquery expression to be used in thefrom clause. The key
concept applied here is that any select-from-where expression returns a
relation as a result and, therefore, can be inserted into another select-from-
where anywhere that a relation can appear.
• Consider the query “Find the average instructors’ salaries of those
departments where the average salary is greater than $42,000.” We wrote
this query before by using the having clause.
• We can now rewrite this query, without using the having clause, by using a
subquery in the from clause, as follows:
Select dept_name, avg_salary from (select dept_name, avg (salary) as
avg_salary from instructor group by dept_name) where avg_salary> 42000;
Nested Subqueries
The with clause
• The with clause makes the query logic clearer; it also permits a view
definition to be used in multiple places within a query.
• For example, suppose we want to find all departments where the total salary
is greater than the average of the total salary at all departments. We can
write the query using the with clause as follows:
with dept_total (dept_name, value) as (select dept_name, sum(salary) From instructor
Group by dept_name), Dept_total_avg(value) as (select avg(value) From dept_total)
select dept_name from dept_total, dept_total_ avg where dept_total.value >=
dept_total_avg.value;
• We can create an equivalent query without the with clause, but it would be
more complicated and harder to understand.
Views
• It is not desirable for all users to see the entire logical model. Security
considerations may require that certain data be hidden from users.
• Instead, SQL allows a “virtual relation” to be defined by a query, and the
relation conceptually contains the result of the query.
• The virtual relation is not precomputed and stored, but instead is computed
by executing the query whenever the virtual relation is used.
• Any such relation that is not part of the logical model, but is made visible to a
user as a virtual relation, is called a view.
• It is possible to support a large number of views on top of any given set of
actual relations.
Views
View Definition
• We define a view in SQL by using the create view command. To define a view,
we must give the view a name and must state the query that computes the
view. The form of the create view command is:
• create view v as <queryexpression>;
• where <queryexpression> is any legal query expression. The view name is
represented by v.
• Consider again the clerk who needs to access all data in the instructor
relation, except salary. The clerk should not be authorized to access the
instructor relation. Instead, a view relation faculty can be made available to
the clerk, with the view defined as follows:
• create view faculty as select ID, name, dept_name from instructor;
Views
Using Views in SQL Queries
• Once we have defined a view, we can use the view name to refer to the virtual relation
that the view generates.
• View names may appear in a query any place where a relation name may appear. The
attribute names of a view can be specified explicitly as follows:
Create view departments_total_salary(dept_name, total_salary) as Select
dept_name, sum (salary) From instructor Group by dept_name;
Materialized Views
• Certain database systems allow view relations to be stored, but they make sure that, if the
actual relations used in the view definition change, the view is kept up-to-date. Such views
are called materialized views.
• The process of keeping the materialized view up-to-date is called materialized view
maintenance. View maintenance can be done immediately when any of the relations on
which the view is defined is updated.
Views
Update of a View
• Although views are a useful tool for queries, they present serious problems if we express updates,
insertions, or deletions with them.
• The difficulty is that a modification to the database expressed in terms of a view must be translated to a
modification to the actual relations in the logical model of the database.
• create view instructor_info as
select ID,name,building from instructor, department where instructor.dept_name =
department.dept_name;
• In general, an SQL view is said to be updatable (that is, inserts, updates or deletes can be applied on the
view) if the following conditions are all satisfied by the query defining the view:
• The from clause has only one database relation.
• The select clause contains only attribute names of the relation, and does not have any expressions,
aggregates, or distinct specification.
• Any attribute not listed in the select clause can be set to null; that is, it does not have a not null constraint
and is not part of a primary key.
• The query does not have a group by or having clause.
Transactions
A transaction consists of a sequence of query and/or update statements. The SQL
standard specifies that a transaction begins implicitly when an SQL statement is executed.
One of the following SQL statements must end the transaction:
• Commit work commits the current transaction; that is, it makes the updates performed by
the transaction become permanent in the database. After the transaction is committed, a
new transaction is automatically started.
• Rollback work causes the current transaction to be rolled back; that is, it undoes all the
updates performed by the SQL statements in the transaction. Thus, the database state is
restored to what it was before the first statement of the transaction was executed.
• The keyword work is optional in both the statements.
• Transaction rollback is useful if some error condition is detected during execution of a
transaction. Commit is similar, in a sense, to saving changes to a document that is being
edited, while rollback is similar to quitting the edit session without saving changes.
• Once a transaction has executed commit work, its effects can no longer be undone by
rollback work.
Integrity Constraints
• Integrity constraints ensure that changes made to the database by authorized users do
not result in a loss of data consistency. Thus, integrity constraints guard against accidental
damage to the database. Examples of integrity constraints are:
• An instructor name cannot be null.
• No two instructors can have the same instructor ID.
• Every department name in the course relation must have a matching department name in
the department relation.
• Integrity constraints are usually identified as part of the database schema design process,
and declared as part of the create table command used to create relations. However,
integrity constraints can also be added to an existing relation by using the command alter
table table-name add constraint, where constraint can be any constraint on the relation.
• When such a command is executed, the system first ensures that the relation satisfies the
specified constraint. If it does, the constraint is added to the relation; if not, the command
is rejected.
Integrity Constraints

Constraints on a Single Relation


• The create table command may also include integrity-constraint statements.
• In addition to the primary-key constraint, there are a number of other ones that can be
included in the create table command.
• The allowed integrity constraints include
• not null
• unique
• check (<predicate>)
Procedures
Although this is suitable for many applications, it is sometimes useful to create database program modules—
procedures or functions— that are stored and executed by the DBMS at the database server. These are
historically known as database stored procedures, although they can be functions or procedures.
The term used in the SQL standard for stored procedures is persistent stored modules because these
programs are stored persistently by the DBMS, similarly to the persistent data stored by the DBMS.
Stored procedures are useful in the following circumstances:
■ If a database program is needed by several applications, it can be stored at the server and invoked by any
of the application programs. This reduces duplication of effort and improves software modularity.
■ Executing a program at the server can reduce data transfer and communication cost between the client and
server in certain situations.
■ These procedures can enhance the modeling power provided by views by allowing more complex types of
derived data to be made available to the database users. Additionally, they can be used to check for complex
constraints that are beyond the specification power of assertions and triggers.
Procedures
In general, many commercial DBMSs allow stored procedures and functions to be written in a general purpose
programming language.
Alternatively, a stored procedure can be made of simple SQL commands such as retrievals and updates. The
general form of declaring stored procedures is as follows:
CREATE PROCEDURE <procedure name> (<parameters>)
<local declarations>
<procedure body>;
The parameters and local declarations are optional, and are specified only if needed. For declaring a function,
a return type is necessary, so the declaration form is :
CREATE FUNCTION <function name> (<parameters>)
RETURNS <return type>
<local declarations>
<function body>;
Procedures
If the procedure (or function) is written in a general-purpose programming language, it is typical to specify the
language as well as a file name where the program code is stored. For example, the following format can be
used:
CREATE PROCEDURE <procedure name> (<parameters>)
LANGUAGE <programming language name>
EXTERNAL NAME <file path name>;
In general, each parameter should have a parameter type that is one of the SQL data types. Each parameter
should also have a parameter mode, which is one of IN, OUT, or INOUT. These correspond to parameters
whose values are input only, output (returned) only, or both input and output, respectively.
Because the procedures and functions are stored persistently by the DBMS, it should be possible to call them
from the various SQL interfaces and programming techniques.
The CALL statement in the SQL standard can be used to invoke a stored procedure—either from an interactive
interface or from embedded SQL or SQLJ. The format of the statement is as follows:
CALL <procedure or function name> (<argument list>);
If this statement is called from JDBC, it should be assigned to a statement object of type CallableStatement .

You might also like