0% found this document useful (0 votes)
0 views59 pages

2 DBMS

The document provides an overview of SQL, a domain-specific declarative language used for managing relational databases. It covers various SQL commands, including Data Definition Language (DDL), Data Manipulation Language (DML), and constraints, as well as query structures, joins, and views. Additionally, it explains the differences between natural joins and inner joins, and the use of aggregate functions, grouping, and filtering in SQL queries.

Uploaded by

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

2 DBMS

The document provides an overview of SQL, a domain-specific declarative language used for managing relational databases. It covers various SQL commands, including Data Definition Language (DDL), Data Manipulation Language (DML), and constraints, as well as query structures, joins, and views. Additionally, it explains the differences between natural joins and inner joins, and the use of aggregate functions, grouping, and filtering in SQL queries.

Uploaded by

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

SQL (Structured Query Language)

• Domain specific Language  Only used for RDBMS


• SQL is declarative language  what to do not how to do (in procedural
language what to do + how to do) , for procedural we have PL –SQL
• DDL, DML, DCL, TCL
• Keys and Constrictions (Candidate Key, Primary Key, Foreign Key, Not null
constrictions, default constraints, domain constrains)
• Operators ( like, between, in , not in , exist, not exist, conditional)
• Clauses (from, distinct, order by, group by , having)
• Aggregate function (min, max, avg, sum,count)
• Join and nested query
• PL-SQL( triggers, functions, cursor , procedures)
SQL Commands

DDL DML DCL TCL Constraints


• Create • Select • Grant • Commit • Primary
• Alter • Insert • Revoke • RollBack Key
• Drop • Update • Savepoint • Foreign
• Truncate • Delete Key
• Rename • Check
• Qunique
• Default
• Not Null
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.
Fig : University Database Schema Diagram
SQL: Data Definition Language
• allows the specification of information about relations, including:
• The schema for each relation.
• The domain of values associated with each attribute.
• Integrity constraints
• also other information such as
• The set of indices to be maintained for each relations.
• Security and authorization information for each relation.
• The physical storage structure of each relation on disk.
• Used to build and modify the structure of tables and other objects of
database. Database Objects can be
• Tables
• Views
• Keys(Constraints
• Index
Create Table Construct Integrity Constraints in Create Table
 An SQL relation is defined using the create  not null
table command:  primary key (A1, ..., An )
 create table r (A1D1, A2D2, ..., AnDn,  foreign key (Am, ..., An ) references r
(integrity-constraint1),
..., create table instructor (
(integrity-constraintk)) ID char(5),
o r is the name of the relation name varchar(20) not null,
o each Ai is an attribute name in the schema dept_name varchar(20),
of relation r salary numeric(8,2),
o Di is the data type of values in the domain primary key (ID),
of attribute Ai foreign key (dept_name)
 Example: references department);
 create table instructor (
create table student (
ID char(5),
ID varchar(5),
name varchar(20),
name varchar(20) not null,
dept_name varchar(20),
dept_name varchar(20),
salary numeric(8,2))
tot_cred numeric(3,0),
primary key (ID),
 primary key declaration on an attribute foreign key (dept_name) references
automatically ensures not null department);
create table takes (
ID varchar(5),
course_id varchar(8),
sec_id varchar(8),
semester varchar(6),
year numeric(4,0),
grade varchar(2),
primary key (ID, course_id, sec_id, semester, year) ,
foreign key (ID) references student,
foreign key (course_id, sec_id, semester, year) references section);

create table course (


course_id varchar(8),
title varchar(50),
dept_name varchar(20),
credits numeric(2,0),
primary key (course_id),
foreign key (dept_name) references department);
Updates to tables
• Insert :insert into instructor values (‘10211’, ’Smith’, ’Biology’, 66000);
• Delete : Remove all tuples from the student relation
delete from student
• 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 andD 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


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 an SQL query is a relation.
• The select clause lists the attributes desired in the result of a query
• corresponds to the projection operation of the relational algebra
• Example: find the names of all instructors:
select name from instructor
• 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 allows duplicates in relations as well as in query results.
• To force the elimination of duplicates, insert the keyword distinct
after select.
Basic Query Structure
• 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
• An asterisk in the select clause denotes “all attributes”
select * from instructor
• The select clause can contain arithmetic expressions involving the operation, +,
–, *, and /, and operating on constants or attributes of tuples.
• The query:
select ID, name, salary/12 from instructor
• would return a relation that is the same as the instructor relation, except that
the value of the attribute salary is divided by 12.
• Can rename “salary/12” using the as clause:
select ID, name, salary/12 as monthly_salary
Basic Query Structure : 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.'
• Comparison results can be combined using the logical connectives and, or,
and not
• To find all instructors in Comp. Sci. dept with salary > 80000
• select name
from instructor
where dept_name =‘Comp. Sci.'and salary > 80000
• Comparisons can be applied to results of arithmetic expressions
Basic Query Structure : From Clause
• The from clause lists the relations involved in the query
• Corresponds to the Cartesian product operation of the relational algebra.
• Find the Cartesian product instructor X teaches
select * from instructor, teaches
• generates every possible instructor – teaches pair, with all attributes from both
relations.
• For common attributes (e.g., ID), the attributes in the resulting table are renamed
using the relation name (e.g., instructor.ID)
• Cartesian product not very useful directly, but useful combined with
where-clause condition (selection operation in relational algebra).
 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’
Consider the following schemas
EMP(EmpNO, Ename, Job, sal,hiredate,comm, deptno)
DEPT(Deptno, dname,loc)
The above EMP and DEPT contains 20 and 10 tuples respectively , then the maximum number of tuples
Returned by the following query will be
Select ename, sal,, dname,loc from EMP, DEPT
a) 200
b) 20
c) 10
d) 30
Basic Query Structure : The Rename Operation
• The SQL allows renaming relations and attributes using the as clause:
• old-name as new-name
• Find the names of all instructors who have a higher salary than
some instructor in ‘Comp. Sci’.
• select distinct T.name
from instructor as T, instructor as S
where T.salary>S.salaryand S.dept_name = ‘Comp. Sci.’
• Keyword as is optional and may be omitted instructor as T ≡ instructor T
Basic Query Structure : Strings Operation
• SQL includes a string-matching operator for
comparisons on character strings. Patterns are case sensitive.
Pattern matching examples:
• The operator like uses patterns that are described ‘Intro%’ matches any string beginning
using two special characters: with “Intro”.
• percent ( % ). The % character matches any ‘%Comp%’ matches any string containing
substring. “Comp” as a substring.
• underscore ( _ ). The _ character matches any ‘_ _ _’ matches any string of exactly three
character. characters.
‘_ _ _ %’ matches any string of at least
• Find the names of all instructors whose name three characters.
includes the substring “dar”.
SQL supports a variety of string operations
select name from instructor where name like '%dar%' such as
• Match the string “100%” concatenation (using “||”)
converting from upper to lower case (and
• like ‘100 \%' escape '\' vice versa)
• in that above we use backslash (\) as the escape finding string length, extracting
character. substrings, etc.
The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set
by one or more columns.
The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate
functions.

The GROUP BY clause groups a set of rows into a set of summary rows or groups. Then the
HAVING clause filters groups based on a specified condition. Note that the HAVING clause is
applied after GROUP BY clause, whereas the WHERE clause is applied before the GROUP
BY clause.

The ORDER BY clause must be the last clause that you specify in a query. If the query also
contains a GROUP BY clause, the clause first arranges the output rows into groups. The
ORDER BY clause then sorts the rows within each group.
Joined Relations
• Join operations take two relations and return as a result another relation.
• A join operation is a Cartesian product which requires that tuples in the
two relations match (under some condition). It also specifies the
attributes that are present in the result of the join
• The join 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.
• Three types of joins:
• Natural join
• Inner join
• Outer join
Difference between Natural JOIN and INNER JOIN in SQL :

SR.NO. NATURAL JOIN INNER JOIN


Natural Join joins two tables based on Inner Join joins two table on the basis of the column
1.
same attribute name and datatypes. which is explicitly specified in the ON clause.
In Natural Join, The resulting table will
In Inner Join, The resulting table will contain all the
contain all the attributes of both the
2. attribute of both the tables including duplicate columns
tables but keep only one copy of each
also
common column
In Natural Join, If there is no condition
In Inner Join, only those records will return which exists
3. specifies then it returns the rows based
in both the tables
on the common column
SYNTAX: SYNTAX:
SELECT * FROM table1 NATURAL JOIN SELECT * FROM table1 INNER JOIN table2 ON
4.
table2; table1.Column_Name = table2.Column_Name;
Natural Join in SQL
• Natural join matches tuples with the same values for all common
attributes, and retains only one copy of each common column.
• The from clause can have multiple relations combined using natural
join:
select A1, A2, … An from r1 natural join r2 natural join .. natural join rn where P ;
• List the names of instructors along with the course ID of the courses
that they taught
• select name, course_id from students, takes where student.ID =
takes.ID;
• Same query in SQL with “natural join” construct
• select name, course_id from student natural join takes;
Takes Relation
Student Relation
student natural join takes output
Dangerous in Natural Join
• Beware of unrelated attributes with same name which get equated incorrectly
• Example -- List the names of students instructors along with the titles of courses that
they have taken
• Correct version
select name, title from student natural join takes, course
where takes.course_id = course.course_id;
• Incorrect version
select name, title from student natural join takes natural join course;
• This query omits all (student name, course title) pairs where the student takes a
course in a department other than the student's own department.
• The correct version (above), correctly outputs such pairs.
To avoid the danger of equating attributes erroneously, we can use the “using” construct
that allows us to specify exactly which columns should be equated.
• Query example : select name, title from (student natural join takes) join course
using (course_id)
Outer Join

• An extension of the join operation that avoids loss of information.


• Computes the join and then adds tuples form one relation that does not
match tuples in the other relation to the result of the join.
• Uses null values.
• Three forms of outer join:
• left outer join
• right outer join
• full outer join
Outer Join Examples
• Relation course
Left Outer Join
• course natural left outer join prereq

• Relation prereq

 In relational algebra: course ⟕ prereq

• Observe that
course information is missing CS-347
prereq information is missing CS-315
Outer Join Examples
• Relation course
Left Outer Join
• course natural right outer join prereq

• Relation prereq

 In relational algebra: course ⟖ prereq


• Observe that
course information is missing CS-347
prereq information is missing CS-315
Outer Join Examples
• Relation course
Full Outer Join
• course natural full outer join prereq

• Relation prereq

 In relational algebra: course ⟗ prereq


• Observe that
course information is missing CS-347
prereq information is missing CS-315
Views
• In some cases, it is not desirable for all users to see the entire logical model
(that is, all the actual relations stored in the database.)
• Consider a person who needs to know an instructors name and department,
but not the salary. This person should see a relation described, in SQL, by

select ID, name, dept_name


from instructor

• A view provides a mechanism to hide certain data from the view of certain
users.
• Any relation that is not of the conceptual model but is made visible to a user
as a “virtual relation” is called a view.
View Definition
• A view is defined using the create view statement which has the form
create view v as < query expression >

where <query expression> is any legal SQL expression. The view name is
represented by v.
• Once a view is defined, the view name can be used to refer to the virtual relation
that the view generates.
• View definition is not the same as creating a new relation by evaluating the query
expression
• Rather, a view definition causes the saving of an expression; the expression is
substituted into queries using the view.
Example Views
• A view of instructors without their salary
create view faculty as
select ID, name, dept_name
from instructor
• Find all instructors in the Biology department
select name
from faculty
where dept_name = ‘Biology’
• Create a view of department salary totals
create view departments_total_salary(dept_name, total_salary) as
select dept_name, sum (salary)
from instructor
group by dept_name;
Views Defined Using Other Views View Expansion
• create view physics_fall_2009 as Expand use of a view in a query/another view
select course.course_id, sec_id,
building, room_number create view physics_fall_2009_watson as
from course, section (select course_id, room_number
where course.course_id = from (select course.course_id, building,
section.course_id room_number
and course.dept_name = from course, section
’Physics’ where course.course_id = section.course_id
and section.semester = ’Fall’ and course.dept_name = ’Physics’
and section.year = ’2009’; and section.semester = ’Fall’
• create view physics_fall_2009_watson and section.year = ’2009’)
as where building= ’Watson’;
select course_id, room_number
from physics_fall_2009
where building= ’Watson’;
Update of a View
• Add a new tuple to faculty view which we defined earlier
insert into faculty values (’30765’, ’Green’, ’Music’);
This insertion must be represented by the insertion of the tuple
(’30765’, ’Green’, ’Music’, null)
into the instructor relation
Functions and Procedures
• Functions/procedures can be written in SQL itself, or in an external
programming language (e.g., C, Java).
• Functions written in an external languages are particularly useful with
specialized data types such as images and geometric objects.
• Example: functions to check if polygons overlap, or to compare images for similarity.
• Some database systems support table-valued functions, which can return a
relation as a result.
• also supports a rich set of imperative constructs, including
• Loops, if-then-else, assignment
• Many databases have proprietary procedural extensions to SQL that
differ.
SQL 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
SQL functions (Cont.)

• Compound statement: begin … end


• May contain multiple SQL statements between begin and end.
• returns -- indicates the variable-type that is returned (e.g.,
integer)
• return -- specifies the values that are to be returned as result of
invoking the function
• SQL function are in fact parameterized views that generalize the
regular notion of views by allowing parameters.
Table Functions
• functions that return a relation as a result
• Example: Return all instructors in a given department
create function instructor_of (dept_name char(20))
returns table (
ID varchar(5),
name varchar(20),
dept_name varchar(20),
salary numeric(8,2))
return table
(select ID, name, dept_name, salary
from instructor
where instructor.dept_name = instructor_of.dept_name)
• Usage
select *
from table (instructor_of (‘Music’))
SQL 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
• 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);
Procedures and functions can be invoked also from dynamic SQL
• SQL:1999 allows more than one function/procedure of the same name (called name overloading), as
long as the number of
arguments differ, or at least the types of the arguments differ
Triggers
• A trigger is a statement that is executed automatically by the system as a
side effect of a modification to the database.
• A trigger defines a set of actions that are performed in response to an
insert, update, or delete operation on a specified table. When such an
SQL operation is executed, the trigger is said to have been activated.
• Triggers can be used, along with referential constraints and check
constraints, to enforce data integrity rules.
• Triggers can also be used to cause updates to other tables, automatically
generate or transform values for inserted or updated rows, or invoke
functions to perform tasks such as issuing alerts.
• Triggers are optional and are defined using the CREATE TRIGGER
statement.
• 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 Types
• BEFORE triggers
• By using triggers that run before an update or insert, values that are being updated
or inserted can be modified before the database is actually modified.
• These can be used to transform input from the application (user view of the data)
to an internal database format where desired.
• AFTER triggers
• Triggers that run after an update, insert, or delete can be used in several ways.
• INSTEAD OF triggers
• INSTEAD OF triggers describe how to perform insert, update, and delete
operations against complex views.
• `INSTEAD OF triggers allow applications to use a view as the sole interface for all
SQL operations (insert, delete, update and select)
Triggers Example
Triggers Example

You might also like