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

SQL Complete

Uploaded by

vandanagowda1813
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)
7 views

SQL Complete

Uploaded by

vandanagowda1813
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/ 135

SQ

L
Introductio
n
SQL (Structured Query Language)
– Statements data definitions, queries,
forupdates (both DDL
andand
DML)
– a•‘standard’ that specifies
how a relational schema is created
• data is inserted / updated in the relations
• data is queried
• transactions are started and stopped
• programs access data in the relations and
a host of other things are done
• DBMS software : SQL Server, SYBASE, Paradox, Informix, Oracle
History of
SQL
▪ SEQUEL
– developed by IBM in early 70’s
– relational query language as part of System-R project
at
IBM San Jose Research Lab.
– the earliest version of SQL

▪ SQL evolution
– ANSI (American National Standard Institute) and
the ISO (International Standard Organization)
Made standard
version of SQL in 1989 called SQL 89.
SQL Server Release
History
SQL Server Release History
Version Year Release Name
1.0 1989 SQL Server 1.0
1.1 1991 SQL Server 1.1
4.21 1993 SQL Server 4.21
6.0 1995 SQL Server 6.0
6.5 1996 SQL Server 6.5
7.0 1998 SQL Server 7.0
8.0 2000 SQL Server 2000
8.0 2003 SQL Server 2000
9.0 2005 SQL Server 2005
10.0 2008 SQL Server 2008
10.25 2010 SQL Azure DB
10.50 2010 SQL Server 2008 R2
11.0 2012 SQL Server 2012
12.0 2014 SQL Server 2014
13.0 2016 SQL server 2016
Components of SQL
Standard
▪ Data Definition Language(DDL)
– Specifies constructs for schema definition, relation
definition, integrity constraints, views and schema
modification.

▪ Data Manipulation Language(DML)


– Specifies constructs for inserting, updating and querying the
data in
the relational instances ( or tables ).

▪ Embedded SQL and Dynamic SQL


– Specifies how SQL commands can be embedded in a
high-level host
language such as C, C++ or Java for programmatic access to
the data.
Components of SQL
Standard

▪ Transaction Control
– Specifies how transactions can be started / stopped, how a
set of
concurrently executing transactions can be managed.
▪ Authorization
– Specifies how to restrict a user / set of users to access only
certain
parts of data, perform only certain types of queries etc.
SQL Data Definition and
Data
▪ Terminology:
– Table, row, and column used for relational model

terms relation, tuple, and attribute

▪ CREATE statement
– Main SQL command for data definition
Data Definition in
SQL
Attribute Data Types in
SQL
▪ Basic data types
– Numeric data types
• Integer numbers: INTEGER,INT, and SMALLINT
• Floating-point (real) numbers: FLOAT or REAL, and
DOUBLE PRECISION
– Character-string data types
• Fixed length: CHAR(n), CHARACTER(n)
• Varying length: VARCHAR(n), CHAR
VARYING(n), CHARACTER VARYING(n)
Attribute Data Types in
SQL
▪ Boolean data type
– Values of TRUE or FALSE or NULL
▪ DATE data type
– Ten positions
– Components are YEAR, MONTH, and DAY in
the
form YYYY-MM-DD
Attribute Data Types in
SQL

▪ Time data type


– TIME type has 8 position format – HH:MM:SS
▪ Others
– There are several more data types whose
details are available in SQL reference books
Specifying Constraints in
SQL

▪ Specifying Constraints in SQL


– Basic constraints:
– Key and referential integrity constraints
– Restrictions on attribute domains and
NULLs
– Constraints on individual tuples within a
relation
Specifying Attribute
Constraints

▪ NOT NULL
– NULL is not permitted for a particular attribute
▪ Default value
– DEFAULT <value>
▪ CHECK clause
– CHECK clauses at the end of a
CREATE TABLE statement Apply to
each tuple individually
CHECK (Dnumber>0 AND Dnumber<21)
Specifying Key and Referential Integrity
Constraints
PRIMARY KEY clause
– Specifies one or more attributes that make • only one in a table
up • It never allows null
– the primary key of a relation values
– Ex : Dnumber INT PRIMARY KEY;

UNIQUE clause
– Specifies alternate (secondary)
• Can be more than one unique key in one
keys table.
– Dname VARCHAR(15) UNIQUE; • Unique key can have null values
Specifying Key and Referential Integrity
Constraints
Referential Integrity Constraints
Violation
▪ can occur if a referenced tuple is deleted or modified action
canspecified for each case using qualifiers ON
be or ON
DELETE UPDATE
▪ Actions
– three possibilities can be specified

SET NULL, SET DEFAULT, CASCADE

▪ these are actions to be taken on the referencing


tuple
– SET NULL –foreign
DEFAULT key attribute
–foreign valuevalue
key attribute to betoset
benull
set to its default
value

– CASCADE –delete the referencing tuple if the referenced tuple is


deleted
or update the FK attribute if the referenced tuple is updated
Example Relational Scheme with
RIC’sshown
Table Definition
Example
DEFAULT and CHECK
example
CREATE TABLE
Employee ( ID int
NOT NULL,
Name varchar(255) NOT
NULL, Dept int,
City varchar(255) DEFAULT
‘Mysuru’,
CHECK (Dept>0 and dept<10)
);

To have default value for city, insert


values :
INSERT into Employee (id, name,
Basic Retrieval Queries in
SQL
▪ SELECT statement
– One basic statement for retrieving information from a
database
– The word select in SQL should not be confused
with select
operation of relational algebra.
▪ Logical comparison operators
=, <, <=, >, >=, and <>
▪ Projection attributes
– Attributes whose values are to be
retrieved
▪ Selection condition
– Boolean condition that must be true for
any retrieved tuple
Inserting data into a
table
▪ Specify a tuple(or tuples) to be inserted
INSERT INTO student VALUES
(„CSO5D014‟,„Mohan‟,„PhD‟,2005,„M‟,3,„FCS008‟),
(„CSO5S031‟,„Madhav‟,„MS‟,2005,„M‟,4,„FCE009‟);

▪ Specify a sub-tuple be inserted

INSERT INTO student(rollNo, name, gen)


VALUES (CS05M022, „Rajasri‟, „F‟),
(CS05B033, „Kalyan‟, „M‟);
Inserting the result of a query in another
table
▪ All the rows or some rows of another table can also be
inserted into the table using INSERT INTO statement.
▪ The rows of another table will be fetched based on
one or more criteria using SQL SELECT statement.
INSERT INTO table1 ( column1, column2)
SELECT table2.column1, table2.column2 FROM
table2 WHERE <condition>;

▪ Example
We have STUDENT table with schema :
STUDENT(USN, NAME, gender, degree, deptno, advisor)
Create new table called CSSTUDENTS(USN, Name) and insert CS
student details from STUDENT table.

INSERT into CSSTUDENT


SELECT usn, name from STUDENT where deptno=3;
Simple SQL
Query
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Product
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi

SELECT *
FROM Product
WHERE category=„Gadgets‟

PName Price Category Manufacturer


“selection” Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
Simple SQL
Query
Product PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi

SELECT PName, Price, Manufacturer


FROM Product
WHERE Price > 100

PName Price Manufacturer


“selection” and
SingleTouch $149.99 Canon
“projection”
MultiTouch $203.99 Hitachi
SQL Query
Result
▪ The result of any SQL query
– A table with select clause attributes as column names.
– Duplicate rows may be present.
– Duplicate rows can be eliminated by specifying DISTINCT
keyword in the select clause, if necessary.
SELECT DISTINCT name
FROM student
– Duplicate rows are essential while computing aggregate
functions ( average, sum etc ).
– Removing duplicate rows involves additional effort and is
done only when necessary.
Eliminating
Duplicates

Category
SELECT DISTINCT Gadgets
category FROM Product Photography
Household

Compare to:
Category
Gadgets
SELECT Gadgets
category FROM Photography
Product Household
Example Queries Involving a Single
Table
▪ Get the rollNo, name of all female students in the dept no.
5.

select rollNo, name


from student
where gen = „F‟ and deptNo = „5‟;

▪ Get the employee Id, name and phone number of


professors in
the CS dept (deptNo= 3) who have joined after 1999.

select empId, name, phone


from professor
where deptNo = 3 and startYear> 1999;
Ambiguous Attribute
Names
▪ Same name can be used for two (or more) attributes
– As long as the attributes are in different relations
▪ If this is the case, and a multi table query refers to two or more
attributes with the same name,
– Must qualify the attribute name with the relation preven
name to t
ambiguity
▪ Select student name and department name for
DeptNo=4

Select STUDENT.name,
DEPARTMENT.name FROM STUDENT,
DEPARTMENT
Where STUDENT.deptNo=DEPARTMENT.deptId
and
STUDENT.deptNo=4
Aliasing, Renaming and Tuple
Variables
▪ Select student name and department name for
DeptNo=4
Select S.name, D.name
FROM STUDENT AS S, DEPARTMENT AS D
Where S.deptNo=D.deptId and Aliasing
S.deptNo=4
▪ Get the rollNo, name of students in the CSE dept (deptNo= 3)
along
with their advisor’s name and phone number.
▪ Get the names, employee ID’s, phone numbers of
professors in CSE dept who joined before 1995.
Unspecified WHERE
Clause
▪ A missing WHERE clause indicates no condition on tuple
selection;
– All tuples of the relation specified in the FROM clause qualify
and are selected for the query result.
SELECT empId
FROM PROFESSOR;
– If more than one relation is specified in the FROM clause, then the
CROSS PRODUCT all possible tuple combinations of these
relations is selected
SELECT empId,deptId
FROM PROFESSOR,DEPARTMENT;
– all combinations of an PROFESSORE empId and a
DEPARTMENT deptId, regardless of whether the employee
works for the department or not
Unspecified WHERE
Clause

▪ It is extremely important to specify every


selection and join condition in the WHERE
clause;
▪ if any such condition is overlooked,
incorrect and very large relations may result.
Tables as Sets in
SQL
▪ Specify an asterisk (*) Retrieve all
the attribute values of the
selected tuples
SELECT *
FROM PROFESSOR
Union, Intersection and Difference
Operations
▪ In SQL, using operators UNION, INTERSECT and
EXCEPT, one can perform set union, intersection and
difference respectively.

▪ Results of these operators are sets, i.e. duplicates are


automatically removed.

▪ Operands need to be union compatible and also have


same attributes in the same order
Example using
UNION

▪ Obtain the roll numbers of students who are currently


(current year and semester) enrolled for either CS563 or
CS561 courses.

(SELECT rollNo FROM enrollment WHERE courseId=


„CS563‟ and sem= 5 and year = 2017)
UNION
(SELECT rollNo FROM enrollment WHERE courseId=
„CS561‟ and sem= 5 and year = 2017 );

R U S returns relation instance containing all tuples that occur in either relation
instance R or S, or both.
Example using
INTERSECTION

▪ Obtain the roll numbers of students who are currently


(current year and semester) enrolled for both CS563 and
CS561 Courses

(SELECT rollNo
FROM enrollment WHERE
courseId= „CS563‟ and sem= 5 and year = 2015)
INTERSECT
(SELECT rollNo
FROM enrollment WHERE
courseId= „CS561‟ and sem= 5 and year = 2014 );

R ⋂ S : returns a relation instance containing all tuples that


occur in both R and S.
Example using EXCEPT
(difference)

▪ Obtain the roll numbers of students who are currently


(current year and semester) not enrolled for CS563 course.

(SELECT rollNo
FROM enrollment
WHERE sem= 5 and year = 2017 )
EXCEPT
(SELECT rollNo
FROM enrollment
WHERE courseId= „CS563‟and
sem= 5 and year = 2017);
R – S: returns a relation instance containing all tuples that occur
in R but not in S.
Substring Pattern Matching and Arithmetic
Operators

▪ LIKE comparison operator


– Used for string pattern
matching
– % any sequence of characters
– underscore ( _ ) a single
character
– Addition (+), subtraction (–), (*), and
▪ Standard arithmetic
multiplication division (/)
operators:
▪ BETWEEN comparison operator
Substring Pattern Matching and Arithmetic
Operators
▪ Specify patterns using special characters
– character ‘%’(percent) matches any Substring
e.g., ‘Raj%’ matches any string starting with “Raj”

e.g., ‘%Raj’ matches any string ending with “Raj”


– character ‘_’(underscore) matches any single character e.g.,

(a) ‘_ _ 91’ matches with any string ending with “91”, with any
two
characters before that.

(b) ‘_ _ _ _’matches any string with exactly four characters

▪ Patterns are case sensitive.


▪ Special characters (percent, underscore) can be
included in patterns using an escape character
‘\’(backslash)
Substring Pattern Matching and Arithmetic
Operators
▪ Obtain roll numbers and names of all students whose names
end with „Kumar‟ .
SELECT rollNo,name
FROM STUDENT
WHERE name like „%Kumar‟;
▪ Match the name “abc%”
like abc\%' escape '\'

▪ 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.
Substring Pattern Matching and Arithmetic
Operators
Case insensitive SQL SELECT: Use upper or lower functions
▪ The SQL standard way to perform case insensitive
queries is to use the SQL upper or lower functions, like
this:

select * from STUDENT where upper(first_name) like


'%AL%'; select * from STUDENT where
lower(first_name) like '%al%';
Substring Pattern Matching and
Arithmetic
▪ Obtain roll names of all students whose admission year is
2012
Date format is DD-MMM-YYYY

SELECT Name
FROM STUDENT
WHERE Year LIKE „_ _ _ _ _ _ _ _ _12‟

▪ Obtain the details of product with the name


containing substring “gizmo”

SELECT
* Products
FROM PName LIKE
WHER ‘%gizmo%’
E
Use of ‘between
and’

▪ Use of ‘between and’ to test the range of a


value

– Obtain names of professors who have joined


between
2000 and 2010
FROM PROFESSOR
WHERE startYear between 2000 and 2010;
SELECT name
Arithmetic
Operators

▪ To get data of 'opening_amt',


‘cust_name', + 'receive_amt')
('opening_amt' 'receive_amt',
from the 'customer' table with
following condition : sum of 'opening_amt' and 'receive_amt' is greater
than 15000,

SELECT cust_name, opening_amt, receive_amt, (opening_amt +


receive_amt)
FROM customer WHERE (opening_amt + receive_amt)>15000;
Arithmetic
Operators

▪ To data of 'cust_name', 'opening_amount',


'oustanding_amount'
get from andthe 'customer' table with
'payment_amount' conditio
:following
'outstanding_amt' - 'payment_amt' is equal to the 'receive_amt', n

SELECT cust_name,opening_amt, payment_amt, outstanding_amt


FROM customer WHERE
(outstanding_amt-payment_amt)=receive_amt;
Deleting rows from a
table
▪ Deletion of tuples is possible ; deleting only part of a
tuple is not possible
▪ Deletion of tuples can be done only from one relation at
a time
▪ Deleting a tuple might trigger further deletions due
to
referentially triggered actions specified as part of
RIC’s
▪ Generic form:
delete from r where <predicate>;
Deleting rows from a
table

▪ Delete tuples from professor relation with start year as


1982.

DELETE FROM PROFESSOR where startYear= 1982;

▪ If ‘where’ clause is not specified, then all the tuples of


that relation are deleted ( Be careful !)
Updating tuples in a
relation
UPDATE r
SET <<attr= newValue> list>
WHERE <predicates>;
▪ Change phone number of all professors working
in CSE dept to “9444445551”
UPDATE PROFESSORS
SET phone = „9444445551‟
WHERE deptNo= (SELECT deptId
FROM DEPARTMENT
WHERE name = „CSE‟);

▪ If ‘where’ clause is not specified, values for the


specified
attributes in all tuples is changed.
Additional features in
SQL
▪ Ordering of result tuples can be done using ‘order by’ clause
▪ Ordering is ascending, unless you specify the DESC
keyword.
▪ Keyword DESC to see result in a descending order of values
– List the names of professors who joined after
1980, in
alphabetic order.

select name from professor


where startYear> 1980
order by name;
▪ In descending order
select name from professor
where startYear> 1980
order by name DESC;
Ordering the
Results
Product (Pname, Price, Category,
Manfacturer)

SELECT pname, price,


manufacturer FROM Product
WHERE category=‘gizmo’ AND price >
50 ORDER BY price, pname

Ties are broken by the second attribute on the ORDER


BY list .
Aggregate
functions
These functions operate on the multiset of values of a
column of a relation, and return a value
Aggregation

SELECT avg(price) SELECT count(*)


FROM Product FROM Product
WHERE WHERE year >
maker=“Toyota” 1995

SQL supports several aggregation operations:

sum, count, min, max, avg

Except count, all aggregations apply to a single attribute

Dr. Mahesha
Aggregation: Count

COUNT applies to duplicates, unless otherwise


stated:
SELECT
Count(category) FROM
same as Count(*)
Product WHERE year
> 1995
We probably
want:
SELECT Count(DISTINCT
category) FROMProduct
WHERE year > 1995

Dr. Mahesha
More Examples

Purchase(product, date, price, quantity)

SELECT Sum(price *
quantity) FROM Purchase
What do
they mean ?
SELECT Sum(price *
quantity) FROM Purchase
WHERE product = „bagel‟

Dr. Mahesha
Simple Aggregations

Purchase
Product Date Price Quantity
Bagel 10/21 1 20
Banana 10/3 0.5 10
Banana 10/10 1 10
Bagel 10/25 1.50 20

SELECT Sum(price *
quantity) FROM Purchase 50 (= 20+30)
WHERE product = „bagel‟

Dr. Mahesha
Grouping &
Aggregation

Dr. Mahesha
Grouping and Aggregation

Purchase(product, date, price, quantity)

Find total sales after 10/1/2005 per product.

SELECT product, Sum(price*quantity) AS


FROM TotalSales Purchase
WHERE date > „10/1/2005‟
GROUP BY
product

Dr. Mahesha
Grouping and Aggregation

SELECT product, Sum(price*quantity) AS


FROM TotalSales Purchase
WHERE date > „10/1/2005‟
GROUP BY
product

1. Compute the FROM and WHERE clauses.

2. Group by the attributes in the GROUPBY

3. Compute the SELECT clause: grouped attributes and


aggregates.
Dr. Mahesha
1&2. FROM-WHERE-GROUPBY

Product Date Price Quantity


Bagel 10/21 1 20
Bagel 10/25 1.50 20
Banana 10/3 0.5 10
Banana 10/10 1 10

Dr. Mahesha
3. SELECT

Product Date Price Quantity Product TotalSales


Bagel 10/21 1 20
Bagel 10/25 1.50 20 Bagel 50
Banana 10/3 0.5 10
Banana 15
Banana 10/10 1 10

SELECT product, Sum(price*quantity) AS


FROM TotalSales Purchase
WHERE date > „10/1/2005‟
GROUP BY
product

Dr. Mahesha
Database schema for Online Book
Database
JOIN
S
▪ A query that combines tuple from two or more relations is
called as
join query

▪ In such types of queries, more than one relation is listed in the


FROM clause
▪ The process of combining data from multiple relation is called
joining
▪ Ex. Consider the following query
▪ This returns Cartesian product of the relation BOOK and
PUBLISHER,
i.e all possible combination of all tuples from both the relation
▪ The condition on the basis of which relations are joined are
Dr. called
Mahesha as
Join
Examples

▪ Retrieve of both BOOK and PUBLISHER where


details in both the P_ID
attribute relation have identical
values

▪ Retrieve P_ID, Pname, Address and Phone of publisher


publishing novels

Dr. Mahesha
Join
▪ Sometimes, it is
examples
required to extract information from more
than two relations.
▪ In such case, more than two relations are required to be
joined
through join query.
▪ This can be achieved by specifying names of all the required
relations in FROM clause and specify join condition in
WHERE clause
▪ Ex. List title, category and price of all the books written by
author
Charles Smith

Dr. Mahesha
More Join
Examples

Dr. Mahesha
More Join
Examples

Dr. Mahesha
Nested Queries or
Subqueries
▪ Complex queries
– In Some queries, part of the computation is specified as
a separate query & the result be used in comparison
condition such queries can be formulated using nested
queries

– Which are complete select-from-where blocks


within the WHERE clause of another query. That other
query is called outer query

Dr. Mahesha
Subqueries/Nested queries

• In the Sub query you may use the different operators to filter out the
result
like [=, >, =, <=, !=, ].
• These Sub queries can be used conjunction with INSERT, UPDATE
and DELETE queries.

Dr. Mahesha
Subquerie
▪ Suppose youwant s findthe name
to of the department
in which employee_id = 100 is currently working on.
SELECT department_name FROM department WHERE
department_id = (SELECT department_id
FROM employee WHERE employee_id = 100);

Dr. Mahesha
Join vs
Subqueries
▪ Joins and subqueries are both used to combine data from
different
tables intoa single result. They share many similarities
differences.
and
▪ But whether to use a JOIN or a sub-query is a tricky subject
discussed in many forums. Unfortunately, there is no definite
answer; very much dependent on the circumstances, data
involved, and the data system involved.
▪ Subqueries can be used to return either a scalar (single) value
or a
row set; whereas, joins are used to return rows.
▪ A common use for a subquery may be to calculate a summary
value for use in a query. For instance, we can use a subquery
to help us obtain all products that have a greater than average
product price.

Dr. Mahesha
Subquer
y
▪ A subquery is a SELECT statement written within
parentheses and nested inside another statement.
▪ Example:
SELECT department_name FROM department WHERE
department_id = (SELECT department_id
FROM employee WHERE employee_id = 100);

▪ Subqueries can return different types of information:


– A scalar subquery returns a single value.
– A column subquery returns a single column of one or more
values.
– A row subquery returns a single row of one or more values.
– A table subquery returns a table of one or more rows of one or
more columns.
Dr. Mahesha
Nested query
examples
▪ SQL provides four useful operations that are
generally used with subqueries : IN,ANY,
ALL & EXIST

Dr. Mahesha
Nested query
operators
▪ IN – This operator is used to compare a value to a list of
literal
values that have been specified.
▪ ANY – This operator is used to compare a
value to any applicable value in the list as per the
condition.
▪ ALL – This operator is used to compare a value to all
values in another value set.
▪ EXISTS – This operator is used to search for the
presence of a row in a specified table that meets a
certain criterion.
Dr. Mahesha
Nested
Queries
▪ Comparison operator IN
– Example : Get the rollNo, name of students who have a lady
professor as their advisor.

SELECT s.usn,
s.name FROM
student s
WHERE s.advisor IN(SELECT eid
FROM professor
WHERE gender="F")

– First nested query selects empId of PROFESSOR that have female


gender
– While the second (outer query) selects rollno and name of students
that have selected empId (o/p of nested)
Dr. Mahesha
Nested
Queries

Dr. Mahesha
EXISTS
Operator
• EXISTS is used to check whether the result of a
correlated query is empty (contains no tuples) or
not (contains one or more tuples)
– Returns a Boolean result (TRUE or FALSE)
– Can be used in the WHERE-clause as a
condition
– EXISTS (Q) evaluates to TRUE if the result of Q
has one or more tuple; evaluates to FALSE if the
result of Q has no tuples

Dr. Mahesha
Correlated Nested
Queries
▪ Whenever a condition in the WHERE clause of a nested
query references some attribute of a relation declared in
the outer query, the two queries are said to be correlated.
▪ Correlated Subquery is a sub-query that uses values from
the outer query. In this case the inner query has to be
executed for every row of outer query.

SELECT eid,
name FROM
professor
WHERE EXISTS (SELECT *
FROM student
WHERE advisor=eid)
Dr. Mahesha
NOT EXISTS
Operator

Dr. Mahesha
Nested query
examples

▪ Retrieve ISBN, Book_title and Category of book with


minimum price

▪ List ISBN, Book_title and Category of book published


by the
publisher residing in the New York

Dr. Mahesha
Nested query
examples
▪ The IN operator can be used to compare a single value to
the set of multiple values

▪ Ex: command to retrieve the details of books belonging


to a category with page count greater than 300 can be
specified as

▪ In case the nested query returns a single attribute an a


single tuple, the query result will be a single value.
▪ In such situation, the = can be used instead of IN
operator
Dr. Mahesha
Nested query
examples

▪ ANY operator compares a value with any of the value in


a list or returned by subquery
▪ This operator returns false value if the subquery
returns no tuple.
▪ Ex. Retrieve details of books with price equal to any
of the books belonging NOVEL category

Dr. Mahesha
Nested query
examples

▪ ALL operator compares a value to every value in a list


returned by the subquery.

▪ Ex. Retrieve details of books with price greater than the


price of all the books belonging to NOVEL category

Dr. Mahesha
Nested query
examples
▪ EXISTS operator evaluates to true if a subquery returns at
least one tuple as result otherwise, it returns false value

▪ Ex. Retrieve the details of publisher havingat least one


book published

Dr. Mahesha
Nested query
examples
▪ On the other hand, NOT EXIST operator evaluates to
true if
subquery returns no tuple as a result.

▪ Ex. Retrieve the details of publishers having not


published any book can be specified as

Dr. Mahesha
Group by and Having
clause

▪ Calculate average price for each category of book in the


BOOK relation

▪ Calculate maximum, minimum and average price of the


books published by each publisher

Dr. Mahesha
Having
clause
▪ HAVING is like a WHERE clause, except that it applies to
the
results of a GROUP BY query
▪ HAVING places conditions on groups, whereas, WHERE
clause used to place conditions on the individual tuples
▪ Another difference is that, condition specified in WHERE
clause cannot include aggregate functions, whereas,
HAVING clause can.

▪ Having class is always used in conjunction with Group By


clause

Dr. Mahesha
Where clause versus Having
clause
▪ Where clause
– Performs tests on rows and eliminates rows not
satisfying the specified condition
– Performed before any grouping of rows is done
▪ Having clause
– Always performed after grouping
– Performs tests on groups and eliminates
groups not satisfying the specified condition
– Tests can only involve grouping attributes
and aggregate functions

Dr. Mahesha
Group by and Having
clause
▪ List the book categories for which number of books published is
less
than 5

▪ More than one condition can be specified in HAVING clause by


using logical operator
▪ Retrieve average price and average page count for each
category of books with average price greater than 30 and
average page count less than 900

Dr. Mahesha
Modifying a Defined
Schema
▪ ALTER TABLE command can be used to modify a
schema
– Adding a new attribute
ALTER table student ADD address varchar(30);
– Deleting an attribute
• need to specify what needs to be done about constraints that refer
to the
attribute being dropped

– two possibilities
• CASCADE - delete the constraints also
• RESTRICT –do not delete the attributes if there are
some views/constraints that refer to it.
ALTER TABLE student DROP degree RESTRICT
Similarly,
Dr. Mahesha an entire table definition can be deleted
Modifying a Defined
Schema
▪ To rename table
ALTER TABLE table_name
RENAME TO new_table_name;
▪ To add a column to an existing table,
ALTER TABLE table_name
ADD column name column-definition;
▪ To modify a column in an existing table,
ALTER TABLE table_name
MODIFY column_name column_type;

Dr. Mahesha
View
▪ A view is a virtual
s
relation, whose
contents are derived
from already existing relation and it does not exist in
physical form
▪ The contents of views are determined by executing a
query based on any relation and it doesn't form the part
of database schema
▪ Each time a view is referred to, its contents are derived
from the relation on which it is based
▪ A view can be used like any other relation, it can be
queried
and joined with other relations or views
▪ These are very useful in the situation where only parts of
relations are to be accessed frequently instead of
Dr. Mahesha
VIE
WS
▪ CREATE VIEW command can be used for creating views
▪ This command provides the name to the view and specifies
the
list of attributes and tuples to be included using a subquery

▪ Ex. Create view containing details of books which belonging


to Text-book and Language book categories

Dr. Mahesha
VIE
WS

▪ This creates a view named BOOK_1, having books satisfying the


WHERE condition, this view consists of all the attributes of
relation
▪ However only selected attributes can also be included in the view

Dr. Mahesha
VIE
WS
▪ Now queries can be performed on these views
as they are performed on the other relations

Dr. Mahesha
VIE

WS
Views can also be based on more than one
relation

▪ Ex. Create view consisting of attributes Book_title, Category, Price and


P_ID of
BOOK relation, Pname and State of PUBLISHER relation

▪ The views that are based on more than one relation are said to be complex
views
▪ These types of views are time consuming to execute, especially if multiple
queries are involved in view definition
▪ Since their contents are not physically stored, they are executed each and
every time they are referred to.
Dr. Mahesha
VIE
WS

▪ To list all the views

SHOW FULL TABLES IN database_name


WHERE TABLE_TYPE LIKE 'VIEW';

▪ Like relation view can also be deleted from


database by using DROP VIEW command

Dr. Mahesha
Restrictions on Updating
Views
▪ Updates on views defined on joining of more than one
table are not allowed
▪ For example, updates on the following view are not
allowed

Create a view Professor_Dept with professor ID,


department Name and department phone

create view profDept(profId, DeptName, DPhone) as


select f.empId, d.name, d.phone from
professor f, department d
where f.depNo= d.depId

Dr. Mahesha
Restrictions on Updating
Views
▪ Updates on views defined with ‘group by’ clause and
aggregate functions is not permitted, as a tuple in view
will not have a corresponding tuple in base relation.
▪ For example, updates on the following view are not
allowed

Create view deptNumCourses which contains the number of


courses offered by a dept.

create view deptNumCourses (deptNo, numCourses) as


select deptNo, count(*) from course
group by deptNo;

Dr. Mahesha
Restrictions on Updating
Views
▪ Updates on views which do not include Primary Key of
base table, are also not permitted

▪ For example, updates on the following view are not


allowed

▪ Create a view StudentPhone with Student name and


phone number.

create view StudentPhone(sname,sphone) as


(select name, phone from student)

View StudentPhone does not include Primary key of the base


table.
Dr. Mahesha
Allowed Updates on
Views
Updates to views are allowed only if

▪ Defined on single base table


▪ Not defined using ‘group by’clause and aggregate
functions
▪ Include Primary Key of base tableAllowed

UPDATE view, also changes the value in base table from


where the attributes are derived for the view

Dr. Mahesha
Stored
Procedures
▪ Stored procedures are procedures or functions that are
stored and executed by the DBMS at the database server
machine.

▪ Stored procedures improve performance as these


procedures
are compiled only at the time of their creation
▪ Hence whenever these procedures are called for the
execution
the time for compilation is saved
▪ Stored procedures are beneficial when a procedure is
required by different applications located at remote sites, it
is stored at server and invoked by any of the applications
Dr. Mahesha
Stored
Procedures
▪ Stored procedures may consists of simple SQL
commands like INSERT, SELECT, UPDATE etc.,
▪ They can accept input parameter and pass values to
output parameters
▪ A stored procedure can be created as

▪ Parameters and local declarations are optional and if


declared
must be valid SQL data types.
Dr. Mahesha
Stored
Procedures

▪ Parameter declared must have one of three modes, IN, OUT, or


INOUT specified for it.

▪ IN mode are argument passed to the stored procedure and act


like a
constant
▪ OUT act like an un-initialized variables
▪ INOUT have combined properties of both IN and OUT mode.
They contain values to be passed to the stored procedure and
also can be assigned values to be returned from the stored
procedure
Dr. Mahesha
Stored
Procedures
▪ Ex. Create procedure to update the value of price of a book
with a given ISBN of relation BOOK

▪ Once the procedure is created, it can be called in any


application for execution. The calling statement can be
specified as

▪ The statements for calling procedure and function


can be
specified as
Dr. Mahesha
Stored
Procedure
▪ Stored procedures can be writtenin general
purpose programming language
▪ It is necessary to specify language and the file name
where program code is stored.
▪ In such case procedure can be created as

▪ Procedures can be
dropped

Dr. Mahesha
Trigger
s
▪ Trigger is a type of stored procedure that is executed
automatically when some database related events like insert,
update, delete etc., occur.

▪ Triggers are mainly needed for the following purpose

Dr. Mahesha
Trigger
s
▪ Although triggers like constraints are defined to maintain
the database integrity, yet they are different in the
following ways

▪ A trigger consists of three


parts

Dr. Mahesha
Trigger
s

▪ Ex. When value in phone attribute of new inserted tuple of


relation AUTHOR is empty, indicating absence of phone
number, the trigger to insert NULL value can be specified
as

Dr. Mahesha
Trigger
s

▪ FOR EACH ROW clause makes sure that trigger is executed for
every single tuple processed
▪ FOR EACH STATEMENT clause specifies the trigger is executed
only once
for specified statement
▪ REFERENCING NEW ROW AS clause can be used to create a
variable for storing the new value of an updated tuple
▪ BEFORE INSERT trigger to set the NULL value no matter what value
was
inserted by a user:
▪ AFTER INSERT trigger, the rows firstly inserted to the table, and
then they are updated.
Dr. Mahesha
Dr. Mahesha
Trigger
s
▪ Triggers can be enabled and disabled by using ALTER
TRIGGER command
▪ The triggers which are not required can be removed by
using DROP Trigger command

▪ The triggers come with lot of advantages. However trigger


must be used with great care as sometimes action of one
trigger can lead to the activation of another trigger.

Dr. Mahesha
Exampl
e

Dr. Mahesha
Exampl
e

Dr. Mahesha
Dr. Mahesha
Dr. Mahesha
Dr. Mahesha
SAILORS ( sid, sname, rating,
age) BOATS (bid, bname,
color) RESERVES (sid, bid,
day)

Dr. Mahesha
Basic SQL
Queries
SAILORS ( sid, sname, rating, age)
BOATS (bid, bname, color)
RESERVES (sid, bid, day)

1. Find the names and ages of all sailors


2. Find all sailors with a rating above 7
3. Find the names of sailors who have reserved boat number
103
4. Find the sid’s of sailors who have reserved a red boat
5. Find the ages of sailors whose name begins and ends with
B and has at least three characters

Dr. Mahesha
UNION, INTERSECT and
EXCEPT
SAILORS ( sid, sname, rating, age)
BOATS (bid, bname, color)
RESERVES (sid, bid, day)

1. Find the names of sailors who have reserved a


red or a green boat
2. Find the names of sailors who have reserved both
a red and a green boat
3. Find the sids of all sailors who have reserved red
boats but not green boats

Dr. Mahesha
Nested queries

SAILORS ( sid, sname, rating, age)


BOATS (bid, bname, color)
RESERVES (sid, bid, day)

1. Find the names of sailors who have


reserved boat number 103
2. Find the sid’s of sailors whoa have
reserved a red boat

Dr. Mahesha
Aggregate
operation
SAILORS ( sid, sname, rating, age)
BOATS (bid, bname, color)
RESERVES (sid, bid, day)

1. Find the average age of all sailors


2. Find the average age of sailors with a rating
of 10
3. Find the name and age of oldest sailor

Dr. Mahesha
Basic SQL
Queries
SAILORS ( sid, sname, rating, age)
BOATS (bid, bname, color)
RESERVES (sid, bid, day)

1. Find the names and ages of all sailors


2. Find all sailors with a rating above 7
3. Find the names of sailors whoa have reserved boat
number 103
4. Find the sid’s of sailors whoa have reserved a red boat
5. Find the ages of sailors whose name begins and ends
with B and has at least three characters

Dr. Mahesha
Dr. Mahesha
Dr. Mahesha
UNION, INTERSECT and
EXCEPT

1. Find the names of sailors who have reserved a


red or a green boat
2. Find the names of sailors who have reserved both
a red and a green boat
3. Find the sids of all sailors who have reserved red
boats but not green boats

Dr. Mahesha
UNION, INTERSECT and
EXCEPT
1. Find the names of sailors who have reserved a
red or a green boat

Dr. Mahesha
UNION, INTERSECT and
EXCEPT
2. Find the names of sailors who have reserved both
a red
and a green boat

Dr. Mahesha
UNION, INTERSECT and
EXCEPT
3. Find the sids of all sailors who have reserved red
boats but
not green boats

Dr. Mahesha
Nested queries

1. Find the names of sailors who have reserved


boat number 103

Dr. Mahesha
Set – Comparison
Operators
1. Find sailors whose rating is better
than some sailor called Horatio

Dr. Mahesha
Set – Comparison
Operators
2. Find the sailors with the highest
rating

Dr. Mahesha
Aggregate
operation

Dr. Mahesha

You might also like