You are on page 1of 36

Database Engineering

Lecture 3 c
Korra Sathya Babu
Department of Computer Science
NIT Rourkela
11/29/15

Lecture 3

SQL
Structured Query
Language

SQL is a Standard - BUT....


SQL is an ANSI (American National Standards Institute)
standard computer language for accessing and
manipulating database systems. SQL statements are used
to retrieve and update data in a database. SQL works with
database programs like MS Access, DB2, Informix, MS SQL
Server, Oracle, Sybase, etc.
Unfortunately, there are many different versions of the
SQL language, but to be in compliance with the ANSI
standard, they must support the same major keywords in
a similar manner (such as SELECT, UPDATE, DELETE,
INSERT, WHERE, and others).
Note: Most of the SQL database programs also have their
own proprietary extensions in addition to the SQL
standard!

SQL
Structured Query Language (SQL) is a language
that provides an interface to relational database
systems
SQL was developed by IBM in the 1970s for use
in System R, and is a de facto standard, as well as
an ISO and ANSI standard
SQL encompasses DML (Data Manipulation
Language), for INSERTs, UPDATEs, DELETEs and
DDL (Data Definition Language), used for creating
and modifying tables and other database
structures
The development of SQL is governed by
standards. A major revision to the SQL standard
was completed in 1992, called SQL2. in 1999
11/29/15
Lecture 3
4
called
SQL3 support
object extensions and
are

SQL Standards
1986 SQL86 (SQL87) Adopted by ANSI (86) and
ISO(87)
1989 SQL89 (FIPS 127-1) After minor revision
adopted by Federal Information Processing Systems
1992- SQL92 (SQL2 or FIPS 127-2) Major Revisions
1999- SQL99 (SQL3) - Added regular expression matching, recursive
queries, triggers, support for procedural and control-of-flow statements, nonscalar types, and some object-oriented features

2003- SQL2003 Introduced XML-related features,window


functions

2006- SQL2006 standardised Complete XML facility and Xquery


2008- SQL2008 Instead of triggers, truncates

11/29/15

Lecture 3

Oracle

The RDBMS Oracle developed by company called


Relational Software Incorporation (RSI) by Larry Ellison, Bob
Minar and Ed Dates in 1977
In 1979 this company delivered its first commercial
product called DQL RDBMS
RSI turns to Oracle: Source of a divine communication
delivered in response to a petitioner's request

11/29/15

Lecture 3

SQL Queries
With SQL, we can query a database and have a result set returned.
A query like this:
SELECT LastName FROM Persons

Gives a result set like this:


LastName
Hansen
Svendson
Pettersen

Classification of SQL Commands

DDL- Data Definition Language: statements used to define the


database structure or schema. Some examples:
CREATE, ALTER, DROP, TRUNCATE, COMMENT, RENAME

DML- Data Manipulation Language: statements used for


managing data within schema objects. Some examples:
SELECT , INSERT, UPDATE, DELETE, MERGE,CALL, LOCK TABLE,
DCL- Data Control Language. Some examples:
GRANT, REVOKE
TCL- Transaction Control: statements used to manage the
changes made by DML statements. It allows statements to be
grouped together into logical transactions.
COMMIT - save work done
SAVEPOINT - identify a point in a transaction to which you can later
roll back
ROLLBACK - restore database to original since the last COMMIT
SET TRANSACTION - Change transaction options like isolation level
and what rollback segment to use
DML are not auto-commit. i.e. you can roll-back the operations, but
DDL are auto-commit

SQL Data Manipulation Language


(DML)

SQL (Structured Query Language) is a syntax for executing


queries. But the SQL language also includes a syntax to
update, insert, and delete records.
These query and update commands together form the Data
Manipulation Language (DML) part of SQL:

SELECT - extracts data from a database table


UPDATE - updates data in a database table
DELETE - deletes data from a database table
INSERT INTO - inserts new data into a database table

SQL Data Definition Language (DDL)


The Data Definition Language (DDL) part of SQL permits
database tables to be created or deleted. We can also define
indexes (keys), specify links between tables, and impose
constraints between database tables.
The most important DDL statements in SQL are:

CREATE TABLE - creates a new database table


ALTER TABLE - alters (changes) a database table
DROP TABLE - deletes a database table
CREATE INDEX - creates an index (search key)
DROP INDEX - deletes an index

Hospital Database

BILLED(BILL_NO: NUMBER(5) PK, PATIENT_NO: NUMBER(9), ITEM_CODE:


NUMBER(5), CHARGE: NUMBER(7,2))

TREATS(PHY_ID: NUMBER(4) PK, PATIENT_NO: NUMBER(4) PK,


PROCEDURE_NO: NUMBER(4) PK, DATE_TREATED: DATE PK,
TREAT_RESULT: VARCHAR2(50))

ITEM(ITEM_CODE: NUMBER(4) PK, DESCRIPTION: VARCHAR2(50),


NORMAL_CHARGE: NUMBER(7,2))

PHYSICIANS(PHY_ID: NUMBER(4) PK, PHY_PHONE: CHAR(8), PHY_NAME:


VARCHAR2(50))

PATIENT(PATIENT_NO: NUMBER(4) PK, DATE_LAST_TREATED: DATE,


PAT_NAME: VARCHAR2(50), ROOM_LOCATION: CHAR(4))

ROOM(ROOM_LOCATION: CHAR(4) PK, ROOM_ACCOMMODATION:


CHAR(2), ROOM_EXTENTION: NUMBER(4))

PROCEDURES(PROCEDURE_NO: NUMBER(4) PK, PROC_DESCRIPTION:


VARCHAR(50))
11/29/15

Lecture 3

12

SQL SELECT statement


The SELECT statement is used to select data from a table. The
tabular result is stored in a result table (called the result-set)
Syntax
SELECT [ALL/DISTINCT/*/expression] Columnlist [AS Column Alias]
FROM <tablename> [Table Alias]
WHERE <predicate>
GROUP BY <column-name(s)>
HAVING <search condition>
ORDER BY column-name

The order of the clauses in the SELECT statement is important


This command is also called Retrieval command coming under
Data Query Language
Select command is similar to Project operation in RA
11/29/15

Lecture 3

13

Sample Queries (1)


Display patient_no, item_code and charge for patient having
number 1117
SELECT patient_no, item_code, charge
FROM billed
WHERE patient_no=1117;

Display Different charges applicable on bills


SELECT DISTINCTcharges
FROM billed;

Display all bills details for patient 1116


SELECT *
FROM billed
WHERE patient_no=1116

11/29/15

Lecture 3

14

Operators
Arithmetic Operators
equal to (=), less than (<), greater than (>), less than equal to (<=) ,
greater than equal to(>=), not equal to (!=, <>, ^=)

LIKE operator
LIKE Sa%
LIKE _ _ I %

IS NULL, IS NOT NULL operators


column containing NULL has no value or unknown, column containing IS
NOT NULL has some value and is known

IN, BETWEEN operators


institute IN(NIT, IIT) or Code IN(1,2,3)
Rollno BETWEEN 65 AND 96

Logical Opeators (AND, OR, NOT)


institute = NIT OR institute= IIT
batchlers=NIT AND masters= IIT
NOT categoryinstitute= Open University
11/29/15

Lecture 3

15

Queries (2)

Display all charges greater than Rs. 5.00/- for patient number 1116
SELECT charge
FROM billed
WHERE patient_no=1116 and charge>5.00;

Display all charges for either patient 1116 or 1117


SELECT patient_no, charge
FROM billed
WHERE patient_no=1116 or patient_no=1117;

Find out how many bills have been issued to patient 1117
SELECT count(*)
FROM billed
WHERE patient_no=1117

11/29/15

Lecture 3

16

Queries (3)

Display a calculated charge from table item that is increased by 6%. The
calculated charge column should bear the name as Increased Charge
SELECT normal_charged, normal_charges * 1.06 Increased Charge
FROM Item;

Findout howlong a patient was in hospital


SELECT patient_no, date_discharged, date_admitted, (date_discharged
date_admitted + 1)
AS No. of Days In
FROM patient ;

List all the patients who were charged between Rs.160 and Rs.170 for
item 2245
SELECT patient_no, charge
FROM billed
WHERE item_code=2245 AND charge BETWEEN 160 AND 170;

11/29/15

Lecture 3

17

SQL Functions
Character functions
concat, initcap, lower, lpad, rpad, substr, upper, ltrim, instr, length

Numeric functions
mod, power, round, sign, sqrt, trunc

Date functions
add_months, last_day, months_between, next_day, round, trunc

Data Type conversion functions


to_char, to_date, to_number

Miscellaneous functions
nvl, decode

Aggregate (group) functions


avg, count, max, min, sum

11/29/15

Lecture 3

18

Joins

A JOIN is a query that combines rows from two or more relations

The WHERE clause is most often used to perform the JOIN


function where two or more tables have common columns
example
SELECT patient_no, description, normal_charge, charge
FROM billed B, item I
WHERE B.item = I.item_code ;

When values within a column of a table are to be compared,


self-join is used. example.
List the Ids of patients treated by same physician
SELECT t1.patient_no, t2.patient_no, phy_id
FROM treats t1, t2
WHERE t1.phy_id = t2.phy_id
AND t1.patient_no <> t2.patient_no ;

11/29/15

Lecture 3

19

Joins
An Inner Join selects only those rows from both the joining
tables
Outer Join selects all the rows that satisfy the join condition
and those rows from one table for which no rows from the
other table satisfy the join condition
The (+) outer join operator is used for which there will be
NULL values in terms of matching
example.
Display the patient_no, name and charge for all the patients
irrespective of the fact whether the patients has not yet
incurred any charges
SELECT p.patient_no, pat_name, b.charge
FROM billed b, patient p
WHERE p.patient_no = b.patient_no (+) ;

11/29/15

Lecture 3

20

Example
Sn
o

Sname

22
29

Sid

bid

day

bid

bname

color

22

101

10/10/08

101

Interlake

Blue

22

102

10/10/08

102

Interlake

Red

33.
0

22

103

10/08/08

103

Clipper

Green

22

104

10/07/08

104

Marine

red

Ratin
g

Age

Dustin
e

45.
0

Brutus

31

Lubbe
r

55.
5

31

102

10/10/08

32

Andy

25.
5

31

103

11/06/08

31

104

11/12/08

58

Rusty

10

35.
0

64

101

09/05/08

64

102

09/08/08

74

103

09/08/08

64

Horati
o

71 Instance
Zorba of 10
Sailors

74

Horati
o

85 11/29/15
Art

35.
0
16.
0

35.
0

25.
5

Instance of Boats

Instance of Reserves

Lecture 3

21

AND, OR
Find the names of sailors who have reserved a green boat or
red boat
SELECT S.sname
FROM Sailors S, Reserves R, Boats B
WHERE S.sid = R.sid AND R.bid = B.bid
AND (B.color = red OR B.color=green) ;

Find the names of sailors who have reserved a green boat and
red boat
Can we simply replace OR with AND ?
SELECT S.sname
FROM Sailors S, Reserves R, Boats B
WHERE S.sid = R.sid AND R.bid = B.bid
AND (B.color = red AND B.color=green) ;
11/29/15

Lecture 3

22

AND
The above query returns names of sailors but the integrity
constraint says that a bid cannot have 2 values. So the query
will always return an empty set. The following query can be
used with AND operator.
Find the names of sailors who have reserved a green boat and
red boat
SELECT S.sname
FROM Sailors S, Reserves R1, Boats B1, Reserves R2, Boats B2
WHERE S.sid = R1.sid AND R1.bid = B1.bid
AND S.sid = R2.sid AND R2.bid = B2.bid
AND B1.color = red AND B2.color=green;

Still the above query looks complex


11/29/15

Lecture 3

23

UNION, INTERSECT
Find the names of sailors who have reserved a green boat or
red boat
SELECT S.sname
FROM Sailors S, Reserves R, Boats B
WHERE S.sid = R.sid AND R.bid = B.bid AND B.color = red
UNION
SELECT S2.sname
FROM Sailors S2, Reserves R2, Boats B2
WHERE S2.sid = R2.sid AND R2.bid = B2.bid AND B2.color = green) ;

Find the names of sailors who have reserved a green boat and
red boat
SELECT S.sname
FROM Sailors S, Reserves R, Boats B
WHERE S.sid = R.sid AND R.bid = B.bid AND B.color = red
INTERSECT
SELECT S2.sname
FROM Sailors S2, Reserves R2, Boats B2
WHERE S2.sid = R2.sid Lecture
AND R2.bid
= B2.bid AND B2.color
11/29/15
3
24= green) ;

EXCEPT (MINUS)

Find the sids of sailors who have reserved a red boat but not green
boat
SELECT R.sid
FROM Reserves R, Boats B
WHERE R.bid = B.bid AND B.color = red
EXCEPT
SELECT R2.sid
FROM Reserves R2, Boats B2
WHERE R2.bid = B2.bid AND B2.color = green) ;

The result of all the above queries is derived first and then the
operator UNION, INTERSECT, EXCEPT is applied
All of the above used operators eliminate duplicate by default
To include duplicate tuples use UNION ALL, INTERSET ALL,
EXCEPT ALL

11/29/15

Lecture 3

25

Nested Queries

Find the names of sailors who have reserved boat 103


SELECT S.sname
FROM Sailors S
WHERE S.sid IN ( SELECT R.sid
FROM Reserves R
WHERE R.bid = 103) ;

At first the nested sub query computes the set of sids who
have reserved boat 103 (ex. The set contains 22, 31 and 74)
The top level query retrieves the names of sailors whose sid is
in this set
The IN operator allows to test whether a value is in a given set
of elements
To find the names of sailors who have not reserved the boat
103 just put NOT before IN operator
11/29/15

Lecture 3

26

Multiple Nested Queries

Find the names of sailors who have reserved a red boat


SELECT S.sname
FROM Sailors S
WHERE S.sid IN ( SELECT R.sid
FROM Reserves R
WHERE R.bid IN (SELECT B.bid
FROM Boats B
WHERE B.color = red) ;

Operators that can be used in the Nested queries are ANY,


SOME, ALL, EXIST

11/29/15

Lecture 3

27

Correlated Nested Queries

In nested query the inner query is completely independent of the


outer query
The inner sub query may sometimes depend on the row currently
being examined in the outer query
Find the names of sailors who have reserved boat 103
SELECT S.sname
FROM Sailors S
WHERE EXISTS ( SELECT *
FROM Reserves R
WHERE R.bid = 103
AND R.sid = S.sid) ;

The sub query clearly depends on the current row S and must
be re-evaluated for each row in Sailors
The occurrence of S in the sub query (S.sid) is called a
correlation
11/29/15

Lecture 3

28

Correlated Nested Queries

The ANY and ALL are also set comparison operators along with EXIST,
IN
SOME is also a set comparison operator but its just a synonym of ANY
Find the sids of sailors whose rating is better than some sailor called
Horatio
SELECT S.sid
FROM Sailors S
WHERE S.rating > ANY ( SELECT S2.rating
FROM Sailors S2
WHERE S2.name = Horatio) ;

If several sailors called Horatio exist then the above query


finds all sailors whose rating is better than that of some sailor
called Horatio
If no sailor called Horatio is present then the comparison
S.rating > Any returns false and the query returns empty
answer set
11/29/15

Lecture 3

29

Correlated Nested Queries

Find the sids of sailors whose rating is better than every sailor called
Horatio
SELECT S.sid
FROM Sailors S
WHERE S.rating > ALL ( SELECT S2.rating
FROM Sailors S2
WHERE S2.name = Horatio) ;

If no sailor called Horatio is present then the comparison


operation will return a true and the query will return all the
sailors value

Find the sids of sailors with highest rating


SELECT S.sid
FROM Sailors S
WHERE S.rating >= ALL ( SELECT S2.rating
FROM Sailors S2) ;
11/29/15

Lecture 3

30

More Queries

Find the name of the sailor who has the kth highest rating
SELECT S.sname
FROM Sailors S
WHERE k = ( SELECT count (distinct S2.rating)
FROM Sailors S2
WHERE S.rating <= S2.rating) ;

Find the name of the sailor who has the first three high rating
SELECT S.sname
FROM Sailors S
WHERE 3 >= ( SELECT count (distinct S2.rating)
FROM Sailors S2
WHERE S.rating <= S2.rating) ;

Find the three name of the sailor with least rating


SELECT S.sname
FROM Sailors S
WHERE 3 <= ( SELECT count (distinct S2.rating)
FROM Sailors S2
WHERE S.rating >= S2.rating) ;
11/29/15

Lecture 3

31

Views
Views are logical tables of data extracted from existing
(generally multiple) tables. It can be queried just like a table but
doesnt require space
Advantages
Security: Can be used to hide sensitive columns
Convenience: Can be used to hide complex queries involving multiple
relations or queries that are used commonly by many users
Check options can be provided to UPDATE and INSERT of views

Syntax
CREATE or REPLACE VIEW <Viewname> AS <query> [WITH READ ONLY]
[WITH CHECK OPTION];
ex. CREATE VIEW EMP_VIEW AS SELECT emp_no, emp_name from emp;
ex. CREATE OR REPLACE VIEW STUDENT AS SELECT * FROM STUDENTDB
WHERE INSITITUTE = NITR WITH CHECK OPTION ;

Displaying the view


SELECT * FROM <Viewname>

To drop a view
DROP VIEW <Viewname>;
11/29/15

Lecture 3

32

Sequences
A special database object that generates integers according to
specified rules. Generally used for generating primary key
values automatically
Syntax
CREATE SEQUENCE <Sequence_name>
[INCREMENT BY <integervalue>
START WITH <integervalue>
MAXVALUE <integervalue>/ NOMAXVALUE
MINVALUE <integervalue>/ NOMINVALUE
CYCLE/NOCYCLE]

example
CREATE SEQUENCE countdown100
START WITH 100
INCREMENT BY -1
NOMAXVALUE
CYCLE
ORDER;
11/29/15

Lecture 3

33

Sequences
Sequences are referenced using CURRVAL and NEXTVAL virtual
columns
Once the NEXTVAL column is referenced, the value in CURRVAL
becomes the value in NEXTVAL, and prior value in CURRVAL is
lost
example usage
INSERT INTO expense (expense_no, empid, amt, submit_date)
VALUES(expense_sequence_01.nextval, 2353, 25000, 08-NOV-08);

11/29/15

Lecture 3

34

CREATE TABLE Statement

The CREATE statement is used to create a table.

Syntax
CREATE TABLE <table_name>
(<column 1> <data_type> <size> [Integrity constraint] [REFERENCES
<tablename> [ON DELETE CASCADE]],

<column n> <data_type> <size> [Integrity constraint],


[Integrity constraint]
);

example
CREATE TABLE employee (
ecode number(4) Primary Key,
ename varchar2(18),
grade char(1),
);

11/29/15

Lecture 3

35

Integrity Constraints
Unique Constraint
No two rows have the same value

Not Null Constraint


The column shouldnt hold blank values

Primary Key Constraint


Unique + Not Null

Default Constraint
A default value can be specified for the column

Check Constraint
Limits values that can be inserted into a column

Foreign Key Constraint


Enforcing a parent-child relationship between tables such that child
records cannot be appended without a parent record and parent record
cannot be deleted when child records exist

11/29/15

Lecture 3

36

Some other basic


commands
INSERT INTO <tablename> VALUES (values..)

DESCRIBE <Tablename>
DELETE FROM <Tablename> WHERE <Predicate>
UPDATE <Tablename> SET <column> = <value>
Alter Table <Tablename> <ADD>/ <MODIFY> (<column>
<type> <width>)
CREATE USER <username> identified by <password>
GRANT CONNECT, RESOURCE, DBA TO <username>

11/29/15

Lecture 3

37

You might also like