SlideShare une entreprise Scribd logo
1  sur  101
Aruna Devi C (DSCASC) 1
SQL
Chapter 7
Unit IV
Data Base Management System
[DBMS]
Aruna Devi C (DSCASC) 2
SQL
• The name SQL is presently expanded as Structured Query Language.
• Originally, SQL was called SEQUEL (Structured English QUEry
Language) and was designed and implemented at IBM Research as
the interface for an experimental relational database system called
SYSTEM R.
• SQL is now the standard language for commercial relational DBMSs.
Aruna Devi C (DSCASC) 3
History - SQL
IBM Sequel language developed as part of System R project at the
IBM San Jose Research Laboratory.
Renamed as Structured Query Language (SQL)
ANSI and ISO standard SQL:
* SQL-86
* SQL-89
* SQL-92
* SQL:1999 (language name became Y2K compliant!)
* SQL:2003
* SQL:2006 ( XML features)
* SQL:2008 (Object Database features)
SQL is based on set and relational operations with certain modifications and
enhancements.
SQL is not case sensitive.
Aruna Devi C (DSCASC) 4
SQL Data Definition and Data Types
• SQL uses the terms table, row, and column for the formal relational model
terms relation, tuple, and attribute, respectively.
• SQL command for data definition is the CREATE statement, which can be used
to create schemas, tables (relations), and domains (as well as other constructs
such as views, assertions, and triggers).
Schema and Catalog Concepts in SQL:
• An SQL schema is identified by a schema name, and includes an
authorization identifier to indicate the user or account who owns the schema,
as well as descriptors for each element in the schema.
• Schema elements include tables, constraints, views, domains, and other
constructs (such as authorization grants) that describe the schema.
Aruna Devi C (DSCASC) 5
SQL Data Definition and Data Types (cont.,)
• A schema is created via the CREATE SCHEMA statement, which can include
all the schema elements’ definitions.
• The following statement creates a schema called COMPANY, owned by the
user with authorization identifier ‘Jsmith’.
• Note that each statement in SQL ends with a semicolon.
CREATE SCHEMA COMPANY AUTHORIZATION ‘Jsmith’;
Aruna Devi C (DSCASC) 6
SQL Data Definition and Data Types (cont.,)
• SQL uses the concept of a catalog—a named collection of schemas in an SQL
environment.
• An SQL environment is basically an installation of an SQL-compliant RDBMS
on a computer system.
• A catalog always contains a special schema called INFORMATION_SCHEMA,
which provides information on all the schemas in the catalog and all the
element descriptors in these schemas.
Aruna Devi C (DSCASC) 7
SQL
SQL can be divided into two parts:
* Data Definition Language (DDL)
* Data Manipulation Language (DML)
DDL:
The DDL part of SQL permits database tables to be created or
deleted. It also define indexes (keys), specify links between tables, and impose constraints
between tables. The most important DDL statements in SQL are:
» CREATE TABLE - creates a new table
» ALTER TABLE - modifies a table
» DROP TABLE - deletes a table
DML:
The query and update commands form the DML part of SQL:
» SELECT - extracts data from a database
» UPDATE - updates data in a database
» DELETE - deletes data from a database
» INSERT INTO - inserts new data into a database
Aruna Devi C (DSCASC) 8
SQL Data Definition and Data Types (cont.,)
The CREATE TABLE Command in SQL:
The CREATE TABLE command is used to specify a new relation by giving it a name and
specifying its attributes and initial constraints.
• An SQL relation is defined using the create table command:
create table r (A1 D1, A2 D2, ..., An Dn,
(integrity-constraint1), ...)
– r is the name of the relation
– each Ai is an attribute name in the schema of relation r
– Di is the data type of values in the domain of attribute Ai
• Example:
create table branch
(branch_name char(15) not null,
branch_city char(30),
assets integer)
Aruna Devi C (DSCASC) 9
SQL Data Definition and Data Types (cont.,)
The CREATE TABLE Command in SQL: (Cont.,)
Aruna Devi C (DSCASC) 10
SQL Data Definition and Data Types (cont.,)
The CREATE TABLE Command in SQL: (Cont.,)
Aruna Devi C (DSCASC) 11
SQL Data Definition and Data Types (cont.,)
The CREATE TABLE Command in SQL: (Cont.,)
Aruna Devi C (DSCASC) 12
Company Database
Aruna Devi C (DSCASC) 13
Attribute Data Types and Domains in SQL:
The basic data types available for attributes include numeric, character
string, bit string, Boolean, date, and time.
Numeric data types:
• Integer numbers of various sizes (INTEGER or INT, and SMALLINT) and floating-point (real)
numbers of various precision (FLOAT or REAL, and DOUBLE PRECISION).
• Formatted numbers can be declared by using DECIMAL(i,j)—or DEC(i,j) or NUMERIC(i,j)—
where i, the precision, is the total number of decimal digits.
Character-string data types:
• Fixed length — CHAR(n) or CHARACTER(n), where n is the number of characters.
• Varying length— VARCHAR(n) or CHAR VARYING(n) or CHARACTER VARYING(n), where
n is the maximum number of characters.
Note: A literal string value is placed between single quotation marks and it is case sensitive
SQL Data Definition and Data Types (cont.,)
Aruna Devi C (DSCASC) 14
Attribute Data Types and Domains in SQL (cont.,)
CLOB data type:
• CLOB is to specify columns that have large text values, such as documents.
• The CLOB maximum length can be specified in kilobytes (K), megabytes (M), or gigabytes
(G).
• For example, CLOB(20M) specifies a maximum length of 20 megabytes.
Bit-string data types:
• Bit string are either of fixed length n—BIT(n)—or varying length—BIT VARYING(n), where n
is the maximum number of bits.
BLOB data type:
• The default for n, the length of a character string or bit string, is 1.
• BLOB is also available to specify columns that have large binary values, such as images.
• The BLOB maximum length can be specified in kilobits (K), megabits (M), or gigabits (G).
• For example, BLOB(30G) specifies a maximum length of 30 gigabits.
SQL Data Definition and Data Types (cont.,)
Aruna Devi C (DSCASC) 15
Attribute Data Types and Domains in SQL (cont.,)
Boolean data type:
It has the traditional values of TRUE or FALSE.
DATE data type:
It has ten positions, and its components are YEAR, MONTH, and DAY in the
form YYYY-MM-DD.
TIME data type:
It has at least eight positions, with the components HOUR, MINUTE, and
SECOND in the form HH:MM:SS.
Timestamp data type:
TIMESTAMP includes the DATE and TIME fields, plus a minimum of six
positions for decimal fractions of seconds and an optional WITH TIME ZONE
qualifier.
------------------
SQL Data Definition and Data Types (cont.,)
Aruna Devi C (DSCASC) 16
Specifying Constraints in SQL
• SQL allows NULLs as attribute values, a constraint NOT NULL may be specified
if NULL is not permitted for a particular attribute.
• It is also possible to define a default value for an attribute by appending the
clause DEFAULT <value> to an attribute definition.
• Constraint can restrict attribute or domain values using the CHECK clause
following an attribute or domain definition.
Dnumber INT NOT NULL CHECK (Dnumber > 0 AND Dnumber < 21);
Aruna Devi C (DSCASC) 17
Specifying Key and Referential Integrity Constraints:
• The PRIMARY KEY clause specifies one or more attributes that make up the
primary key of a relation.
• If a primary key has a single attribute, the clause can follow the attribute directly.
• The UNIQUE clause specifies alternate (secondary) keys.
Dname VARCHAR(15) UNIQUE
• Referential integrity is specified via the FOREIGN KEY clause.
Specifying Constraints in SQL (Cont.,)
Aruna Devi C (DSCASC) 18
Specifying Key and Referential Integrity Constraints (cont.,):
• A referential integrity constraint can be violated when tuples are inserted or
deleted, or when a foreign key or primary key attribute value is modified.
• The default action that SQL takes for an integrity violation is to reject the update
operation that will cause a violation, which is known as the RESTRICT option.
• However, the schema designer can specify an alternative action to be taken by
attaching a referential triggered action clause to any foreign key constraint.
• The options include SET NULL, CASCADE, and SET DEFAULT.
• An option must be qualified with either ON DELETE or ON UPDATE.
Specifying Constraints in SQL (Cont.,)
Aruna Devi C (DSCASC) 19
Specifying Key and Referential Integrity Constraints (cont.,)
Example:
• The database designer chooses ON DELETE SET NULL and ON UPDATE
CASCADE for the foreign key Super_ssn of EMPLOYEE.
• This means that if the tuple for a supervising employee is deleted, the value of
Super_ssn is automatically set to NULL for all employee tuples that were
referencing the deleted employee tuple.
• On the other hand, if the Ssn value for a supervising employee is updated (say,
because it was entered incorrectly), the new value is cascaded to Super_ssn for all
employee tuples referencing the updated employee tuple.
• The action for CASCADE ON DELETE is to delete all the referencing tuples.
• The action for CASCADE ON UPDATE is to change the value of the referencing
foreign key attribute(s) to the updated (new) primary key value for all the
referencing tuples.
Aruna Devi C (DSCASC) 20
Specifying Key and Referential Integrity Constraints (cont.,)
• We can specify RESTRICT, CASCADE, SET NULL or SET DEFAULT on
referential integrity constraints (foreign keys)
CREATE TABLE DEPT
( DNAME VARCHAR(10) NOT NULL,
DNUMBER INTEGER NOT NULL,
MGRSSN CHAR(9),
MGRSTARTDATE CHAR(9),
PRIMARY KEY (DNUMBER),
UNIQUE (DNAME),
FOREIGN KEY (MGRSSN) REFERENCES EMP
ON DELETE SET DEFAULT ON UPDATE CASCADE );
Aruna Devi C (DSCASC) 21
Specifying Key and Referential Integrity Constraints (cont.,)
CREATE TABLE EMP
( ENAME VARCHAR(30) NOT NULL,
ESSN CHAR(9),
BDATE DATE,
DNO INTEGER DEFAULT 1,
SUPERSSN CHAR(9),
PRIMARY KEY (ESSN),
FOREIGN KEY (DNO) REFERENCES DEPT
ON DELETE SET DEFAULT ON UPDATE CASCADE,
FOREIGN KEY (SUPERSSN) REFERENCES EMP
ON DELETE SET NULL ON UPDATE CASCADE );
Aruna Devi C (DSCASC) 22
Specifying Constraints in SQL (Cont.,)
Giving Names to Constraints:
• A constraint name is used to identify a particular constraint in case the
constraint must be dropped later and replaced with another constraint.
Specifying Constraints on Tuples Using CHECK:
• CHECK clauses at the end of a CREATE TABLE statement.
• These can be called tuple-based constraints because they apply to each tuple
individually and are checked whenever a tuple is inserted or modified.
CHECK (Dept_create_date <= Mgr_start_date);
Aruna Devi C (DSCASC) 23
Schema Change Statement in SQL
Schema Change Statement in SQL, which can be
used to alter a schema by adding or dropping tables, attributes,
constraints, and other schema elements.
1) DROP Command.
2) The ALTER Command.
Aruna Devi C (DSCASC) 24
Schema Change Statement in SQL (Cont.,)
DROP Command:
The DROP command can be used to drop named schema elements,
such as tables, domains, or constraints.
There are two drop behavior options: CASCADE and RESTRICT.
For example, to remove the COMPANY database schema and all its tables,
domains, and other elements, the CASCADE option is used as follows:
DROP SCHEMA COMPANY CASCADE;
Aruna Devi C (DSCASC) 25
Schema Change Statement in SQL (Cont.,)
• If the RESTRICT option is chosen in place of CASCADE, the schema is dropped
only if it has no elements in it; otherwise, the DROP command will not be executed.
• If a base relation within a schema is no longer needed, the relation and its definition can be
deleted by using the DROP TABLE command.
• If the RESTRICT option is chosen instead of CASCADE, a table is dropped only if it is not
referenced in any constraints.
• With the CASCADE option, all such constraints, views, and other elements that reference
the table being dropped are also dropped automatically from the schema, along with the
table itself.
• The DROP TABLE command not only deletes all the records in the table
successful, but also removes the table definition from the catalog.
DROP TABLE DEPENDENT CASCADE;
Aruna Devi C (DSCASC) 26
Schema Change Statement in SQL (Cont.,)
The ALTER Command:
The definition of a base table or of other named schema elements can be
changed by using the ALTER command.
• The possible alter table actions:
1) Add
2)Drop a column (attribute)
3) Alter (or changing) a column definition
• To Add a column
Syntax:
Alter Table <tablename> Add Column A D
ALTER TABLE COMPANY.EMPLOYEE ADD COLUMN Job VARCHAR(12);
• If no default clause is specified, the new attribute will have NULL in all the tuples of the
relation immediately after the command is executed; hence, the NOT NULL constraint is not
allowed in this case.
Aruna Devi C (DSCASC) 27
Schema Change Statement in SQL (Cont.,)
• To drop a column, we must choose either CASCADE or RESTRICT for drop
behavior.
Syntax:
• Alter Table <tablename> Drop Column A cascade;
ALTER TABLE COMPANY.EMPLOYEE DROP COLUMN Address CASCADE;
• It is also possible to alter a column definition by dropping an existing default
clause or by defining a new default clause.
Syntax:
Alter Table <tablename> Alter Column A D
ALTER TABLE COMPANY.DEPARTMENT ALTER COLUMN Mgr_ssn Varchar2;
Aruna Devi C (DSCASC) 28
Basic Retrieval Queries in SQL
Basic statement for retrieving information from a database is the
SELECT statement.
The SELECT-FROM-WHERE Structure of Basic SQL Queries:
where
• <attribute list> is a list of attribute names whose values are to be retrieved by
• the query.
• <table list> is a list of the relation names required to process the query.
• <condition> is a conditional (Boolean) expression that identifies the tuples
to be retrieved by the query.
SELECT <attribute list>
FROM <table>
WHERE <condition>;
Aruna Devi C (DSCASC) 29
Basic Retrieval Queries in SQL (Cont.,)
• The basic logical comparison operators for comparing attribute values with one
another and with literal constants are =, <, <=, >, >=, and <>.
Query 1: Retrieve the birth date and address of the employee(s) whose name is
John B. Smith’.
SELECT Bdate, Address
FROM EMPLOYEE
WHERE Fname=‘John’ AND Minit=‘B’ AND Lname=‘Smith’;
1
Result:
Company Database
Aruna Devi C (DSCASC) 30
Basic Retrieval Queries in SQL (Cont.,)
Query 2: Retrieve the name and address of all employees who work for the
‘Research’ department.
SELECT Fname, Lname, Address
FROM EMPLOYEE, DEPARTMENT
WHERE Dname=‘Research’ AND Dnumber=Dno;
Result:
2
Company Database
Aruna Devi C (DSCASC) 31
Basic Retrieval Queries in SQL (Cont.,)
Query 3: For every project located in ‘Stafford’, list the project number, the
controlling department number, and the department manager’s last name, address,
and birth date.
SELECT Pnumber, Dnum, Lname, Address, Bdate
FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE Dnum=Dnumber AND Mgr_ssn=Ssn AND
Plocation=‘Stafford’;
Result:
3
Company Database
Aruna Devi C (DSCASC) 32
Basic Retrieval Queries in SQL (Cont.,)
Ambiguous Attribute Names, Aliasing, Renaming, and
Tuple Variables:
• In SQL, we can use the same name for two (or more) attributes as long as the
attributes are in different relations.
• A query that refers to two or more attributes with the same name must qualify
the attribute name with the relation name by prefixing the relation name to the
attribute name.
SELECT Fname, EMPLOYEE.Name, Address
FROM EMPLOYEE, DEPARTMENT
WHERE DEPARTMENT.Name=‘Research’ AND
DEPARTMENT.Dnumber=EMPLOYEE.Dnumber;
Aruna Devi C (DSCASC) 33
Basic Retrieval Queries in SQL (Cont.,)
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;
Result:
• E and S, called aliases or tuple variables, for the EMPLOYEE relation. An alias can
follows the keyword AS (or) it can directly follow the relation name.
• EMPLOYEE AS E(Fn, Mi, Ln, Ssn, Bd, Addr, Sex, Sal, Sssn, Dno) in the FROM clause,
Fn becomes an alias for Fname, Mi for Minit, Ln for Lname, and so on.
Aliasing
Company Database
Aruna Devi C (DSCASC) 34
Basic Retrieval Queries in SQL (Cont.,)
• To retrieve all the attribute values of the selected tuples, we do not have to list the
attribute names explicitly in SQL; we just specify an asterisk (*), which stands for
all the attributes.
SELECT *
FROM EMPLOYEE
WHERE Dno=5;
Company Database
USE OF *
Aruna Devi C (DSCASC) 35
Basic Retrieval Queries in SQL (Cont.,)
• If we do want to eliminate duplicate tuples from the result of an SQL query, we
use the keyword DISTINCT in the SELECT clause, meaning that only distinct
tuples should remain in the result.
Query: a)Retrieve the salary of every employee,
b) Retrieve all distinct salary values.
SELECT ALL Salary
FROM EMPLOYEE;
SELECT DISTINCT Salary
FROM EMPLOYEE;
Company Database
DISTINCT
Aruna Devi C (DSCASC) 36
Basic Retrieval Queries in SQL (Cont.,)
• SQL has directly incorporated some set operations.
• There is a union operation (UNION), and in some versions of SQL there are
set difference (MINUS) and intersection (INTERSECT) operations.
• The resulting relations of these set operations are sets of tuples; duplicate
tuples are eliminated from the result.
• The set operations apply only to union compatible relations ; the two relations
must have the same attributes and the attributes must appear in the same
order
SET OPERATIONS:
Aruna Devi C (DSCASC) 37
Basic Retrieval Queries in SQL (Cont.,)
• Make a list of all project numbers for projects that involve an employee whose last
name is ‘Smith’, either as a worker or as a manager of the department that controls
the project.
SET OPERATIONS (Cont.,)
The first SELECT query retrieves the projects that involve a ‘Smith’ as manager of
the department that controls the project, and the second retrieves the projects
that involve a ‘Smith’ as a worker on the project.
Aruna Devi C (DSCASC) 38
Aruna Devi.C (DSCASC) 38
Set Operations
• Find all customers who have a loan, an account, or both:
(select customer-name from depositor)
except
(select customer-name from borrower)
(select customer-name from depositor)
intersect
(select customer-name from borrower)
Find all customers who have an account but no loan.
(select customer-name from depositor)
union
(select customer-name from borrower)
Find all customers who have both a loan and an account.
TS∪S T
S union T
TS∩S T
S intersect T
TSS - T
S minus T
Basic Retrieval Queries in SQL (Cont.,)
Aruna Devi C (DSCASC) 39
Basic Retrieval Queries in SQL (Cont.,)
• SQL includes a string-matching operator for comparisons on character strings.
• Patterns are described using two special characters:
– percent (%) The % character matches any substring.
– underscore (_) The _ character matches any character.
percent (%)
select cname from customer where street like ‘%Main%’
Underscore(_) ”---” matches any string of exactly three character.
“---%” matches any string of atleast three character.
Escape Keyword: It is use when the special pattern like % and _ is in the
data, It is treated like normal character.
like ‘ab%cd%’
escape  matches all string beginning with ‘ab%cd’
Eg:select cname from customer where cstreet like ‘%Nagar%’
select cname from customer where cstreet like ‘Jaya%’
select cname from customer where ccity like ‘%lore%’
select cname from customer where cname like ‘_ _ _ _’
Substring Pattern Matching and Arithmetic Operators
Aruna Devi C (DSCASC) 40
Basic Retrieval Queries in SQL (Cont.,)
• The standard arithmetic operators '+', '-'. '*', and '/' (for addition, subtraction,
multiplication, and division, respectively) can be applied to numeric values in
an SQL query result.
Query: Show the resulting salaries if every employee working on the
‘ProductX’ project is given a 10 percent raise.
SELECT E.Fname, E.Lname, 1.1 * E.Salary AS Increased_sal
FROM EMPLOYEE AS E, WORKS_ON AS W, PROJECT AS P
WHERE E.Ssn=W.Essn AND W.Pno=P.Pnumber AND
P.Pname=‘ProductX’;
Arithmetic Operators
Aruna Devi C (DSCASC) 41
Basic Retrieval Queries in SQL (Cont.,)
• Comparison operator, which can be used for convenience, is BETWEEN.
Query: Retrieve all employees in department 5 whose salary is between $30,000
and $40,000.
comparison operator
SELECT *
FROM EMPLOYEE
WHERE (Salary BETWEEN 30000 AND
40000) AND Dno = 5;
The condition (Salary BETWEEN 30000 AND 40000) in Query is equivalent
to the condition ((Salary >= 30000) AND (Salary <= 40000)).
Aruna Devi C (DSCASC) 42
Basic Retrieval Queries in SQL (Cont.,)
• The ORDER BY clause is used to sort the tuples in a query result based
on the values of some attribute(s).
Retrieve a list of employees and the projects they are working on, ordered by
department and, within each department, ordered alphabetically by last name,
then first name.
SELECT D.Dname, E.Lname, E.Fname, P.Pname
FROM DEPARTMENT D, EMPLOYEE E, WORKS_ON W,
PROJECT P
WHERE D.Dnumber= E.Dno AND E.Ssn= W.Essn AND
W.Pno= P.Pnumber
ORDER BY D.Dname, E.Lname, E.Fname;
ORDER BY
We can specify the keyword DESC if we want to see the result in a descending order of
values. The keyword ASC can be used to specify ascending order explicitly
Aruna Devi C (DSCASC) 43
INSERT, DELETE, and UPDATE Statements in SQL
• In its simplest form, it is used to add one or more tuples to a relation.
• Attribute values should be listed in the same order as the attributes were
specified in the CREATE TABLE command.
INSERT INTO EMPLOYEE
VALUES ( ‘Richard’, ‘K’, ‘Marini’, ‘653298653’, ‘1962-12-30’, ‘98
Oak Forest, Katy, TX’, ‘M’, 37000, ‘653298653’, 4 );
INSERT
A second form of the INSERT statement allows the user to specify explicit
attribute names that correspond to the values provided in the INSERT command.
INSERT INTO EMPLOYEE (Fname, Lname, Dno, Ssn)
VALUES (‘Richard’, ‘Marini’, 4, ‘653298653’);
Attributes not specified in query are set to their DEFAULT or to NULL.
Aruna Devi C (DSCASC) 44
INSERT, DELETE, and UPDATE Statements in SQL (Cont.,)
• To remove tuples from a relation.
• Includes a WHERE-clause to select the tuples to be deleted.
• Tuples are deleted from only one table at a time (unless CASCADE is specified
on a referential integrity constraint).
• A missing WHERE-clause specifies that all tuples in the relation are to be
deleted; the table then becomes an empty table.
• The number of tuples deleted depends on the number of tuples in the relation
that satisfy the WHERE-clause.
• Referential integrity should be enforced
DELETE
Aruna Devi C (DSCASC) 45
INSERT, DELETE, and UPDATE Statements in SQL (Cont.,)
DELETE FROM EMPLOYEE
WHERE Lname=‘Brown’;
DELETE
DELETE FROM EMPLOYEE
WHERE Ssn=‘123456789’;
DELETE FROM EMPLOYEE;
Aruna Devi C (DSCASC) 46
INSERT, DELETE, and UPDATE Statements in SQL (Cont.,)
• Update is used to modify attribute values of one or more selected tuples.
• A WHERE-clause selects the tuples to be modified.
• An additional SET-clause specifies the attributes to be modified and their new
values.
• Each command modifies tuples in the same relation.
• Referential integrity should be enforced.
UPDATE
Aruna Devi C (DSCASC) 47
INSERT, DELETE, and UPDATE Statements in SQL (Cont.,)
Change the location and controlling department number of project
number 10 to 'Bellaire' and 5, respectively.
UPDATE PROJECT
SET Plocation = ‘Bellaire’, Dnum = 5
WHERE Pnumber=10;
UPDATE
----------------------------------------
Company Database
Aruna Devi C (DSCASC) 48
More Complex SQL Queries
• SQL has various rules for dealing with NULL values.
• NULL is used to represent a missing value.
• That it usually has one of three different interpretations:
1. Value unknown (exists but is not known).
2. Value not available (exists but is purposely withheld).
3. Value not applicable (the attribute is undefined for this tuple).
Example:
• Unknown value: A person’s date of birth is not known, so it is represented by NULL in the
database.
• Unavailable or withheld value: A person has a home phone but does not want it to
be listed, so it is withheld and represented as NULL in the database.
• Not applicable attribute: An attribute LastCollegeDegree would be NULL for a
person who has no college degrees because it does not apply to that person.
Comparisons Involving NULL and Three-Valued Logic
Aruna Devi C (DSCASC) 49
More Complex SQL Queries (Cont.,)
Nested queries:
• A complete SELECT query, called a nested query , can be specified within the
WHERE-clause of another query, called the outer query.
• Many of the previous queries can be specified in an alternative form using
nesting.
Query: Retrieve the name and address of all employees who work for the 'Research'
department.
Nested Queries, Tuples, and Set/Multiset Comparisons
SELECT FNAME, LNAME, ADDRESS
FROM EMPLOYEE
WHERE DNO IN (SELECT DNUMBER
FROM DEPARTMENT
WHERE DNAME='Research' )
Aruna Devi C (DSCASC) 50
More Complex SQL Queries (Cont.,)
Nested queries:
• The nested query selects the number of the 'Research' department.
• The outer query select an EMPLOYEE tuple if its DNO value is in the result of
either nested query.
• The comparison operator IN compares a value v with a set (or multi-set) of
values V, and evaluates to TRUE if v is one of the elements in V.
• In general, we can have several levels of nested queries.
• A reference to an unqualified attribute refers to the relation declared in the
innermost nested query.
• In this example, the nested query is not correlated with the outer query.
Aruna Devi C (DSCASC) 51
More Complex SQL Queries (Cont.,)
Comparison operators:
• In addition to the IN operator, a number of other comparison operators can be
used to compare a single value v.
• The = ANY (or = SOME) operator returns TRUE if the value v is equal to some
value in the set V and is hence equivalent to IN.
• The two keywords ANY and SOME have the same effect. Other operators that
can be combined with ANY (or SOME) include >, >=, <, <=, and <>.
• The keyword ALL can also be combined with each of these operators.
• For example, the comparison condition (v > ALL V) returns TRUE if the value v is
greater than all the values in the set (or multiset) V.
Aruna Devi C (DSCASC) 52
More Complex SQL Queries (Cont.,)
Query: Return the names of employees whose salary is greater than the salary of
all the employees in department 5.
SELECT Lname, Fname
FROM EMPLOYEE
WHERE Salary > ALL ( SELECT Salary
FROM EMPLOYEE
WHERE Dno=5 );
Company Database
Aruna Devi C (DSCASC) 53
More Complex SQL Queries (Cont.,)
Query : Retrieve the name of each employee who has a dependent with the
same first name and is the same sex as the employee.
In the nested query, we must qualify E.Sex because it refers to the Sex attribute of
EMPLOYEE from the outer query, and DEPENDENT also has an attribute called Sex. If there
were any unqualified references to Sex in the nested query, they would refer to the Sex
attribute of DEPENDENT. However, we would not have to qualify the attributes Fname and
Ssn of EMPLOYEE if they appeared in the nested query because the DEPENDENT relation
does not have attributes called Fname and Ssn, so there is no ambiguity.
Aruna Devi C (DSCASC) 54
More Complex SQL Queries (Cont.,)
• If a condition in the WHERE-clause of a nested query references an attribute of a
relation declared in the outer query , the two queries are said to be correlated.
• The result of a correlated nested query is different for each tuple (or combination
of tuples) of the relation(s) the outer query.
Query: Retrieve the name of each employee who has a dependent with the same
first name as the employee.
Correlated Nested Queries
SELECT E.FNAME, E.LNAME
FROM EMPLOYEE AS E
WHERE E.SSN IN (SELECT ESSN
FROM DEPENDENT
WHERE ESSN=E.SSN AND
E.FNAME=DEPENDENT_NAME)
Aruna Devi C (DSCASC) 55
More Complex SQL Queries (Cont.,)
• EXISTS is used to check whether the result of a correlated nested query is empty
(contains no tuples) or not
Query 12: Retrieve the name of each employee who has a dependent with the same
first name as the employee.
EXISTS Functions in SQL
SELECT FNAME, LNAME
FROM EMPLOYEE
WHERE EXISTS (SELECT *
FROM DEPENDENT
WHERE SSN=ESSN AND
FNAME=DEPENDENT_NAME)
Aruna Devi C (DSCASC) 56
More Complex SQL Queries (Cont.,)
Query: Retrieve the names of employees who have no dependents.
SELECT FNAME, LNAME
FROM EMPLOYEE
WHERE NOT EXISTS (SELECT *
FROM DEPENDENT
WHERE SSN=ESSN)
The correlated nested query retrieves all DEPENDENT tuples related
to an EMPLOYEE tuple.
If none exist , the EMPLOYEE tuple is selected
Aruna Devi C (DSCASC) 57
More Complex SQL Queries (Cont.,)
Joints:
Join operation take two relations and return another relation.
Can specify a "joined relation" in the FROM-clause
Different SQL JOINs:
• JOIN: Return rows when there is at least one match in both tables.
• LEFT JOIN: Return all rows from the left table, even if there are no matches in the
right table.
• RIGHT JOIN: Return all rows from the right table, even if there are no matches in
the left table.
• FULL JOIN: Return rows when there is a match in one of the tables.
Joined Tables in SQL and Outer Joins
Aruna Devi C (DSCASC) 58
More Complex SQL Queries (Cont.,)
Join operation take two relations and return another relation.
Product (pname, price, category, manufacturer)
Company (cname, stockPrice, country)
Find all products under $200 manufactured in Japan;
return their names and prices.
SELECT PName, Price
FROM Product, Company
WHERE Manufacturer=CName AND Country=‘Japan’
AND Price <= 200
SELECT PName, Price
FROM Product, Company
WHERE Manufacturer=CName AND Country=‘Japan’
AND Price <= 200
Join
between Product
and Company
Joins
Aruna Devi C (DSCASC) 59
Joins
• Connect two or more tables:
PName Price Category Manufacturer
Gizmo 19.99 Gadgets GizmoWorks
Powergizmo 29.99 Gadgets GizmoWorks
SingleTouch 149.99 Photography Canon
MultiTouch 203.99 Household Hitachi
Product
Company
CName StockPrice Country
GizmoWorks 25 USA
Canon 65 Japan
Hitachi 15 Japan
What is
the Connection
between
them ?
More Complex SQL Queries (Cont.,)
Aruna Devi C (DSCASC) 60
Joins
PName Price Category Manufacturer
Gizmo 19.99 Gadgets GizmoWorks
Powergizmo 29.99 Gadgets GizmoWorks
SingleTouch 149.99 Photography Canon
MultiTouch 203.99 Household Hitachi
Product Company
Cname StockPrice Country
GizmoWorks 25 USA
Canon 65 Japan
Hitachi 15 Japan
PName Price
SingleTouch $149.99
SELECT PName, Price
FROM Product, Company
WHERE Manufacturer=CName AND Country=‘Japan’
AND Price <= 200
SELECT PName, Price
FROM Product, Company
WHERE Manufacturer=CName AND Country=‘Japan’
AND Price <= 200
More Complex SQL Queries (Cont.,)
Aruna Devi C (DSCASC) 61
More Complex SQL Queries (Cont.,)
• Join operations take two relations and return as a result another relation.
• These additional operations are typically used as subquery expressions in the
from clause
• Join condition – defines which tuples in the two relations match, and what
attributes are present in the result of the join.
• Join type – defines how tuples in each relation that do not match any tuple in
the other relation (based on the join condition) are treated.
Joins
Aruna Devi C (DSCASC) 62
More Complex SQL Queries (Cont.,)
Query Q1, which retrieves the name and address of every employee who works for
the ‘Research’ department.
Simple Query 1:
SELECT Fname, Lname, Address
FROM EMPLOYEE, DEPARTMENT
WHERE Dname=‘Research’ AND Dnumber=Dno;
• Query1 Can be written with join: [It may be easier to specify the join of the
EMPLOYEE and DEPARTMENT relations first, and then to select the desired
tuples and attributes.]
SELECT Fname, Lname, Address
FROM (EMPLOYEE JOIN DEPARTMENT ON Dno=Dnumber)
WHERE Dname=‘Research’;
Joins
The attributes of such a table are all the attributes of the first table, EMPLOYEE, followed by
all the attributes of the second table, DEPARTMENT
Aruna Devi C (DSCASC) 63
More Complex SQL Queries (Cont.,)
• If the names of the join attributes are not the same in the base relations, it is
possible to rename the attributes so that they match, and then to apply
NATURAL JOIN.
• Query where the DEPARTMENT relation is renamed as DEPT and its attributes are renamed as Dname,
Dno (to match the name of the desired join attribute Dno in the EMPLOYEE table), Mssn, and Msdate.
The implied join condition for this NATURAL JOIN is EMPLOYEE.Dno=DEPT.Dno, because this is the
only pair of attributes with the same name after renaming:
• Query 1 can be also written as
Natural Join
SELECT Fname, Lname, Address
FROM (EMPLOYEE NATURAL JOIN
(DEPARTMENT AS DEPT (Dname, Dno, Mssn, Msdate)))
WHERE Dname=‘Research’;
Aruna Devi C (DSCASC) 64
More Complex SQL Queries (Cont.,)
• The default type of join in a joined table is called an inner join, where a tuple is
included in the result only if a matching tuple exists in the other relation.
• For example, in query, only employees who have a supervisor are included in the
result; an EMPLOYEE tuple whose value for Super_ssn is NULL is excluded. If
the user requires that all employees be included, an OUTER JOIN must be used
explicitly.
SELECT E.Lname AS Employee_name,
S.Lname AS Supervisor_name
FROM (EMPLOYEE AS E LEFT OUTER JOIN EMPLOYEE AS S
ON E.Super_ssn=S.Ssn);
2
Aruna Devi C (DSCASC) 65
More Complex SQL Queries (Cont.,)
In SQL, the options available for specifying joined tables include:
• INNER JOIN (only pairs of tuples that match the join condition are retrieved,
same as JOIN).
• LEFT OUTER JOIN (every tuple in the left table must appear in the result; if it
does not have a matching tuple, it is padded with NULL values for the attributes
of the right table).
• RIGHT OUTER JOIN (every tuple in the right table must appear in the result; if
it does not have a matching tuple, it is padded with NULL values for the
attributes of the left table), and FULL OUTER JOIN.
Aruna Devi C (DSCASC) 66
Joined Relations – Datasets for Examples
Relation loan
Relation borrower
Note: borrower information not available for L-260 and loan
information not available for L-155
Aruna Devi C (DSCASC) 67
Joined Relations – Examples
• loan inner join borrower on
loan.loan_number = borrower.loan_number
• loan left outer join borrower on
loan.loan_number = borrower.loan_number
Aruna Devi C (DSCASC) 68
Joined Relations – Examples
• loan natural inner join borrower
• loan natural right outer join borrower
Aruna Devi C (DSCASC) 69
Joined Relations – Examples
• loan full outer join borrower using (loan_number)
Find all customers who have either an account or a loan (but not both)
at the bank.
select customer_name
from (depositor natural full outer join borrower )
where account_number is null or loan_number is null
Aruna Devi C (DSCASC) 72
More Complex SQL Queries (Cont.,)
• Include COUNT, SUM, MAX, MIN, and AVG
Query: Find the maximum salary, the minimum salary, and the average salary
among all employees.
SELECT MAX(SALARY), MIN(SALARY), AVG(SALARY)
FROM EMPLOYEE
– Some SQL implementations may not allow more than one function in
the SELECT-clause
Aggregate Functions in SQL
Aruna Devi C (DSCASC) 73
More Complex SQL Queries (Cont.,)
Query: Find the maximum salary, the minimum salary, and the average salary
among employees who work for the 'Research' department.
SELECT MAX(SALARY), MIN(SALARY), AVG(SALARY)
FROM EMPLOYEE, DEPARTMENT
WHERE DNO=DNUMBER AND DNAME='Research'
Query: Retrieve the total number of employees in the company
Aggregate Functions in SQL
SELECT COUNT (*) FROM EMPLOYEE
SELECT COUNT (*) FROM EMPLOYEE, DEPARTMENT
WHERE DNO=DNUMBER AND DNAME='Research
Query: Retrieve the number of employees in the 'Research' department.
Aruna Devi C (DSCASC) 74
More Complex SQL Queries (Cont.,)
• In many cases, we want to apply the aggregate functions to subgroups of
tuples in a relation Each subgroup of tuples consists of the set of tuples that
have the same value for the grouping attribute(s)
• The function is applied to each subgroup independently
• SQL has a GROUP BY-clause for specifying the grouping attributes, which
must also appear in the SELECT-clause
Grouping: The GROUP BY and HAVING Clauses
Aruna Devi C (DSCASC) 75
More Complex SQL Queries (Cont.,)
Query: For each department, retrieve the department number, the number of
employees in the department, and their average salary.
SELECT DNO, COUNT (*), AVG (SALARY)
FROM EMPLOYEE
GROUP BY DNO
– In Query, the EMPLOYEE tuples are divided into groups--each group
having the same value for the grouping attribute DNO
– The COUNT and AVG functions are applied to each such group of tuples
separately
– The SELECT-clause includes only the grouping attribute and the functions
to be applied on each group of tuples
– A join condition can be used in conjunction with grouping
GROUP BY
Aruna Devi C (DSCASC) 76
More Complex SQL Queries (Cont.,)
• Query: For each project, retrieve the project number, project name, and the
number of employees who work on that project.
SELECT PNUMBER, PNAME, COUNT (*)
FROM PROJECT, WORKS_ON
WHERE PNUMBER=PNO
GROUP BY PNUMBER, PNAME
– In this case, the grouping and functions are applied after the joining of
the two relations
GROUP BY
Aruna Devi C (DSCASC) 77
More Complex SQL Queries (Cont.,)
• Sometimes we want to retrieve the values of these functions for only those
groups that satisfy certain conditions
• The HAVING-clause is used for specifying a selection condition on groups
(rather than on individual tuples).
Query: For each project on which more than two employees work , retrieve the
project number, project name, and the number of employees who work on that
project.
SELECT PNUMBER, PNAME, COUNT (*)
FROM PROJECT, WORKS_ON
WHERE PNUMBER=PNO
GROUP BY PNUMBER, PNAME
HAVING COUNT (*) > 2
Having Clause
Note:
predicates in the having clause are applied after the formation of groups
whereas predicates in the where clause are applied before forming groups.
Aruna Devi C (DSCASC) 78
Summary of SQL Queries
A query in SQL can consist of up to six clauses, but only the first two, SELECT and
FROM, are mandatory. The clauses are specified in the following order:
SELECT <attribute list>
FROM <table list>
[WHERE <condition>]
[GROUP BY <grouping attribute(s)>]
[HAVING <group condition>]
[ORDER BY <attribute list>]
Aruna Devi C (DSCASC) 79
Summary of SQL Queries (cont.,)
• The SELECT-clause lists the attributes or functions to be retrieved.
• The FROM-clause specifies all relations (or aliases) needed in the query but not
those needed in nested queries.
• The WHERE-clause specifies the conditions for selection and join of tuples from
the relations specified in the FROM-clause.
• GROUP BY specifies grouping attributes.
• HAVING specifies a condition for selection of groups.
• ORDER BY specifies an order (Ascending or Descending) for displaying the
result of a query.
• A query is evaluated by first applying the WHERE-clause, then GROUP BY and
HAVING, and finally the SELECT- clause.
Aruna Devi C (DSCASC) 80
Specifying Constraints as Assertions and Triggers
Specifying General Constraints as Assertions in SQL:
• General constraints: constraints that do not fit in the basic SQL categories.
• Mechanism: CREATE ASSERTION
– components include: a constraint name, followed by CHECK, followed by a
condition
• For example, to specify the constraint that the salary of an employee must not be
greater than the salary of the manager of the department that the employee works
for in SQL, we can write the following assertion:
Aruna Devi C (DSCASC) 81
Specifying Constraints as Assertions and Triggers (cont.,)
• The basic technique for writing such assertions is to specify a query that
selects any tuples that violate the desired condition.
• Example, the query selects all employees whose salaries are greater than the
salary of the manager of their department. If the result of the query is not
empty, the assertion is violated.
• On the other hand, the schema designer should use CREATE ASSERTION
only in cases where it is not possible to use CHECK on attributes, domains, or
tuples, so that simple checks are implemented more efficiently by the DBMS.
Aruna Devi C (DSCASC) 82
Specifying Constraints as Assertions and Triggers (cont.,)
• 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.
• For example, it may be useful to specify a condition that, if violated, causes
some user to be informed of the violation. A manager may want to be informed
if an employee’s travel expenses exceed a certain limit by receiving a message
whenever this occurs.
• The CREATE TRIGGER statement is used to implement such actions in SQL.
Triggers in SQL
Aruna Devi C (DSCASC) 83
Specifying Constraints as Assertions and Triggers (cont.,)
• A trigger to compare an employee’s salary to his/her supervisor during insert or
update operations:
• Several events can trigger this rule: inserting a new employee record, changing an
employee’s salary, or changing an employee’s supervisor.
• Suppose that the action to take would be to call an external stored procedure
SALARY_VIOLATION, which will notify the supervisor.
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 );
Triggers
Aruna Devi C (DSCASC) 84
Specifying Constraints as Assertions and Triggers (cont.,)
• The trigger is given the name SALARY_VIOLATION.
• 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 condition that determines whether the rule action should be executed:
Once the triggering event has occurred, an optional condition may be evaluated.
• 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
Aruna Devi C (DSCASC) 85
Views (Virtual Tables) in SQL
• A view is a “virtual” table that is derived from other tables.
• Allows for limited update operations (since the table may not physically be
stored).
• Allows full query operations.
• A convenience for expressing certain operations.
Aruna Devi C (DSCASC) 86
Views (Virtual Tables) in SQL (Cont.,)
Specification of Views:
SQL command: CREATE VIEW
– a table (view) name
– a possible list of attribute names (for example, when arithmetic operations
are specified or when we want the names to be different from the attributes
in the base relations)
– a query to specify the table contents
Aruna Devi C (DSCASC) 87
Views (Virtual Tables) in SQL (Cont.,)
Specify a different WORKS_ON table
SQL Views: An Example
CREATE VIEW WORKS_ON1
AS SELECT Fname, Lname, Pname, Hours
FROM EMPLOYEE, PROJECT, WORKS_ON
WHERE Ssn=Essn AND Pno=Pnumber;
Company Database
Aruna Devi C (DSCASC) 88
Views (Virtual Tables) in SQL (Cont.,)
Using a Virtual Table:
• We can specify SQL queries on a newly create table (view):
SELECT FNAME, LNAME FROM WORKS_ON1
WHERE PNAME=‘ProductX’;
• When no longer needed, a view can be dropped:
DROP WORKS_ON1;
Aruna Devi C (DSCASC) 89
Views (Virtual Tables) in SQL (Cont.,)
View Implementation:
• View materialization: involves physically creating and keeping a temporary table
– assumption: other queries on the view will follow
– concerns: maintaining correspondence between the base table and the view
when the base table is updated
– strategy: incremental update
View Update:
• Update on a single view without aggregate operations: update may map to an
update on the underlying base table
• Views involving joins: an update may map to an update on the underlying base
relations
– not always possible
Aruna Devi C (DSCASC) 90
Additional Features of SQL
• SQL has various techniques for writing programs in various programming
languages that include SQL statements to access one or more databases. These
include embedded (and dynamic) SQL, SQL/CLI (Call Level Interface) and its
predecessor ODBC (Open Data Base Connectivity), and SQL/PSM (Persistent
Stored Modules).
• Each commercial RDBMS will have, in addition to the SQL commands, a set of
commands for specifying physical database design parameters, file structures for
relations, and access paths such as indexes. We called these commands a storage
definition language (SDL).
• SQL has transaction control commands. These are used to specify units of
database processing for concurrency control and recovery purposes.
Aruna Devi C (DSCASC) 91
Additional Features of SQL (Cont.,)
• SQL has language constructs for specifying the granting and revoking of
privileges to users. Privileges typically correspond to the right to use certain
SQL commands to access certain relations.
• SQL has language constructs for creating triggers.
• SQL has incorporated many features from object-oriented models to have
more powerful capabilities, leading to enhanced relational systems known as
object-relational.
• SQL and relational databases can interact with new technologies such as
• XML and OLAP
----------------------------------
Aruna Devi C (DSCASC) 92
Database Programming: Techniques and Issues
• The majority of database interactions are executed through programs that have been
carefully designed and tested.
• These programs are generally known as application programs or database applications.
Approaches to Database Programming:
• Embedding database commands in a general-purpose programming language:
Database commands are embedded in a general-purpose programming language
• Using a library of database functions:
Available to the host language for database calls; known as an API (Application
Programming Interface)
• Designing a brand-new language:
A database programming language is designed from scratch to be compatible with
the database model and query language.
Aruna Devi C (DSCASC) 93
Database Programming: Techniques and Issues
When a programmer or software engineer writes a program that
requires access to a database, it is quite common for the program to be running on
one computer system while the database is installed on another.
When writing such a program, a common sequence of interaction is the
following:
1. When the client program requires access to a particular database, the program
must first establish or open a connection to the database server.
2. Once the connection is established, the program can interact with the database by
submitting queries, updates, and other database commands.
3. When the program no longer needs access to a particular database, it should
terminate or close the connection to the database.
Typical Sequence of Interaction in Database Programming
Aruna Devi C (DSCASC) 94
Embedded SQL, Dynamic SQL
• Most SQL statements can be embedded in a general-purpose host programming
language such as COBOL, C, Java.
Retrieving Single Tuples with Embedded SQL:
• An embedded SQL statement is distinguished from the host language
statements by EXEC SQL and a matching END-EXEC (or semicolon).
– shared variables (used in both languages) usually prefixed with a colon (:) in
SQL
• Suppose that we want to write C programs to process the COMPANY database.
• We need to declare program variables to match the types of the database
attributes that the program will process.
Aruna Devi C (DSCASC) 95
Embedded SQL, Dynamic SQL (Cont.,)
• Variables inside DECLARE are shared and can appear (while prefixed by a colon)
in SQL statements.
• SQLCODE is used to communicate errors/exceptions between the database and
the program
C program variables used in the
embedded SQL examples E1 and E2.
The C program variables
declared in lines 2
through 5 correspond
to the attributes of the
EMPLOYEE and
DEPARTMENT tables
from the
COMPANY database
The variables declared SQLCODE and
SQLSTATE—are used to communicate
errors and exception conditions between the
database system and the executing
program.
Aruna Devi C (DSCASC) 96
Embedded SQL, Dynamic SQL (Cont.,)
Connecting to the Database:
• The SQL command for establishing a connection to a database has the following
form:
CONNECT TO <server name>AS <connection name>
AUTHORIZATION <user account name and password> ;
• To change from the currently active connection to a different one by using the
following command:
SET CONNECTION <connection name> ;
• Once a connection is no longer needed, it can be terminated by the following
command:
DISCONNECT <connection name> ;
1
2
3
Aruna Devi C (DSCASC) 97
Embedded SQL, Dynamic SQL (Cont.,)
Example of Embedded SQL Programming:
• To illustrate embedded SQL programming is a repeating program segment
(loop) that takes as input a Social Security number of an employee and prints
some information from the corresponding EMPLOYEE record in the
database.
Aruna Devi C (DSCASC) 98
Embedded SQL, Dynamic SQL (Cont.,)
Example explanation –
• The program reads (inputs) an Ssn value and then retrieves the EMPLOYEE
tuple with that Ssn from the database via the embedded SQL command.
• The INTO clause (line 5) specifies the program variables into which attribute
values from the database record are retrieved.
Aruna Devi C (DSCASC) 99
Embedded SQL, Dynamic SQL (Cont.,)
Retrieving Multiple Tuples with Embedded SQL Using Cursors:
• We can think of a cursor as a pointer that points to a single tuple (row) from the
result of a query that retrieves multiple tuples.
• An OPEN CURSOR command fetches the query result from the database and
sets the cursor to a position before the first row in the result of the query.
• FETCH commands move the cursor to the next tuple.
• CLOSE CURSOR indicates that the processing of query results has been
completed
Aruna Devi C (DSCASC) 100
Embedded SQL, Dynamic SQL (Cont.,)
Specifying Queries at Runtime Using Dynamic SQL:
• Objective: executing new (not previously compiled) SQL statements at run-time
– a program accepts SQL statements from the keyboard at run-time
– a point-and-click operation translates to certain SQL query
• Dynamic update is relatively simple; dynamic query can be complex
– because the type and number of retrieved attributes are unknown at compile
time
Aruna Devi C (DSCASC) 101
Database Stored Procedures and SQL/PSM
Database Stored Procedures and Functions:
• Procedures / functions (modules) are stored locally and executed by the database
server (as opposed to execution by clients)
• Advantages:
– If the procedure is needed by many applications, it can be invoked by any of
them (thus reduce duplications)
– Execution by the server reduces communication costs
– Enhance the modeling power of views
Aruna Devi C (DSCASC) 102
Database Stored Procedures and SQL/PSM (Cont.,)
• Many commercial DBMS’s 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.
The general form of declaring stored procedures is as follows:
• A stored procedure:
CREATE PROCEDURE procedure-name (params)
local-declarations
procedure-body;
• A stored function:
CREATE FUNCTION fun-name (params) RETURNS return-type
local-declarations
function-body;
• Calling a procedure or function:
CALL procedure-name/fun-name (arguments);
Aruna Devi C (DSCASC) 103
Company Database
Q1
Q2

Contenu connexe

Tendances

Tendances (20)

R code for data manipulation
R code for data manipulationR code for data manipulation
R code for data manipulation
 
Chapter 6 relational data model and relational
Chapter  6  relational data model and relationalChapter  6  relational data model and relational
Chapter 6 relational data model and relational
 
The Relational Model
The Relational ModelThe Relational Model
The Relational Model
 
Basic sql Commands
Basic sql CommandsBasic sql Commands
Basic sql Commands
 
A must Sql notes for beginners
A must Sql notes for beginnersA must Sql notes for beginners
A must Sql notes for beginners
 
Object-Oriented Programming in Java.pdf
Object-Oriented Programming in Java.pdfObject-Oriented Programming in Java.pdf
Object-Oriented Programming in Java.pdf
 
CLASS & OBJECT IN JAVA
CLASS & OBJECT  IN JAVACLASS & OBJECT  IN JAVA
CLASS & OBJECT IN JAVA
 
Aggregate functions
Aggregate functionsAggregate functions
Aggregate functions
 
Ppt of dbms e r features
Ppt of dbms e r featuresPpt of dbms e r features
Ppt of dbms e r features
 
Presentation on Relational Schema (Database)
Presentation on Relational Schema (Database)Presentation on Relational Schema (Database)
Presentation on Relational Schema (Database)
 
Sql operator
Sql operatorSql operator
Sql operator
 
Chapter 4 Structured Query Language
Chapter 4 Structured Query LanguageChapter 4 Structured Query Language
Chapter 4 Structured Query Language
 
R programming Language
R programming LanguageR programming Language
R programming Language
 
SQL Queries Information
SQL Queries InformationSQL Queries Information
SQL Queries Information
 
SImple SQL
SImple SQLSImple SQL
SImple SQL
 
Relational algebra in dbms
Relational algebra in dbmsRelational algebra in dbms
Relational algebra in dbms
 
Chapter-4 Enhanced ER Model
Chapter-4 Enhanced ER ModelChapter-4 Enhanced ER Model
Chapter-4 Enhanced ER Model
 
SQL
SQLSQL
SQL
 
SQL
SQLSQL
SQL
 
8. sql
8. sql8. sql
8. sql
 

En vedette

Dbms ii mca-ch10-concurrency-control-2013
Dbms ii mca-ch10-concurrency-control-2013Dbms ii mca-ch10-concurrency-control-2013
Dbms ii mca-ch10-concurrency-control-2013Prosanta Ghosh
 
Dbms ii mca-ch12-security-2013
Dbms ii mca-ch12-security-2013Dbms ii mca-ch12-security-2013
Dbms ii mca-ch12-security-2013Prosanta Ghosh
 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming TechniquesRaji Ghawi
 
Dbms ii mca-ch3-er-model-2013
Dbms ii mca-ch3-er-model-2013Dbms ii mca-ch3-er-model-2013
Dbms ii mca-ch3-er-model-2013Prosanta Ghosh
 
Dbms ii mca-ch11-recovery-2013
Dbms ii mca-ch11-recovery-2013Dbms ii mca-ch11-recovery-2013
Dbms ii mca-ch11-recovery-2013Prosanta Ghosh
 
File organization
File organizationFile organization
File organizationGokul017
 
Dbms ii mca-ch1-ch2-intro-datamodel-2013
Dbms ii mca-ch1-ch2-intro-datamodel-2013Dbms ii mca-ch1-ch2-intro-datamodel-2013
Dbms ii mca-ch1-ch2-intro-datamodel-2013Prosanta Ghosh
 
Dbms ii mca-ch4-relational model-2013
Dbms ii mca-ch4-relational model-2013Dbms ii mca-ch4-relational model-2013
Dbms ii mca-ch4-relational model-2013Prosanta Ghosh
 
Dbms ii mca-ch9-transaction-processing-2013
Dbms ii mca-ch9-transaction-processing-2013Dbms ii mca-ch9-transaction-processing-2013
Dbms ii mca-ch9-transaction-processing-2013Prosanta Ghosh
 
Dbms ii mca-ch5-ch6-relational algebra-2013
Dbms ii mca-ch5-ch6-relational algebra-2013Dbms ii mca-ch5-ch6-relational algebra-2013
Dbms ii mca-ch5-ch6-relational algebra-2013Prosanta Ghosh
 
1. Introduction to DBMS
1. Introduction to DBMS1. Introduction to DBMS
1. Introduction to DBMSkoolkampus
 
Normalization of database_tables_chapter_4
Normalization of database_tables_chapter_4Normalization of database_tables_chapter_4
Normalization of database_tables_chapter_4Farhan Chishti
 
Database management system presentation
Database management system presentationDatabase management system presentation
Database management system presentationsameerraaj
 

En vedette (18)

Dbms ii mca-ch10-concurrency-control-2013
Dbms ii mca-ch10-concurrency-control-2013Dbms ii mca-ch10-concurrency-control-2013
Dbms ii mca-ch10-concurrency-control-2013
 
Dbms ii mca-ch12-security-2013
Dbms ii mca-ch12-security-2013Dbms ii mca-ch12-security-2013
Dbms ii mca-ch12-security-2013
 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming Techniques
 
Dbms ii mca-ch3-er-model-2013
Dbms ii mca-ch3-er-model-2013Dbms ii mca-ch3-er-model-2013
Dbms ii mca-ch3-er-model-2013
 
Normalization case
Normalization caseNormalization case
Normalization case
 
Dbms ii mca-ch11-recovery-2013
Dbms ii mca-ch11-recovery-2013Dbms ii mca-ch11-recovery-2013
Dbms ii mca-ch11-recovery-2013
 
File organization
File organizationFile organization
File organization
 
Dbms ii mca-ch1-ch2-intro-datamodel-2013
Dbms ii mca-ch1-ch2-intro-datamodel-2013Dbms ii mca-ch1-ch2-intro-datamodel-2013
Dbms ii mca-ch1-ch2-intro-datamodel-2013
 
Dbms ii mca-ch4-relational model-2013
Dbms ii mca-ch4-relational model-2013Dbms ii mca-ch4-relational model-2013
Dbms ii mca-ch4-relational model-2013
 
Dbms ii mca-ch9-transaction-processing-2013
Dbms ii mca-ch9-transaction-processing-2013Dbms ii mca-ch9-transaction-processing-2013
Dbms ii mca-ch9-transaction-processing-2013
 
Dbms ii mca-ch5-ch6-relational algebra-2013
Dbms ii mca-ch5-ch6-relational algebra-2013Dbms ii mca-ch5-ch6-relational algebra-2013
Dbms ii mca-ch5-ch6-relational algebra-2013
 
1. Introduction to DBMS
1. Introduction to DBMS1. Introduction to DBMS
1. Introduction to DBMS
 
Data Base Management System
Data Base Management SystemData Base Management System
Data Base Management System
 
Normalization of database_tables_chapter_4
Normalization of database_tables_chapter_4Normalization of database_tables_chapter_4
Normalization of database_tables_chapter_4
 
File organization
File organizationFile organization
File organization
 
Data integrity
Data integrityData integrity
Data integrity
 
Dbms slides
Dbms slidesDbms slides
Dbms slides
 
Database management system presentation
Database management system presentationDatabase management system presentation
Database management system presentation
 

Similaire à Dbms ii mca-ch7-sql-2013

DBMS MODULE 3 NOTES ENGINEERING CSE .pdf
DBMS MODULE 3 NOTES ENGINEERING CSE .pdfDBMS MODULE 3 NOTES ENGINEERING CSE .pdf
DBMS MODULE 3 NOTES ENGINEERING CSE .pdfraki082m
 
Database COMPLETE
Database COMPLETEDatabase COMPLETE
Database COMPLETEAbrar ali
 
Chapter 7 relation database language
Chapter 7 relation database languageChapter 7 relation database language
Chapter 7 relation database languageJafar Nesargi
 
Chapter 7 relation database language
Chapter 7 relation database languageChapter 7 relation database language
Chapter 7 relation database languageJafar Nesargi
 
Relational database language
Relational database languageRelational database language
Relational database languageJafar Nesargi
 
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 knowPavithSingh
 
Structure query language (sql)
Structure query language (sql)Structure query language (sql)
Structure query language (sql)Nalina Kumari
 
Chapter 7 relation database language
Chapter 7 relation database languageChapter 7 relation database language
Chapter 7 relation database languageJafar Nesargi
 
Steps towards of sql server developer
Steps towards of sql server developerSteps towards of sql server developer
Steps towards of sql server developerAhsan Kabir
 
Structure Query Language (SQL).pptx
Structure Query Language (SQL).pptxStructure Query Language (SQL).pptx
Structure Query Language (SQL).pptxNalinaKumari2
 
chapter9-SQL.pptx
chapter9-SQL.pptxchapter9-SQL.pptx
chapter9-SQL.pptxYaser52
 

Similaire à Dbms ii mca-ch7-sql-2013 (20)

DBMS MODULE 3 NOTES ENGINEERING CSE .pdf
DBMS MODULE 3 NOTES ENGINEERING CSE .pdfDBMS MODULE 3 NOTES ENGINEERING CSE .pdf
DBMS MODULE 3 NOTES ENGINEERING CSE .pdf
 
Module02
Module02Module02
Module02
 
Assignment#01
Assignment#01Assignment#01
Assignment#01
 
SQL Commands
SQL Commands SQL Commands
SQL Commands
 
Database COMPLETE
Database COMPLETEDatabase COMPLETE
Database COMPLETE
 
12 SQL
12 SQL12 SQL
12 SQL
 
12 SQL
12 SQL12 SQL
12 SQL
 
Lab
LabLab
Lab
 
Chapter 7 relation database language
Chapter 7 relation database languageChapter 7 relation database language
Chapter 7 relation database language
 
Chapter 7 relation database language
Chapter 7 relation database languageChapter 7 relation database language
Chapter 7 relation database language
 
Relational database language
Relational database languageRelational database language
Relational database language
 
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
 
Structure query language (sql)
Structure query language (sql)Structure query language (sql)
Structure query language (sql)
 
Chapter 7 relation database language
Chapter 7 relation database languageChapter 7 relation database language
Chapter 7 relation database language
 
Steps towards of sql server developer
Steps towards of sql server developerSteps towards of sql server developer
Steps towards of sql server developer
 
Structure Query Language (SQL).pptx
Structure Query Language (SQL).pptxStructure Query Language (SQL).pptx
Structure Query Language (SQL).pptx
 
chapter9-SQL.pptx
chapter9-SQL.pptxchapter9-SQL.pptx
chapter9-SQL.pptx
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
Sql server
Sql serverSql server
Sql server
 
Ankit
AnkitAnkit
Ankit
 

Dernier

%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024VictoriaMetrics
 
tonesoftg
tonesoftgtonesoftg
tonesoftglanshi9
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Hararemasabamasaba
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...masabamasaba
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 

Dernier (20)

%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 

Dbms ii mca-ch7-sql-2013

  • 1. Aruna Devi C (DSCASC) 1 SQL Chapter 7 Unit IV Data Base Management System [DBMS]
  • 2. Aruna Devi C (DSCASC) 2 SQL • The name SQL is presently expanded as Structured Query Language. • Originally, SQL was called SEQUEL (Structured English QUEry Language) and was designed and implemented at IBM Research as the interface for an experimental relational database system called SYSTEM R. • SQL is now the standard language for commercial relational DBMSs.
  • 3. Aruna Devi C (DSCASC) 3 History - SQL IBM Sequel language developed as part of System R project at the IBM San Jose Research Laboratory. Renamed as Structured Query Language (SQL) ANSI and ISO standard SQL: * SQL-86 * SQL-89 * SQL-92 * SQL:1999 (language name became Y2K compliant!) * SQL:2003 * SQL:2006 ( XML features) * SQL:2008 (Object Database features) SQL is based on set and relational operations with certain modifications and enhancements. SQL is not case sensitive.
  • 4. Aruna Devi C (DSCASC) 4 SQL Data Definition and Data Types • SQL uses the terms table, row, and column for the formal relational model terms relation, tuple, and attribute, respectively. • SQL command for data definition is the CREATE statement, which can be used to create schemas, tables (relations), and domains (as well as other constructs such as views, assertions, and triggers). Schema and Catalog Concepts in SQL: • An SQL schema is identified by a schema name, and includes an authorization identifier to indicate the user or account who owns the schema, as well as descriptors for each element in the schema. • Schema elements include tables, constraints, views, domains, and other constructs (such as authorization grants) that describe the schema.
  • 5. Aruna Devi C (DSCASC) 5 SQL Data Definition and Data Types (cont.,) • A schema is created via the CREATE SCHEMA statement, which can include all the schema elements’ definitions. • The following statement creates a schema called COMPANY, owned by the user with authorization identifier ‘Jsmith’. • Note that each statement in SQL ends with a semicolon. CREATE SCHEMA COMPANY AUTHORIZATION ‘Jsmith’;
  • 6. Aruna Devi C (DSCASC) 6 SQL Data Definition and Data Types (cont.,) • SQL uses the concept of a catalog—a named collection of schemas in an SQL environment. • An SQL environment is basically an installation of an SQL-compliant RDBMS on a computer system. • A catalog always contains a special schema called INFORMATION_SCHEMA, which provides information on all the schemas in the catalog and all the element descriptors in these schemas.
  • 7. Aruna Devi C (DSCASC) 7 SQL SQL can be divided into two parts: * Data Definition Language (DDL) * Data Manipulation Language (DML) DDL: The DDL part of SQL permits database tables to be created or deleted. It also define indexes (keys), specify links between tables, and impose constraints between tables. The most important DDL statements in SQL are: » CREATE TABLE - creates a new table » ALTER TABLE - modifies a table » DROP TABLE - deletes a table DML: The query and update commands form the DML part of SQL: » SELECT - extracts data from a database » UPDATE - updates data in a database » DELETE - deletes data from a database » INSERT INTO - inserts new data into a database
  • 8. Aruna Devi C (DSCASC) 8 SQL Data Definition and Data Types (cont.,) The CREATE TABLE Command in SQL: The CREATE TABLE command is used to specify a new relation by giving it a name and specifying its attributes and initial constraints. • An SQL relation is defined using the create table command: create table r (A1 D1, A2 D2, ..., An Dn, (integrity-constraint1), ...) – r is the name of the relation – each Ai is an attribute name in the schema of relation r – Di is the data type of values in the domain of attribute Ai • Example: create table branch (branch_name char(15) not null, branch_city char(30), assets integer)
  • 9. Aruna Devi C (DSCASC) 9 SQL Data Definition and Data Types (cont.,) The CREATE TABLE Command in SQL: (Cont.,)
  • 10. Aruna Devi C (DSCASC) 10 SQL Data Definition and Data Types (cont.,) The CREATE TABLE Command in SQL: (Cont.,)
  • 11. Aruna Devi C (DSCASC) 11 SQL Data Definition and Data Types (cont.,) The CREATE TABLE Command in SQL: (Cont.,)
  • 12. Aruna Devi C (DSCASC) 12 Company Database
  • 13. Aruna Devi C (DSCASC) 13 Attribute Data Types and Domains in SQL: The basic data types available for attributes include numeric, character string, bit string, Boolean, date, and time. Numeric data types: • Integer numbers of various sizes (INTEGER or INT, and SMALLINT) and floating-point (real) numbers of various precision (FLOAT or REAL, and DOUBLE PRECISION). • Formatted numbers can be declared by using DECIMAL(i,j)—or DEC(i,j) or NUMERIC(i,j)— where i, the precision, is the total number of decimal digits. Character-string data types: • Fixed length — CHAR(n) or CHARACTER(n), where n is the number of characters. • Varying length— VARCHAR(n) or CHAR VARYING(n) or CHARACTER VARYING(n), where n is the maximum number of characters. Note: A literal string value is placed between single quotation marks and it is case sensitive SQL Data Definition and Data Types (cont.,)
  • 14. Aruna Devi C (DSCASC) 14 Attribute Data Types and Domains in SQL (cont.,) CLOB data type: • CLOB is to specify columns that have large text values, such as documents. • The CLOB maximum length can be specified in kilobytes (K), megabytes (M), or gigabytes (G). • For example, CLOB(20M) specifies a maximum length of 20 megabytes. Bit-string data types: • Bit string are either of fixed length n—BIT(n)—or varying length—BIT VARYING(n), where n is the maximum number of bits. BLOB data type: • The default for n, the length of a character string or bit string, is 1. • BLOB is also available to specify columns that have large binary values, such as images. • The BLOB maximum length can be specified in kilobits (K), megabits (M), or gigabits (G). • For example, BLOB(30G) specifies a maximum length of 30 gigabits. SQL Data Definition and Data Types (cont.,)
  • 15. Aruna Devi C (DSCASC) 15 Attribute Data Types and Domains in SQL (cont.,) Boolean data type: It has the traditional values of TRUE or FALSE. DATE data type: It has ten positions, and its components are YEAR, MONTH, and DAY in the form YYYY-MM-DD. TIME data type: It has at least eight positions, with the components HOUR, MINUTE, and SECOND in the form HH:MM:SS. Timestamp data type: TIMESTAMP includes the DATE and TIME fields, plus a minimum of six positions for decimal fractions of seconds and an optional WITH TIME ZONE qualifier. ------------------ SQL Data Definition and Data Types (cont.,)
  • 16. Aruna Devi C (DSCASC) 16 Specifying Constraints in SQL • SQL allows NULLs as attribute values, a constraint NOT NULL may be specified if NULL is not permitted for a particular attribute. • It is also possible to define a default value for an attribute by appending the clause DEFAULT <value> to an attribute definition. • Constraint can restrict attribute or domain values using the CHECK clause following an attribute or domain definition. Dnumber INT NOT NULL CHECK (Dnumber > 0 AND Dnumber < 21);
  • 17. Aruna Devi C (DSCASC) 17 Specifying Key and Referential Integrity Constraints: • The PRIMARY KEY clause specifies one or more attributes that make up the primary key of a relation. • If a primary key has a single attribute, the clause can follow the attribute directly. • The UNIQUE clause specifies alternate (secondary) keys. Dname VARCHAR(15) UNIQUE • Referential integrity is specified via the FOREIGN KEY clause. Specifying Constraints in SQL (Cont.,)
  • 18. Aruna Devi C (DSCASC) 18 Specifying Key and Referential Integrity Constraints (cont.,): • A referential integrity constraint can be violated when tuples are inserted or deleted, or when a foreign key or primary key attribute value is modified. • The default action that SQL takes for an integrity violation is to reject the update operation that will cause a violation, which is known as the RESTRICT option. • However, the schema designer can specify an alternative action to be taken by attaching a referential triggered action clause to any foreign key constraint. • The options include SET NULL, CASCADE, and SET DEFAULT. • An option must be qualified with either ON DELETE or ON UPDATE. Specifying Constraints in SQL (Cont.,)
  • 19. Aruna Devi C (DSCASC) 19 Specifying Key and Referential Integrity Constraints (cont.,) Example: • The database designer chooses ON DELETE SET NULL and ON UPDATE CASCADE for the foreign key Super_ssn of EMPLOYEE. • This means that if the tuple for a supervising employee is deleted, the value of Super_ssn is automatically set to NULL for all employee tuples that were referencing the deleted employee tuple. • On the other hand, if the Ssn value for a supervising employee is updated (say, because it was entered incorrectly), the new value is cascaded to Super_ssn for all employee tuples referencing the updated employee tuple. • The action for CASCADE ON DELETE is to delete all the referencing tuples. • The action for CASCADE ON UPDATE is to change the value of the referencing foreign key attribute(s) to the updated (new) primary key value for all the referencing tuples.
  • 20. Aruna Devi C (DSCASC) 20 Specifying Key and Referential Integrity Constraints (cont.,) • We can specify RESTRICT, CASCADE, SET NULL or SET DEFAULT on referential integrity constraints (foreign keys) CREATE TABLE DEPT ( DNAME VARCHAR(10) NOT NULL, DNUMBER INTEGER NOT NULL, MGRSSN CHAR(9), MGRSTARTDATE CHAR(9), PRIMARY KEY (DNUMBER), UNIQUE (DNAME), FOREIGN KEY (MGRSSN) REFERENCES EMP ON DELETE SET DEFAULT ON UPDATE CASCADE );
  • 21. Aruna Devi C (DSCASC) 21 Specifying Key and Referential Integrity Constraints (cont.,) CREATE TABLE EMP ( ENAME VARCHAR(30) NOT NULL, ESSN CHAR(9), BDATE DATE, DNO INTEGER DEFAULT 1, SUPERSSN CHAR(9), PRIMARY KEY (ESSN), FOREIGN KEY (DNO) REFERENCES DEPT ON DELETE SET DEFAULT ON UPDATE CASCADE, FOREIGN KEY (SUPERSSN) REFERENCES EMP ON DELETE SET NULL ON UPDATE CASCADE );
  • 22. Aruna Devi C (DSCASC) 22 Specifying Constraints in SQL (Cont.,) Giving Names to Constraints: • A constraint name is used to identify a particular constraint in case the constraint must be dropped later and replaced with another constraint. Specifying Constraints on Tuples Using CHECK: • CHECK clauses at the end of a CREATE TABLE statement. • These can be called tuple-based constraints because they apply to each tuple individually and are checked whenever a tuple is inserted or modified. CHECK (Dept_create_date <= Mgr_start_date);
  • 23. Aruna Devi C (DSCASC) 23 Schema Change Statement in SQL Schema Change Statement in SQL, which can be used to alter a schema by adding or dropping tables, attributes, constraints, and other schema elements. 1) DROP Command. 2) The ALTER Command.
  • 24. Aruna Devi C (DSCASC) 24 Schema Change Statement in SQL (Cont.,) DROP Command: The DROP command can be used to drop named schema elements, such as tables, domains, or constraints. There are two drop behavior options: CASCADE and RESTRICT. For example, to remove the COMPANY database schema and all its tables, domains, and other elements, the CASCADE option is used as follows: DROP SCHEMA COMPANY CASCADE;
  • 25. Aruna Devi C (DSCASC) 25 Schema Change Statement in SQL (Cont.,) • If the RESTRICT option is chosen in place of CASCADE, the schema is dropped only if it has no elements in it; otherwise, the DROP command will not be executed. • If a base relation within a schema is no longer needed, the relation and its definition can be deleted by using the DROP TABLE command. • If the RESTRICT option is chosen instead of CASCADE, a table is dropped only if it is not referenced in any constraints. • With the CASCADE option, all such constraints, views, and other elements that reference the table being dropped are also dropped automatically from the schema, along with the table itself. • The DROP TABLE command not only deletes all the records in the table successful, but also removes the table definition from the catalog. DROP TABLE DEPENDENT CASCADE;
  • 26. Aruna Devi C (DSCASC) 26 Schema Change Statement in SQL (Cont.,) The ALTER Command: The definition of a base table or of other named schema elements can be changed by using the ALTER command. • The possible alter table actions: 1) Add 2)Drop a column (attribute) 3) Alter (or changing) a column definition • To Add a column Syntax: Alter Table <tablename> Add Column A D ALTER TABLE COMPANY.EMPLOYEE ADD COLUMN Job VARCHAR(12); • If no default clause is specified, the new attribute will have NULL in all the tuples of the relation immediately after the command is executed; hence, the NOT NULL constraint is not allowed in this case.
  • 27. Aruna Devi C (DSCASC) 27 Schema Change Statement in SQL (Cont.,) • To drop a column, we must choose either CASCADE or RESTRICT for drop behavior. Syntax: • Alter Table <tablename> Drop Column A cascade; ALTER TABLE COMPANY.EMPLOYEE DROP COLUMN Address CASCADE; • It is also possible to alter a column definition by dropping an existing default clause or by defining a new default clause. Syntax: Alter Table <tablename> Alter Column A D ALTER TABLE COMPANY.DEPARTMENT ALTER COLUMN Mgr_ssn Varchar2;
  • 28. Aruna Devi C (DSCASC) 28 Basic Retrieval Queries in SQL Basic statement for retrieving information from a database is the SELECT statement. The SELECT-FROM-WHERE Structure of Basic SQL Queries: where • <attribute list> is a list of attribute names whose values are to be retrieved by • the query. • <table list> is a list of the relation names required to process the query. • <condition> is a conditional (Boolean) expression that identifies the tuples to be retrieved by the query. SELECT <attribute list> FROM <table> WHERE <condition>;
  • 29. Aruna Devi C (DSCASC) 29 Basic Retrieval Queries in SQL (Cont.,) • The basic logical comparison operators for comparing attribute values with one another and with literal constants are =, <, <=, >, >=, and <>. Query 1: Retrieve the birth date and address of the employee(s) whose name is John B. Smith’. SELECT Bdate, Address FROM EMPLOYEE WHERE Fname=‘John’ AND Minit=‘B’ AND Lname=‘Smith’; 1 Result: Company Database
  • 30. Aruna Devi C (DSCASC) 30 Basic Retrieval Queries in SQL (Cont.,) Query 2: Retrieve the name and address of all employees who work for the ‘Research’ department. SELECT Fname, Lname, Address FROM EMPLOYEE, DEPARTMENT WHERE Dname=‘Research’ AND Dnumber=Dno; Result: 2 Company Database
  • 31. Aruna Devi C (DSCASC) 31 Basic Retrieval Queries in SQL (Cont.,) Query 3: For every project located in ‘Stafford’, list the project number, the controlling department number, and the department manager’s last name, address, and birth date. SELECT Pnumber, Dnum, Lname, Address, Bdate FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE Dnum=Dnumber AND Mgr_ssn=Ssn AND Plocation=‘Stafford’; Result: 3 Company Database
  • 32. Aruna Devi C (DSCASC) 32 Basic Retrieval Queries in SQL (Cont.,) Ambiguous Attribute Names, Aliasing, Renaming, and Tuple Variables: • In SQL, we can use the same name for two (or more) attributes as long as the attributes are in different relations. • A query that refers to two or more attributes with the same name must qualify the attribute name with the relation name by prefixing the relation name to the attribute name. SELECT Fname, EMPLOYEE.Name, Address FROM EMPLOYEE, DEPARTMENT WHERE DEPARTMENT.Name=‘Research’ AND DEPARTMENT.Dnumber=EMPLOYEE.Dnumber;
  • 33. Aruna Devi C (DSCASC) 33 Basic Retrieval Queries in SQL (Cont.,) 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; Result: • E and S, called aliases or tuple variables, for the EMPLOYEE relation. An alias can follows the keyword AS (or) it can directly follow the relation name. • EMPLOYEE AS E(Fn, Mi, Ln, Ssn, Bd, Addr, Sex, Sal, Sssn, Dno) in the FROM clause, Fn becomes an alias for Fname, Mi for Minit, Ln for Lname, and so on. Aliasing Company Database
  • 34. Aruna Devi C (DSCASC) 34 Basic Retrieval Queries in SQL (Cont.,) • To retrieve all the attribute values of the selected tuples, we do not have to list the attribute names explicitly in SQL; we just specify an asterisk (*), which stands for all the attributes. SELECT * FROM EMPLOYEE WHERE Dno=5; Company Database USE OF *
  • 35. Aruna Devi C (DSCASC) 35 Basic Retrieval Queries in SQL (Cont.,) • If we do want to eliminate duplicate tuples from the result of an SQL query, we use the keyword DISTINCT in the SELECT clause, meaning that only distinct tuples should remain in the result. Query: a)Retrieve the salary of every employee, b) Retrieve all distinct salary values. SELECT ALL Salary FROM EMPLOYEE; SELECT DISTINCT Salary FROM EMPLOYEE; Company Database DISTINCT
  • 36. Aruna Devi C (DSCASC) 36 Basic Retrieval Queries in SQL (Cont.,) • SQL has directly incorporated some set operations. • There is a union operation (UNION), and in some versions of SQL there are set difference (MINUS) and intersection (INTERSECT) operations. • The resulting relations of these set operations are sets of tuples; duplicate tuples are eliminated from the result. • The set operations apply only to union compatible relations ; the two relations must have the same attributes and the attributes must appear in the same order SET OPERATIONS:
  • 37. Aruna Devi C (DSCASC) 37 Basic Retrieval Queries in SQL (Cont.,) • Make a list of all project numbers for projects that involve an employee whose last name is ‘Smith’, either as a worker or as a manager of the department that controls the project. SET OPERATIONS (Cont.,) The first SELECT query retrieves the projects that involve a ‘Smith’ as manager of the department that controls the project, and the second retrieves the projects that involve a ‘Smith’ as a worker on the project.
  • 38. Aruna Devi C (DSCASC) 38 Aruna Devi.C (DSCASC) 38 Set Operations • Find all customers who have a loan, an account, or both: (select customer-name from depositor) except (select customer-name from borrower) (select customer-name from depositor) intersect (select customer-name from borrower) Find all customers who have an account but no loan. (select customer-name from depositor) union (select customer-name from borrower) Find all customers who have both a loan and an account. TS∪S T S union T TS∩S T S intersect T TSS - T S minus T Basic Retrieval Queries in SQL (Cont.,)
  • 39. Aruna Devi C (DSCASC) 39 Basic Retrieval Queries in SQL (Cont.,) • SQL includes a string-matching operator for comparisons on character strings. • Patterns are described using two special characters: – percent (%) The % character matches any substring. – underscore (_) The _ character matches any character. percent (%) select cname from customer where street like ‘%Main%’ Underscore(_) ”---” matches any string of exactly three character. “---%” matches any string of atleast three character. Escape Keyword: It is use when the special pattern like % and _ is in the data, It is treated like normal character. like ‘ab%cd%’ escape matches all string beginning with ‘ab%cd’ Eg:select cname from customer where cstreet like ‘%Nagar%’ select cname from customer where cstreet like ‘Jaya%’ select cname from customer where ccity like ‘%lore%’ select cname from customer where cname like ‘_ _ _ _’ Substring Pattern Matching and Arithmetic Operators
  • 40. Aruna Devi C (DSCASC) 40 Basic Retrieval Queries in SQL (Cont.,) • The standard arithmetic operators '+', '-'. '*', and '/' (for addition, subtraction, multiplication, and division, respectively) can be applied to numeric values in an SQL query result. Query: Show the resulting salaries if every employee working on the ‘ProductX’ project is given a 10 percent raise. SELECT E.Fname, E.Lname, 1.1 * E.Salary AS Increased_sal FROM EMPLOYEE AS E, WORKS_ON AS W, PROJECT AS P WHERE E.Ssn=W.Essn AND W.Pno=P.Pnumber AND P.Pname=‘ProductX’; Arithmetic Operators
  • 41. Aruna Devi C (DSCASC) 41 Basic Retrieval Queries in SQL (Cont.,) • Comparison operator, which can be used for convenience, is BETWEEN. Query: Retrieve all employees in department 5 whose salary is between $30,000 and $40,000. comparison operator SELECT * FROM EMPLOYEE WHERE (Salary BETWEEN 30000 AND 40000) AND Dno = 5; The condition (Salary BETWEEN 30000 AND 40000) in Query is equivalent to the condition ((Salary >= 30000) AND (Salary <= 40000)).
  • 42. Aruna Devi C (DSCASC) 42 Basic Retrieval Queries in SQL (Cont.,) • The ORDER BY clause is used to sort the tuples in a query result based on the values of some attribute(s). Retrieve a list of employees and the projects they are working on, ordered by department and, within each department, ordered alphabetically by last name, then first name. SELECT D.Dname, E.Lname, E.Fname, P.Pname FROM DEPARTMENT D, EMPLOYEE E, WORKS_ON W, PROJECT P WHERE D.Dnumber= E.Dno AND E.Ssn= W.Essn AND W.Pno= P.Pnumber ORDER BY D.Dname, E.Lname, E.Fname; ORDER BY We can specify the keyword DESC if we want to see the result in a descending order of values. The keyword ASC can be used to specify ascending order explicitly
  • 43. Aruna Devi C (DSCASC) 43 INSERT, DELETE, and UPDATE Statements in SQL • In its simplest form, it is used to add one or more tuples to a relation. • Attribute values should be listed in the same order as the attributes were specified in the CREATE TABLE command. INSERT INTO EMPLOYEE VALUES ( ‘Richard’, ‘K’, ‘Marini’, ‘653298653’, ‘1962-12-30’, ‘98 Oak Forest, Katy, TX’, ‘M’, 37000, ‘653298653’, 4 ); INSERT A second form of the INSERT statement allows the user to specify explicit attribute names that correspond to the values provided in the INSERT command. INSERT INTO EMPLOYEE (Fname, Lname, Dno, Ssn) VALUES (‘Richard’, ‘Marini’, 4, ‘653298653’); Attributes not specified in query are set to their DEFAULT or to NULL.
  • 44. Aruna Devi C (DSCASC) 44 INSERT, DELETE, and UPDATE Statements in SQL (Cont.,) • To remove tuples from a relation. • Includes a WHERE-clause to select the tuples to be deleted. • Tuples are deleted from only one table at a time (unless CASCADE is specified on a referential integrity constraint). • A missing WHERE-clause specifies that all tuples in the relation are to be deleted; the table then becomes an empty table. • The number of tuples deleted depends on the number of tuples in the relation that satisfy the WHERE-clause. • Referential integrity should be enforced DELETE
  • 45. Aruna Devi C (DSCASC) 45 INSERT, DELETE, and UPDATE Statements in SQL (Cont.,) DELETE FROM EMPLOYEE WHERE Lname=‘Brown’; DELETE DELETE FROM EMPLOYEE WHERE Ssn=‘123456789’; DELETE FROM EMPLOYEE;
  • 46. Aruna Devi C (DSCASC) 46 INSERT, DELETE, and UPDATE Statements in SQL (Cont.,) • Update is used to modify attribute values of one or more selected tuples. • A WHERE-clause selects the tuples to be modified. • An additional SET-clause specifies the attributes to be modified and their new values. • Each command modifies tuples in the same relation. • Referential integrity should be enforced. UPDATE
  • 47. Aruna Devi C (DSCASC) 47 INSERT, DELETE, and UPDATE Statements in SQL (Cont.,) Change the location and controlling department number of project number 10 to 'Bellaire' and 5, respectively. UPDATE PROJECT SET Plocation = ‘Bellaire’, Dnum = 5 WHERE Pnumber=10; UPDATE ---------------------------------------- Company Database
  • 48. Aruna Devi C (DSCASC) 48 More Complex SQL Queries • SQL has various rules for dealing with NULL values. • NULL is used to represent a missing value. • That it usually has one of three different interpretations: 1. Value unknown (exists but is not known). 2. Value not available (exists but is purposely withheld). 3. Value not applicable (the attribute is undefined for this tuple). Example: • Unknown value: A person’s date of birth is not known, so it is represented by NULL in the database. • Unavailable or withheld value: A person has a home phone but does not want it to be listed, so it is withheld and represented as NULL in the database. • Not applicable attribute: An attribute LastCollegeDegree would be NULL for a person who has no college degrees because it does not apply to that person. Comparisons Involving NULL and Three-Valued Logic
  • 49. Aruna Devi C (DSCASC) 49 More Complex SQL Queries (Cont.,) Nested queries: • A complete SELECT query, called a nested query , can be specified within the WHERE-clause of another query, called the outer query. • Many of the previous queries can be specified in an alternative form using nesting. Query: Retrieve the name and address of all employees who work for the 'Research' department. Nested Queries, Tuples, and Set/Multiset Comparisons SELECT FNAME, LNAME, ADDRESS FROM EMPLOYEE WHERE DNO IN (SELECT DNUMBER FROM DEPARTMENT WHERE DNAME='Research' )
  • 50. Aruna Devi C (DSCASC) 50 More Complex SQL Queries (Cont.,) Nested queries: • The nested query selects the number of the 'Research' department. • The outer query select an EMPLOYEE tuple if its DNO value is in the result of either nested query. • The comparison operator IN compares a value v with a set (or multi-set) of values V, and evaluates to TRUE if v is one of the elements in V. • In general, we can have several levels of nested queries. • A reference to an unqualified attribute refers to the relation declared in the innermost nested query. • In this example, the nested query is not correlated with the outer query.
  • 51. Aruna Devi C (DSCASC) 51 More Complex SQL Queries (Cont.,) Comparison operators: • In addition to the IN operator, a number of other comparison operators can be used to compare a single value v. • The = ANY (or = SOME) operator returns TRUE if the value v is equal to some value in the set V and is hence equivalent to IN. • The two keywords ANY and SOME have the same effect. Other operators that can be combined with ANY (or SOME) include >, >=, <, <=, and <>. • The keyword ALL can also be combined with each of these operators. • For example, the comparison condition (v > ALL V) returns TRUE if the value v is greater than all the values in the set (or multiset) V.
  • 52. Aruna Devi C (DSCASC) 52 More Complex SQL Queries (Cont.,) Query: Return the names of employees whose salary is greater than the salary of all the employees in department 5. SELECT Lname, Fname FROM EMPLOYEE WHERE Salary > ALL ( SELECT Salary FROM EMPLOYEE WHERE Dno=5 ); Company Database
  • 53. Aruna Devi C (DSCASC) 53 More Complex SQL Queries (Cont.,) Query : Retrieve the name of each employee who has a dependent with the same first name and is the same sex as the employee. In the nested query, we must qualify E.Sex because it refers to the Sex attribute of EMPLOYEE from the outer query, and DEPENDENT also has an attribute called Sex. If there were any unqualified references to Sex in the nested query, they would refer to the Sex attribute of DEPENDENT. However, we would not have to qualify the attributes Fname and Ssn of EMPLOYEE if they appeared in the nested query because the DEPENDENT relation does not have attributes called Fname and Ssn, so there is no ambiguity.
  • 54. Aruna Devi C (DSCASC) 54 More Complex SQL Queries (Cont.,) • If a condition in the WHERE-clause of a nested query references an attribute of a relation declared in the outer query , the two queries are said to be correlated. • The result of a correlated nested query is different for each tuple (or combination of tuples) of the relation(s) the outer query. Query: Retrieve the name of each employee who has a dependent with the same first name as the employee. Correlated Nested Queries SELECT E.FNAME, E.LNAME FROM EMPLOYEE AS E WHERE E.SSN IN (SELECT ESSN FROM DEPENDENT WHERE ESSN=E.SSN AND E.FNAME=DEPENDENT_NAME)
  • 55. Aruna Devi C (DSCASC) 55 More Complex SQL Queries (Cont.,) • EXISTS is used to check whether the result of a correlated nested query is empty (contains no tuples) or not Query 12: Retrieve the name of each employee who has a dependent with the same first name as the employee. EXISTS Functions in SQL SELECT FNAME, LNAME FROM EMPLOYEE WHERE EXISTS (SELECT * FROM DEPENDENT WHERE SSN=ESSN AND FNAME=DEPENDENT_NAME)
  • 56. Aruna Devi C (DSCASC) 56 More Complex SQL Queries (Cont.,) Query: Retrieve the names of employees who have no dependents. SELECT FNAME, LNAME FROM EMPLOYEE WHERE NOT EXISTS (SELECT * FROM DEPENDENT WHERE SSN=ESSN) The correlated nested query retrieves all DEPENDENT tuples related to an EMPLOYEE tuple. If none exist , the EMPLOYEE tuple is selected
  • 57. Aruna Devi C (DSCASC) 57 More Complex SQL Queries (Cont.,) Joints: Join operation take two relations and return another relation. Can specify a "joined relation" in the FROM-clause Different SQL JOINs: • JOIN: Return rows when there is at least one match in both tables. • LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table. • RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table. • FULL JOIN: Return rows when there is a match in one of the tables. Joined Tables in SQL and Outer Joins
  • 58. Aruna Devi C (DSCASC) 58 More Complex SQL Queries (Cont.,) Join operation take two relations and return another relation. Product (pname, price, category, manufacturer) Company (cname, stockPrice, country) Find all products under $200 manufactured in Japan; return their names and prices. SELECT PName, Price FROM Product, Company WHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200 SELECT PName, Price FROM Product, Company WHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200 Join between Product and Company Joins
  • 59. Aruna Devi C (DSCASC) 59 Joins • Connect two or more tables: PName Price Category Manufacturer Gizmo 19.99 Gadgets GizmoWorks Powergizmo 29.99 Gadgets GizmoWorks SingleTouch 149.99 Photography Canon MultiTouch 203.99 Household Hitachi Product Company CName StockPrice Country GizmoWorks 25 USA Canon 65 Japan Hitachi 15 Japan What is the Connection between them ? More Complex SQL Queries (Cont.,)
  • 60. Aruna Devi C (DSCASC) 60 Joins PName Price Category Manufacturer Gizmo 19.99 Gadgets GizmoWorks Powergizmo 29.99 Gadgets GizmoWorks SingleTouch 149.99 Photography Canon MultiTouch 203.99 Household Hitachi Product Company Cname StockPrice Country GizmoWorks 25 USA Canon 65 Japan Hitachi 15 Japan PName Price SingleTouch $149.99 SELECT PName, Price FROM Product, Company WHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200 SELECT PName, Price FROM Product, Company WHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200 More Complex SQL Queries (Cont.,)
  • 61. Aruna Devi C (DSCASC) 61 More Complex SQL Queries (Cont.,) • Join operations take two relations and return as a result another relation. • These additional operations are typically used as subquery expressions in the from clause • Join condition – defines which tuples in the two relations match, and what attributes are present in the result of the join. • Join type – defines how tuples in each relation that do not match any tuple in the other relation (based on the join condition) are treated. Joins
  • 62. Aruna Devi C (DSCASC) 62 More Complex SQL Queries (Cont.,) Query Q1, which retrieves the name and address of every employee who works for the ‘Research’ department. Simple Query 1: SELECT Fname, Lname, Address FROM EMPLOYEE, DEPARTMENT WHERE Dname=‘Research’ AND Dnumber=Dno; • Query1 Can be written with join: [It may be easier to specify the join of the EMPLOYEE and DEPARTMENT relations first, and then to select the desired tuples and attributes.] SELECT Fname, Lname, Address FROM (EMPLOYEE JOIN DEPARTMENT ON Dno=Dnumber) WHERE Dname=‘Research’; Joins The attributes of such a table are all the attributes of the first table, EMPLOYEE, followed by all the attributes of the second table, DEPARTMENT
  • 63. Aruna Devi C (DSCASC) 63 More Complex SQL Queries (Cont.,) • If the names of the join attributes are not the same in the base relations, it is possible to rename the attributes so that they match, and then to apply NATURAL JOIN. • Query where the DEPARTMENT relation is renamed as DEPT and its attributes are renamed as Dname, Dno (to match the name of the desired join attribute Dno in the EMPLOYEE table), Mssn, and Msdate. The implied join condition for this NATURAL JOIN is EMPLOYEE.Dno=DEPT.Dno, because this is the only pair of attributes with the same name after renaming: • Query 1 can be also written as Natural Join SELECT Fname, Lname, Address FROM (EMPLOYEE NATURAL JOIN (DEPARTMENT AS DEPT (Dname, Dno, Mssn, Msdate))) WHERE Dname=‘Research’;
  • 64. Aruna Devi C (DSCASC) 64 More Complex SQL Queries (Cont.,) • The default type of join in a joined table is called an inner join, where a tuple is included in the result only if a matching tuple exists in the other relation. • For example, in query, only employees who have a supervisor are included in the result; an EMPLOYEE tuple whose value for Super_ssn is NULL is excluded. If the user requires that all employees be included, an OUTER JOIN must be used explicitly. SELECT E.Lname AS Employee_name, S.Lname AS Supervisor_name FROM (EMPLOYEE AS E LEFT OUTER JOIN EMPLOYEE AS S ON E.Super_ssn=S.Ssn); 2
  • 65. Aruna Devi C (DSCASC) 65 More Complex SQL Queries (Cont.,) In SQL, the options available for specifying joined tables include: • INNER JOIN (only pairs of tuples that match the join condition are retrieved, same as JOIN). • LEFT OUTER JOIN (every tuple in the left table must appear in the result; if it does not have a matching tuple, it is padded with NULL values for the attributes of the right table). • RIGHT OUTER JOIN (every tuple in the right table must appear in the result; if it does not have a matching tuple, it is padded with NULL values for the attributes of the left table), and FULL OUTER JOIN.
  • 66. Aruna Devi C (DSCASC) 66 Joined Relations – Datasets for Examples Relation loan Relation borrower Note: borrower information not available for L-260 and loan information not available for L-155
  • 67. Aruna Devi C (DSCASC) 67 Joined Relations – Examples • loan inner join borrower on loan.loan_number = borrower.loan_number • loan left outer join borrower on loan.loan_number = borrower.loan_number
  • 68. Aruna Devi C (DSCASC) 68 Joined Relations – Examples • loan natural inner join borrower • loan natural right outer join borrower
  • 69. Aruna Devi C (DSCASC) 69 Joined Relations – Examples • loan full outer join borrower using (loan_number) Find all customers who have either an account or a loan (but not both) at the bank. select customer_name from (depositor natural full outer join borrower ) where account_number is null or loan_number is null
  • 70. Aruna Devi C (DSCASC) 72 More Complex SQL Queries (Cont.,) • Include COUNT, SUM, MAX, MIN, and AVG Query: Find the maximum salary, the minimum salary, and the average salary among all employees. SELECT MAX(SALARY), MIN(SALARY), AVG(SALARY) FROM EMPLOYEE – Some SQL implementations may not allow more than one function in the SELECT-clause Aggregate Functions in SQL
  • 71. Aruna Devi C (DSCASC) 73 More Complex SQL Queries (Cont.,) Query: Find the maximum salary, the minimum salary, and the average salary among employees who work for the 'Research' department. SELECT MAX(SALARY), MIN(SALARY), AVG(SALARY) FROM EMPLOYEE, DEPARTMENT WHERE DNO=DNUMBER AND DNAME='Research' Query: Retrieve the total number of employees in the company Aggregate Functions in SQL SELECT COUNT (*) FROM EMPLOYEE SELECT COUNT (*) FROM EMPLOYEE, DEPARTMENT WHERE DNO=DNUMBER AND DNAME='Research Query: Retrieve the number of employees in the 'Research' department.
  • 72. Aruna Devi C (DSCASC) 74 More Complex SQL Queries (Cont.,) • In many cases, we want to apply the aggregate functions to subgroups of tuples in a relation Each subgroup of tuples consists of the set of tuples that have the same value for the grouping attribute(s) • The function is applied to each subgroup independently • SQL has a GROUP BY-clause for specifying the grouping attributes, which must also appear in the SELECT-clause Grouping: The GROUP BY and HAVING Clauses
  • 73. Aruna Devi C (DSCASC) 75 More Complex SQL Queries (Cont.,) Query: For each department, retrieve the department number, the number of employees in the department, and their average salary. SELECT DNO, COUNT (*), AVG (SALARY) FROM EMPLOYEE GROUP BY DNO – In Query, the EMPLOYEE tuples are divided into groups--each group having the same value for the grouping attribute DNO – The COUNT and AVG functions are applied to each such group of tuples separately – The SELECT-clause includes only the grouping attribute and the functions to be applied on each group of tuples – A join condition can be used in conjunction with grouping GROUP BY
  • 74. Aruna Devi C (DSCASC) 76 More Complex SQL Queries (Cont.,) • Query: For each project, retrieve the project number, project name, and the number of employees who work on that project. SELECT PNUMBER, PNAME, COUNT (*) FROM PROJECT, WORKS_ON WHERE PNUMBER=PNO GROUP BY PNUMBER, PNAME – In this case, the grouping and functions are applied after the joining of the two relations GROUP BY
  • 75. Aruna Devi C (DSCASC) 77 More Complex SQL Queries (Cont.,) • Sometimes we want to retrieve the values of these functions for only those groups that satisfy certain conditions • The HAVING-clause is used for specifying a selection condition on groups (rather than on individual tuples). Query: For each project on which more than two employees work , retrieve the project number, project name, and the number of employees who work on that project. SELECT PNUMBER, PNAME, COUNT (*) FROM PROJECT, WORKS_ON WHERE PNUMBER=PNO GROUP BY PNUMBER, PNAME HAVING COUNT (*) > 2 Having Clause Note: predicates in the having clause are applied after the formation of groups whereas predicates in the where clause are applied before forming groups.
  • 76. Aruna Devi C (DSCASC) 78 Summary of SQL Queries A query in SQL can consist of up to six clauses, but only the first two, SELECT and FROM, are mandatory. The clauses are specified in the following order: SELECT <attribute list> FROM <table list> [WHERE <condition>] [GROUP BY <grouping attribute(s)>] [HAVING <group condition>] [ORDER BY <attribute list>]
  • 77. Aruna Devi C (DSCASC) 79 Summary of SQL Queries (cont.,) • The SELECT-clause lists the attributes or functions to be retrieved. • The FROM-clause specifies all relations (or aliases) needed in the query but not those needed in nested queries. • The WHERE-clause specifies the conditions for selection and join of tuples from the relations specified in the FROM-clause. • GROUP BY specifies grouping attributes. • HAVING specifies a condition for selection of groups. • ORDER BY specifies an order (Ascending or Descending) for displaying the result of a query. • A query is evaluated by first applying the WHERE-clause, then GROUP BY and HAVING, and finally the SELECT- clause.
  • 78. Aruna Devi C (DSCASC) 80 Specifying Constraints as Assertions and Triggers Specifying General Constraints as Assertions in SQL: • General constraints: constraints that do not fit in the basic SQL categories. • Mechanism: CREATE ASSERTION – components include: a constraint name, followed by CHECK, followed by a condition • For example, to specify the constraint that the salary of an employee must not be greater than the salary of the manager of the department that the employee works for in SQL, we can write the following assertion:
  • 79. Aruna Devi C (DSCASC) 81 Specifying Constraints as Assertions and Triggers (cont.,) • The basic technique for writing such assertions is to specify a query that selects any tuples that violate the desired condition. • Example, the query selects all employees whose salaries are greater than the salary of the manager of their department. If the result of the query is not empty, the assertion is violated. • On the other hand, the schema designer should use CREATE ASSERTION only in cases where it is not possible to use CHECK on attributes, domains, or tuples, so that simple checks are implemented more efficiently by the DBMS.
  • 80. Aruna Devi C (DSCASC) 82 Specifying Constraints as Assertions and Triggers (cont.,) • 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. • For example, it may be useful to specify a condition that, if violated, causes some user to be informed of the violation. A manager may want to be informed if an employee’s travel expenses exceed a certain limit by receiving a message whenever this occurs. • The CREATE TRIGGER statement is used to implement such actions in SQL. Triggers in SQL
  • 81. Aruna Devi C (DSCASC) 83 Specifying Constraints as Assertions and Triggers (cont.,) • A trigger to compare an employee’s salary to his/her supervisor during insert or update operations: • Several events can trigger this rule: inserting a new employee record, changing an employee’s salary, or changing an employee’s supervisor. • Suppose that the action to take would be to call an external stored procedure SALARY_VIOLATION, which will notify the supervisor. 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 ); Triggers
  • 82. Aruna Devi C (DSCASC) 84 Specifying Constraints as Assertions and Triggers (cont.,) • The trigger is given the name SALARY_VIOLATION. • 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 condition that determines whether the rule action should be executed: Once the triggering event has occurred, an optional condition may be evaluated. • 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
  • 83. Aruna Devi C (DSCASC) 85 Views (Virtual Tables) in SQL • A view is a “virtual” table that is derived from other tables. • Allows for limited update operations (since the table may not physically be stored). • Allows full query operations. • A convenience for expressing certain operations.
  • 84. Aruna Devi C (DSCASC) 86 Views (Virtual Tables) in SQL (Cont.,) Specification of Views: SQL command: CREATE VIEW – a table (view) name – a possible list of attribute names (for example, when arithmetic operations are specified or when we want the names to be different from the attributes in the base relations) – a query to specify the table contents
  • 85. Aruna Devi C (DSCASC) 87 Views (Virtual Tables) in SQL (Cont.,) Specify a different WORKS_ON table SQL Views: An Example CREATE VIEW WORKS_ON1 AS SELECT Fname, Lname, Pname, Hours FROM EMPLOYEE, PROJECT, WORKS_ON WHERE Ssn=Essn AND Pno=Pnumber; Company Database
  • 86. Aruna Devi C (DSCASC) 88 Views (Virtual Tables) in SQL (Cont.,) Using a Virtual Table: • We can specify SQL queries on a newly create table (view): SELECT FNAME, LNAME FROM WORKS_ON1 WHERE PNAME=‘ProductX’; • When no longer needed, a view can be dropped: DROP WORKS_ON1;
  • 87. Aruna Devi C (DSCASC) 89 Views (Virtual Tables) in SQL (Cont.,) View Implementation: • View materialization: involves physically creating and keeping a temporary table – assumption: other queries on the view will follow – concerns: maintaining correspondence between the base table and the view when the base table is updated – strategy: incremental update View Update: • Update on a single view without aggregate operations: update may map to an update on the underlying base table • Views involving joins: an update may map to an update on the underlying base relations – not always possible
  • 88. Aruna Devi C (DSCASC) 90 Additional Features of SQL • SQL has various techniques for writing programs in various programming languages that include SQL statements to access one or more databases. These include embedded (and dynamic) SQL, SQL/CLI (Call Level Interface) and its predecessor ODBC (Open Data Base Connectivity), and SQL/PSM (Persistent Stored Modules). • Each commercial RDBMS will have, in addition to the SQL commands, a set of commands for specifying physical database design parameters, file structures for relations, and access paths such as indexes. We called these commands a storage definition language (SDL). • SQL has transaction control commands. These are used to specify units of database processing for concurrency control and recovery purposes.
  • 89. Aruna Devi C (DSCASC) 91 Additional Features of SQL (Cont.,) • SQL has language constructs for specifying the granting and revoking of privileges to users. Privileges typically correspond to the right to use certain SQL commands to access certain relations. • SQL has language constructs for creating triggers. • SQL has incorporated many features from object-oriented models to have more powerful capabilities, leading to enhanced relational systems known as object-relational. • SQL and relational databases can interact with new technologies such as • XML and OLAP ----------------------------------
  • 90. Aruna Devi C (DSCASC) 92 Database Programming: Techniques and Issues • The majority of database interactions are executed through programs that have been carefully designed and tested. • These programs are generally known as application programs or database applications. Approaches to Database Programming: • Embedding database commands in a general-purpose programming language: Database commands are embedded in a general-purpose programming language • Using a library of database functions: Available to the host language for database calls; known as an API (Application Programming Interface) • Designing a brand-new language: A database programming language is designed from scratch to be compatible with the database model and query language.
  • 91. Aruna Devi C (DSCASC) 93 Database Programming: Techniques and Issues When a programmer or software engineer writes a program that requires access to a database, it is quite common for the program to be running on one computer system while the database is installed on another. When writing such a program, a common sequence of interaction is the following: 1. When the client program requires access to a particular database, the program must first establish or open a connection to the database server. 2. Once the connection is established, the program can interact with the database by submitting queries, updates, and other database commands. 3. When the program no longer needs access to a particular database, it should terminate or close the connection to the database. Typical Sequence of Interaction in Database Programming
  • 92. Aruna Devi C (DSCASC) 94 Embedded SQL, Dynamic SQL • Most SQL statements can be embedded in a general-purpose host programming language such as COBOL, C, Java. Retrieving Single Tuples with Embedded SQL: • An embedded SQL statement is distinguished from the host language statements by EXEC SQL and a matching END-EXEC (or semicolon). – shared variables (used in both languages) usually prefixed with a colon (:) in SQL • Suppose that we want to write C programs to process the COMPANY database. • We need to declare program variables to match the types of the database attributes that the program will process.
  • 93. Aruna Devi C (DSCASC) 95 Embedded SQL, Dynamic SQL (Cont.,) • Variables inside DECLARE are shared and can appear (while prefixed by a colon) in SQL statements. • SQLCODE is used to communicate errors/exceptions between the database and the program C program variables used in the embedded SQL examples E1 and E2. The C program variables declared in lines 2 through 5 correspond to the attributes of the EMPLOYEE and DEPARTMENT tables from the COMPANY database The variables declared SQLCODE and SQLSTATE—are used to communicate errors and exception conditions between the database system and the executing program.
  • 94. Aruna Devi C (DSCASC) 96 Embedded SQL, Dynamic SQL (Cont.,) Connecting to the Database: • The SQL command for establishing a connection to a database has the following form: CONNECT TO <server name>AS <connection name> AUTHORIZATION <user account name and password> ; • To change from the currently active connection to a different one by using the following command: SET CONNECTION <connection name> ; • Once a connection is no longer needed, it can be terminated by the following command: DISCONNECT <connection name> ; 1 2 3
  • 95. Aruna Devi C (DSCASC) 97 Embedded SQL, Dynamic SQL (Cont.,) Example of Embedded SQL Programming: • To illustrate embedded SQL programming is a repeating program segment (loop) that takes as input a Social Security number of an employee and prints some information from the corresponding EMPLOYEE record in the database.
  • 96. Aruna Devi C (DSCASC) 98 Embedded SQL, Dynamic SQL (Cont.,) Example explanation – • The program reads (inputs) an Ssn value and then retrieves the EMPLOYEE tuple with that Ssn from the database via the embedded SQL command. • The INTO clause (line 5) specifies the program variables into which attribute values from the database record are retrieved.
  • 97. Aruna Devi C (DSCASC) 99 Embedded SQL, Dynamic SQL (Cont.,) Retrieving Multiple Tuples with Embedded SQL Using Cursors: • We can think of a cursor as a pointer that points to a single tuple (row) from the result of a query that retrieves multiple tuples. • An OPEN CURSOR command fetches the query result from the database and sets the cursor to a position before the first row in the result of the query. • FETCH commands move the cursor to the next tuple. • CLOSE CURSOR indicates that the processing of query results has been completed
  • 98. Aruna Devi C (DSCASC) 100 Embedded SQL, Dynamic SQL (Cont.,) Specifying Queries at Runtime Using Dynamic SQL: • Objective: executing new (not previously compiled) SQL statements at run-time – a program accepts SQL statements from the keyboard at run-time – a point-and-click operation translates to certain SQL query • Dynamic update is relatively simple; dynamic query can be complex – because the type and number of retrieved attributes are unknown at compile time
  • 99. Aruna Devi C (DSCASC) 101 Database Stored Procedures and SQL/PSM Database Stored Procedures and Functions: • Procedures / functions (modules) are stored locally and executed by the database server (as opposed to execution by clients) • Advantages: – If the procedure is needed by many applications, it can be invoked by any of them (thus reduce duplications) – Execution by the server reduces communication costs – Enhance the modeling power of views
  • 100. Aruna Devi C (DSCASC) 102 Database Stored Procedures and SQL/PSM (Cont.,) • Many commercial DBMS’s 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. The general form of declaring stored procedures is as follows: • A stored procedure: CREATE PROCEDURE procedure-name (params) local-declarations procedure-body; • A stored function: CREATE FUNCTION fun-name (params) RETURNS return-type local-declarations function-body; • Calling a procedure or function: CALL procedure-name/fun-name (arguments);
  • 101. Aruna Devi C (DSCASC) 103 Company Database Q1 Q2

Notes de l'éditeur

  1. &amp;lt;number&amp;gt;
  2. &amp;lt;number&amp;gt;
  3. &amp;lt;number&amp;gt;
  4. &amp;lt;number&amp;gt;
  5. &amp;lt;number&amp;gt;
  6. &amp;lt;number&amp;gt;
  7. &amp;lt;number&amp;gt;
  8. &amp;lt;number&amp;gt;
  9. &amp;lt;number&amp;gt;