0% found this document useful (0 votes)
14 views

Unit_III_Lect

Uploaded by

403 Aditi Dhaske
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Unit_III_Lect

Uploaded by

403 Aditi Dhaske
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Unit III: Basics of SQL

DDL, DML, DCL, Structure: Creation, Alteration, Defining constraints –


Primary key, Foreign key, Unique key, Not null, Check, IN operator,
Functions - Aggregate Functions, Built-in Functions –Numeric, Date,
String Functions, Set operations, sub-queries, correlated subqueries, Use
of group by, having, order by, join and its types, Exist, Any, All, view and
its types. Transaction control commands: Commit, Rollback, Save-point
PL/SQL Concepts: Cursors, Stored Procedures, Stored Function, Database
Triggers.
SQL Parts

 DML -- provides the ability to query information from the database


and to insert tuples into, delete tuples from, and modify tuples in the
database.
 integrity – the DDL includes commands for specifying integrity
constraints.
 View definition -- The DDL includes commands for defining views.
 Transaction control –includes commands for specifying the beginning
and ending of transactions.
 Embedded SQL and dynamic SQL -- define how SQL statements can
be embedded within general-purpose programming languages.
 Authorization – includes commands for specifying access rights to
relations and views.
DDL: Data Definition Language
 The SQL data-definition language (DDL) allows the specification of
information about relations, including:

 The schema for each relation.


 The type of values associated with each attribute.
 The Integrity constraints
 The set of indices to be maintained for each relation.
 Security and authorization information for each relation.
 The physical storage structure of each relation on disk.
DDL: Data Definition Language
 Domain Types in SQL:
 char(n). Fixed length character string, with user-specified length n.
 varchar(n). Variable length character strings, with user-specified
maximum length n.
 int. Integer (a finite subset of the integers that is machine-dependent).
 smallint. Small integer (a machine-dependent subset of the integer
domain type).
 numeric(p,d). Fixed point number, with user-specified precision of p
digits, with d digits to the right of decimal point. (ex., numeric(3,1),
allows 44.5 to be stores exactly, but not 444.5 or 0.32)
 real, double precision. Floating point and double-precision floating
point numbers, with machine-dependent precision.
 float(n). Floating point number, with user-specified precision of at least
n digits.
DDL: Data Definition Language
 Create Table Construct:
 An SQL relation is defined using the create table command:
create table r
(A1 D1, A2 D2, ..., An Dn,
(integrity-constraint1),
...,
(integrity-constraintk))
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 instructor (
ID char(5),
name varchar(20),
dept_name varchar(20),
salary numeric(8,2))
DDL: Data Definition Language
 Integrity Constraints in Create Table Construct:

 Types of integrity constraints


 primary key (A1, ..., An )
 foreign key (Am, ..., An ) references r
 not null
 SQL prevents any update to the database that violates an integrity
constraint.
 Example:
create table instructor (
ID char(5),
name varchar(20) not null,
dept_name varchar(20),
salary numeric(8,2),
primary key (ID),
foreign key (dept_name) references department);
DDL: Data Definition Language
 Updates to tables :
 Drop Table
drop table r
 Alter
alter table r add A D
 where A is the name of the attribute to be added to relation r
and D is the domain of A.
 All exiting tuples in the relation are assigned null as the value for
the new attribute.
alter table r drop A
 where A is the name of an attribute of relation r
 Dropping of attributes not supported by many databases.
DML: Data Manipulation Language
 Modification of the Database:

 Insertion of new tuples into a given relation


 Deletion of tuples from a given relation.
 Updating of values in some tuples in a given
relation
DML: Data Manipulation Language
 Insertion:
 Add a new tuple to course
insert into course
values ('CS-437', 'Database Systems', 'Comp. Sci.', 4);

 or equivalently

insert into course (course_id, title, dept_name, credits)


values ('CS-437', 'Database Systems', 'Comp. Sci.', 4);

 Add a new tuple to student with tot_creds set to null


insert into student
values ('3003', 'Green', 'Finance', null);
DML: Data Manipulation Language
 Deletion:
 Delete all instructors
delete from instructor

 Delete all instructors from the Finance department


delete from instructor
where dept_name= 'Finance’;

 Delete all tuples in the instructor relation for those instructors


associated with a department located in the Watson building.
delete from instructor
where dept name in (select dept name
from department
where building = 'Watson');
DML: Data Manipulation Language
 Updates:
 Give a 5% salary raise to all instructors
update instructor
set salary = salary * 1.05
 Give a 5% salary raise to those instructors who earn less than 70000
update instructor
set salary = salary * 1.05
where salary < 70000;
 Give a 5% salary raise to instructors whose salary is less than average
update instructor
set salary = salary * 1.05
where salary < (select avg (salary)
from instructor);
SQL Queries
 Basic Query Structure :

 A typical SQL query has the form:

select A1, A2, ..., An


from r1, r2, ..., rm
where P

 Ai represents an attribute
 Ri represents a relation
 P is a predicate.
 The result of a SQL query is a relation.
SQL Queries
 Basic Query Structure :

 Example: find the names of all instructors:


select name
from instructor
 NOTE: SQL names are case insensitive (i.e., you may use
upper- or lower-case letters.)
E.g., Name ≡ NAME ≡ name
Some people use upper case wherever we use bold
font.
SQL Queries
 Basic Query Structure :

 SQL allows duplicates in relations as well as in query results.


 To force the elimination of duplicates, insert the keyword distinct after
select.
 Find the department names of all instructors, and remove duplicates
select distinct dept_name
from instructor
 The keyword all specifies that duplicates should not be removed.

select all dept_name


from instructor
SQL Queries
 Basic Query Structure :

 An asterisk in the select clause denotes “all attributes”


select *
from instructor
 An attribute can be a literal with no from clause
select '437'
Results is a table with one column and a single row with
value “437”
Can give the column a name using:
select '437' as FOO
SQL Queries
 The where Clause:
 The where clause specifies conditions that the result must satisfy
 Corresponds to the selection predicate of the relational algebra.
 To find all instructors in Comp. Sci. dept
select name
from instructor
where dept_name = 'Comp. Sci.'
 SQL allows the use of the logical connectives and, or, and not
 The operands of the logical connectives can be expressions involving the
comparison operators <, <=, >, >=, =, and <>.
 Comparisons can be applied to results of arithmetic expressions
 To find all instructors in Comp. Sci. dept with salary > 70000
select name
from instructor
where dept_name = 'Comp. Sci.' and salary > 70000
SQL Queries
 Examples:
 Find the names of all instructors who have
taught some course and the course_id
 select name, course_id
from instructor , teaches
where instructor.ID = teaches.ID

 Find the names of all instructors in the Art


department who have taught some course
and the course_id
 select name, course_id
from instructor , teaches
where instructor.ID = teaches.ID
and instructor. dept_name =
'Art'
SQL Queries
 String Operations:

 SQL includes a string-matching operator for comparisons on character


strings. The operator like uses patterns that are described using two
special characters:
 percent ( % ). The % character matches any substring.
 underscore ( _ ). The _ character matches any character.
 Find the names of all instructors whose name includes the substring
“dar”.
select name
from instructor
where name like '%dar%'
 Match the string “100%”
like '100 \%' escape '\'
in that above we use backslash (\) as the escape character.
SQL Queries
 String Operations:
 Patterns are case sensitive.
 Pattern matching examples:
 'Intro%' matches any string beginning with “Intro”.
 '%Comp%' matches any string containing “Comp” as a substring.
 '_ _ _' matches any string of exactly three characters.
 '_ _ _ %' matches any string of at least three characters.

 SQL supports a variety of string operations such as


 concatenation (using “||”)
 converting from upper to lower case (and vice versa)
 finding string length, extracting substrings, etc.
SQL Queries
 Ordering the Display of Tuples:

 List in alphabetic order the names of all instructors


 select distinct name
from instructor
order by name
 We may specify desc for descending order or asc for ascending order,
for each attribute; ascending order is the default.
 Example: order by name desc
 Can sort on multiple attributes
 Example: order by dept_name, name
SQL Queries
 Where Clause Predicates:

 SQL includes a between comparison operator


 Example: Find the names of all instructors with salary between
$90,000 and $100,000 (that is,  $90,000 and  $100,000)
select name
from instructor
where salary between 90000 and 100000
 Tuple comparison
select name, course_id
from instructor, teaches
where (instructor.ID, dept_name) = (teaches.ID, 'Biology');
SQL Queries
 Set Operations:

 Find courses that ran in Fall 2017 or in Spring 2018


(select course_id from section where sem = 'Fall' and year = 2017)
union
(select course_id from section where sem = 'Spring' and year = 2018)
 Find courses that ran in Fall 2017 and in Spring 2018
(select course_id from section where sem = 'Fall' and year = 2017)
intersect
(select course_id from section where sem = 'Spring' and year = 2018)
 Find courses that ran in Fall 2017 but not in Spring 2018
(select course_id from section where sem = 'Fall' and year = 2017)
except
(select course_id from section where sem = 'Spring' and year = 2018)
SQL Queries
 Aggregate Functions:

 These functions operate on the multiset of values of a column of a


relation, and return a value

avg: average value


min: minimum value
max: maximum value
sum: sum of values
count: number of values
SQL Queries
 Aggregate Functions:
 Find the average salary of instructors in the Computer Science
department
select avg (salary)
from instructor
where dept_name= 'Comp. Sci.';
 Find the total number of instructors who teach a course in the Spring
2018 semester
select count (distinct ID)
from teaches
where semester = 'Spring' and year = 2018;
 Find the number of tuples in the course relation
select count (*)
from course;
SQL Queries
 Aggregate Functions – Having Clause:

 Find the names and average salaries of all departments whose average salary is
greater than 42000

select dept_name, avg (salary) as avg_salary


from instructor
group by dept_name
having avg (salary) > 42000;

 Note: predicates in the having clause are applied after the formation of groups
whereas predicates in the where clause are applied before forming groups
SQL Queries
 Nested Subqueries:
 SQL provides a mechanism for the nesting of subqueries. A subquery is a
select-from-where expression that is nested within another query.
 The nesting can be done in the following SQL query

select A1, A2, ..., An


from r1, r2, ..., rm
where P

as follows:
 From clause: ri can be replaced by any valid subquery
 Where clause: P can be replaced with an expression of the form:
B <operation> (subquery)
 B is an attribute and <operation> to be defined later.
 Select clause:
 Ai can be replaced be a subquery that generates a single value.
SQL Queries
 Nested Subqueries: Set Membership

 Find courses offered in Fall 2017 and in Spring 2018

select distinct course_id


from section
where semester = 'Fall' and year= 2017 and
course_id in (select course_id
from section
where semester = 'Spring' and year= 2018);

 Find courses offered in Fall 2017 but not in Spring 2018


select distinct course_id
from section
where semester = 'Fall' and year= 2017 and
course_id not in (select course_id
from section
where semester = 'Spring' and year= 2018);
SQL Queries
 Nested Subqueries: Set Comparison – “some” Clause

 Find names of instructors with salary greater than that of some


(at least one) instructor in the Biology department.
select distinct T.name
from instructor as T, instructor as S
where T.salary > S.salary and S.dept name = 'Biology';

 Same query using > some clause


select name
from instructor
where salary > some (select salary
from instructor
where dept name = 'Biology');
SQL Queries
 Nested Subqueries: Set Comparison – “all” Clause

 Find the names of all instructors whose salary is greater than the salary
of all instructors in the Biology department.
select name
from instructor
where salary > all (select salary
from instructor
where dept name = 'Biology');
SQL Queries
 Nested Subqueries: Test for Empty Relations

 The exists construct returns the value true if the argument subquery is
nonempty.
 exists r  r  Ø
 not exists r  r = Ø
SQL Queries
 Nested Subqueries: Use of “exists” Clause
 Yet another way of specifying the query “Find all courses taught in both
the Fall 2017 semester and in the Spring 2018 semester”
select course_id
from section as S
where semester = 'Fall' and year = 2017 and
exists (select *
from section as T
where semester = 'Spring' and year= 2018
and S.course_id = T.course_id);

 Correlation name – variable S in the outer query


 Correlated subquery – the inner query
SQL Queries
 Nested Subqueries: Use of “not exists” Clause
 Find all students who have taken all courses offered in the Biology
department.

select distinct S.ID, S.name


from student as S
where not exists ( (select course_id
from course
where dept_name = 'Biology')
except
(select T.course_id
from takes as T
where S.ID = T.ID));

• First nested query lists all courses offered in Biology


• Second nested query lists all courses a particular student took
 Note that X – Y = Ø  X Y
 Note: Cannot write this query using = all and its variants
PL/SQL Queries
 Functions and Procedures

 Functions and procedures allow “business logic” to be stored in the


database and executed from SQL statements.

 These can be defined either by the procedural component of SQL or


by an external programming language such as Java, C, or C++.
PL/SQL Queries
 Functions
 Define a function that, given the name of a department, returns the count of
the number of instructors in that department.
create function dept_count (dept_name varchar(20))
returns integer
begin
declare d_count integer;
select count (* ) into d_count
from instructor
where instructor.dept_name = dept_name
return d_count;
end
 The function dept_count can be used to find the department names and
budget of all departments with more that 12 instructors.
select dept_name, budget
from department
where dept_count (dept_name ) > 12
PL/SQL Queries
 Procedures
 The dept_count function could instead be written as procedure:
create procedure dept_count_proc (in dept_name varchar(20),
out d_count integer)
begin
select count(*) into d_count
from instructor
where instructor.dept_name = dept_count_proc.dept_name
end
 The keywords in and out are parameters that are expected to have
values assigned to them and parameters whose values are set in the
procedure in order to return results.
 Procedures can be invoked either from an SQL procedure or from
embedded SQL, using the call statement.
declare d_count integer;
call dept_count_proc( 'Physics', d_count);
PL/SQL Queries
 Language Constructs for Procedures & Functions
 SQL supports constructs that gives it almost all the power of a
general-purpose programming language.
 Warning: most database systems implement their own variant of the
standard syntax below.
 Compound statement: begin … end,
 May contain multiple SQL statements between begin and end.
 Local variables can be declared within a compound statements
 While and repeat statements:
while boolean expression do
sequence of statements ;
end while

repeat
sequence of statements ;
until boolean expression
end repeat
PL/SQL Queries
 Language Constructs for Procedures & Functions

 For loop
 Permits iteration over all results of a query
 Example: Find the budget of all departments

declare n integer default 0;


for r as
select budget from department
where dept_name = 'Music'
do
set n = n + r.budget
end for
PL/SQL Queries
 Language Constructs for Procedures & Functions

 Conditional statements (if-then-else)


if boolean expression
then statement or compound statement
elseif boolean expression
then statement or compound statement
else statement or compound statement
end if
PL/SQL Queries
 Triggers

 A trigger is a statement that is executed automatically by the


system as a side effect of a modification to the database.
 To design a trigger mechanism, we must:
 Specify the conditions under which the trigger is to be executed.
 Specify the actions to be taken when the trigger executes.
 Triggers introduced to SQL standard in SQL:1999, but supported even
earlier using non-standard syntax by most databases.
PL/SQL Queries
 Triggers

 Triggering event can be insert, delete or update


 Triggers on update can be restricted to specific attributes
 For example, after update of takes on grade
 Values of attributes before and after an update can be referenced
 referencing old row as : for deletes and updates
 referencing new row as : for inserts and updates
 Triggers can be activated before an event, which can serve as extra
constraints. For example, convert blank grades to null.

create trigger setnull_trigger before update of takes


referencing new row as nrow
for each row
when (nrow.grade = ' ')
begin atomic
set nrow.grade = null;
end;
PL/SQL Queries
 Cursors

 To process an SQL statement, ORACLE needs to create an area of


memory known as the context area; this will have the information
needed to process the statement.
 This information includes the number of rows processed by the
statement, a pointer to the parsed representation of the statement.
 In a query, the active set refers to the rows that will be returned.
PL/SQL Queries
 Cursors

 A cursor is a handle, or pointer, to the context area.


 Through the cursor, a PL/SQL program can control the context area
and what happens to it as the statement is processed.
 Two important features about the cursor are
 Cursors allow you to fetch and process rows returned by a
SELECT statement, one row at a time.
 A cursor is named so that it can be referenced.
PL/SQL Queries
 Cursors

 There are two types of cursors:


 An IMPLICIT cursor is automatically declared by Oracle every time an SQL
statement is executed. The user will not be aware of this happening and will
not be able to control or process the information in an implicit cursor.
 An EXPLICIT cursor is defined by the program for any query that returns more
than one row of data. That means the programmer has declared the cursor
within the PL/SQL code block.
PL/SQL Queries
 Cursors

 The process of working with an explicit cursor consists of the following


steps:

 DECLARING the cursor. This initializes the cursor into memory.

 OPENING the cursor. The previously declared cursor can now be opened; memory
is allotted.

 FETCHING the cursor. The previously declared and opened cursor can now
retrieve data; this is the process of fetching the cursor.

 CLOSING the cursor. The previously declared, opened, and fetched cursor must
now be closed to release memory allocation.
PL/SQL Queries
 Cursors
PL/SQL Queries
 Cursors

DECLARE
CURSOR c_zip IS
SELECT *
FROM zipcode;
vr_zip c_zip%ROWTYPE;
BEGIN
OPEN c_zip;
LOOP
FETCH c_zip INTO vr_zip;
EXIT WHEN c_zip%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(vr_zip.zipcode|| ‘ ’||vr_zip.city||‘
’||vr_zip.state);
END LOOP;
Thanks

You might also like