0% found this document useful (0 votes)
7 views36 pages

DBMS Unit 3

This document provides an overview of SQL, focusing on its core components, including Data Definition Language (DDL) commands such as CREATE, and various data types. It also covers SQL queries, including SELECT statements, JOIN operations, and constraints, along with advanced topics like NULL handling and nested queries. Additionally, it discusses large object types and aggregate functions, emphasizing the importance of proper syntax and structure in SQL commands.

Uploaded by

ithvika
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 views36 pages

DBMS Unit 3

This document provides an overview of SQL, focusing on its core components, including Data Definition Language (DDL) commands such as CREATE, and various data types. It also covers SQL queries, including SELECT statements, JOIN operations, and constraints, along with advanced topics like NULL handling and nested queries. Additionally, it discusses large object types and aggregate functions, emphasizing the importance of proper syntax and structure in SQL commands.

Uploaded by

ithvika
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/ 36

DBMS

UNIT -3
SQL

feedback / corrections : [email protected] VIBHAMASTI


© vibha’s notes 2021
SQL

Declarative
language

SQL GIS)
core
components extensions
leg
• : + :

DDL

1. CREATE

Schemas tables , domains , views , assertions , triggers
,

PSQL : database

1. I create schema

CREATE SCHEMA COMPANY AUTHORIZATION ‘Jsmith’;

named of
catalog collection schemas
-

-
Schema called INFORMATION - SCHEMA

Default root PSQL)


owner :
Cpostgres in

Default schema (
creating schema) : owner name

1. 2 Create Table


Default schema (creating table) : PUBLIC

PUBLIC schema
CREATE TABLE EMPLOYEE ←


Prefix table name with schema name while
creating

CREATE TABLE COMPANY.EMPLOYEE


-
schema
© vibha’s notes 2021

Alternate : create schema name auth name C
- y -

- , I

create table statements

7
1.3 Virtual Relations

CREATE VIEW NAME AS (QUERY);

column name attribute constraint


- -

type ,

Tl

© vibha’s notes 2021


Attribute types

(a)
String
Fixed CHARM CHARACTER Cn)
length :

Variable VARCHAR (n) CHAR VARYING CHI ,


length :

CHARACTER VARYING (n)

1 '
Enclose in
single quotes


Default n = 1

Fixed
length blank
padded

: -

(b) Numeric

INTEGER , SMALLINT
Integer INT

:
,


Float : FLOAT , REAL DOUBLE PRECISION
,

'

Decimal : DECIMAL Ci ,j) DECCI ,j) ,


NUMERIC Cigj)
,

-
i :
precision ( total
digits)
of decimal default =D
-

j : scale Cno .

places -

DECIMAL (5) 2) ,
DECCIO)

(c) Bit
string
1311Th) BIT VARYING In )
Fixed length Variable length :

:
,

Default n = I

'
and prefixed 1001 )
'
Enclosed in l '
with B
leg :B© vibha’s

notes 2021
(d) Boolean


True and False land unknown for 3- valued logic)

(e) Date

Ten
positions :
yyyy MM DD
. - -

6
Enclosed '
in
single quotes


Sometimes prefixed with DATE

' '

Eg DATE 2019-02-28

:

Cf) Time

Eight positions HH : MM :S

:


Time Ci) -
i extra
digits for decimal of seconds

É!
(g) Timestamp

cfraction of second)
DATE + TIME -1 6
positions

"" "
"" " " "" " "
"""

' '

TIMESTAMP 2021-09-28 19:40:30 643792 .

( h) Interval


Relative value to increment / decrement date ,
time , timestamp
types

© vibha’s notes 2021


Large Object Types

(a) CLOB

documents)
Character
large object [ text


PSQL : text ( 1GB Max )


Oracle : Max 4GB

Eg book review clob(10KB)


(b) BLOB

Binary Large Objects


videos etc
Images
-

( Max 1GB)
PSQL :
bytea
-


Oracle : Max 4GB

Eg image blob(10MB)

:

movie blob(2GB)
PSQL to insert images
use
psycopz

:

© vibha’s notes 2021


1.4 Create Domain


Renamed default datatype with or without constraints

for domain
Easy to
change datatype

Improves readability

Eg CREATE DOMAIN SSN_TYPE AS CHAR(9);



:

create
is
type
Defined c. UDTs )
User Types

Object oriented apps (not RDBMS)



-

PSQL : relational object DBS

VARCHARC 907 Street VARCHARC90))


CREATE TYPE full - address AS C.
city >
;

© vibha’s notes 2021


Constraints in SQL

1. Attribute constraints

1. 1 NOT NULL

Implicit for PK

1.2 DEFAULT
-
DEFAULT (value >

© vibha’s notes 2021


© vibha’s notes 2021
2. SELECT FROM- -
WHERE

2.2
Aliasing
SELECT E. f-name
,
5. Lname from EMPLOYEE AS E EMPLOYEE AS S
,

WHERE E. SSN = 5. SSN

2- 3 WHERE
Missing

select all rows


IT relational operation


Cartesian product -

multiple tables

SELECT * FROM EMPLOYEE DEPARTMENT


,

2-4
Joining
SELECT JOIN DEPARTMENT ON CDNO
* FROM EMPLOYEE DEPARTMENT DNVMER
)j
-
-

© vibha’s notes 2021



Can
specify
-
LEFT OUTER JOIN
-

NATURAL JOIN

-
RIGHT OUTER JOIN

SELECT * FROM EMPLOYEE DEPARTMENT NATURAL JOIN DEPARTMENT


,

2-5 Distinct Project

SELECT DISTINCT ESSN FROM DEPENDENT ;

2.6 Default Project

default : select
By all

SELECT ALL SALARY FROM EMPLOYEE ;

Query 0. Retrieve the birth date and address of the employee(s)


whose name is ‘John B. Smith’.

Result :

2.7 Set operations


UNION
°
EXCEPT ( difference) postgres ,
MINUS -

Mysql

INTERSECTION
© vibha’s notes 2021
2.8 Pattern
Matching

Postgres only -
varchar

Oracle - dates also


LIKE

_
: one char

% :
any number of chars

'
'
SELECT f- NAME , ADDRESS FROM EMPLOYEE WHERE ADDRESS LIKE % Houston
-1 .
;

-
For dates in
postgres
-

typecast
'
SELECT BDATE FROM EMPLOYEE WHERE BDATE : TEXT
'
LIKE 1965-1
'
- .
;

2-9 BETWEEN

Including

SELECT . - . WHERE SALARY BETWEEN 10000 AND 50000 ;

2.10 Finalized Project / Arithmetic operations


*
SELECT FNAME ,
SALARY ,
I I
-
SALARY AS HIKED FROM EMPLOYEE ;

of
2. 11
Ordering Tuples


ORDER BY
u
Default : ASC

DESC
© vibha’s notes 2021
SELECT LNAME FROM EMPLOYEE ORDER BY SALARY DESC ;


Order by multiple columns

SELECT * FROM EMPLOYEE DEPARTMENT JOIN DEPARTMENT ON CDNO -_ DNUMER)


,

ORDER BY DNAME f-NAME ;


,

Diff orders

SELECT * FROM EMPLOYEE DEPARTMENT JOIN DEPARTMENT ON CDNO -_ DNUMER)


,

ORDER BY DNAME DESC f-NAME ;


,

SELECT * FROM EMPLOYEE DEPARTMENT JOIN DEPARTMENT ON CDNO -_ DNUMER)


,

ORDER BY DNAME DESC f-NAME ;


,

3. INSERT

3.1 Insert with select

© vibha’s notes 2021


4. DELETE

5. UPDATE

ADVANCED DATATYPES LARGE OBJECTS

Postgres
-

( Oracle dob>
1. text :
large text -

2.
bytea :
images ( byte array) ( Oracle -
blob)

text
3. ntext : even
larger

psycopg 2 :
python

© vibha’s notes 2021


COMPLEX SQL

1. 1 NULL 4 Three Valued


-

logic


NULL due to 3 reasons

1. Unknown value. A person’s date of birth is not known, so it is


represented by NULL in the database. An example of the other
case of unknown would be NULL for a person’s home phone
because it is not known whether or not the person has a home
phone.

2. Unavailable or withheld value. A person has a home phone


but does not want it to be listed, so it is withheld and
represented as NULL in the database.

3. Not applicable attribute. An attribute LastCollegeDegree


would be NULL for a person who has no college degrees
because it does not apply to that person.

Three valued True False Unknown


logic ( not boot)
-
- -

, ,

© vibha’s notes 2021


Eg

1.2 Nested Queries , Tuples and set / Multi set comparisons

nested
using

© vibha’s notes 2021


Tuple comparisons

1. 2-1 IN

where cessn , pno) in ( select essn


pno where )
. . .

, . . .

IN
operator is same as =
ANY

1- 2-2 ANY 9 ALL

Sats in dept 5
salary > all
-


=
all 4 > all
may give 0 in most instances
.
=
any or = some

1. 2-3 ALIAS

© vibha’s notes 2021


PSQL : no need to write AS C
optional)
-

1. 3 CORRELATED QUERIES

correlated queries : for tuple in inner


every outer query , query

is executed ( inner uses result of outer


query)
query


normal : inner then outer

more

✗ optimised

1. 4 EXISTS and UNIQUE

check if inner
query is
empty
.

like IN

© vibha’s notes 2021


(a)

select f-name , I name from


employee except

from )
( select f-name
,
I name
employee , dependent where essn -
- Ssn

(b)

select f-name from where not C select


,
I name
employee ssn in

essn from dependent)

Eg

Ca)

select distinct frame from


,
I name
employee , department ,

dependent where ssh -


-

mgr -
ssn and ssn = essn ;

© vibha’s notes 2021


1- 4.1 For all / division is SQL

Using EXISTS and NOT EXISTS


Q3: Retrieve the name of each employee who works on all the
projects controlled by department number 5

leftover projects

÷.i÷:*
emp

É
have leftover

works on

© vibha’s notes 2021


1. 5
Explicit set of values in where

1. 6 JOIN in FROM

here also NULL ignored


1.6.1 Natural Join

Col

gives Cartesian prod if names do not match

1.6.2 Outer Joins


shows emps w/o super
y also

© vibha’s notes 2021


Alternate syntax coracle only)

1.7 Functions
Aggregate

from

NULL
ignored aggregate tune on
particular cot


count (* ) includes NULL in few columns

min sum count


Max
avg

, , , ,

of if group used ( filter


instead where
having by
-

use

out
groups)

© vibha’s notes 2021


select clause project)
in
group by is
very imp

valid if I value
per group

is
Group by NULL one
group

Group by with
having
°

© vibha’s notes 2021


Result

© vibha’s notes 2021


Group by multiple

Q: Count the total number of employees whose salaries exceed


$40,000 in each department, but only for departments where
more than five employees work

incorrect : will first filter emp


before
counting dept
execution
/ / size

order u

correct :

dnos
get →
{ }

© vibha’s notes 2021


1. s with and case clauses

WITH : common table expressions CCTE )

write statements
auxiliary
-

define temp table for one


query
-

with
c- optional
abc
keyword
as
eg :

C
complex query
:
7
select * from abc
;


WITH mainly for readibility ; can use nested query instead


CASE : like switch case

© vibha’s notes 2021


Assertions Eg Triggers

2- 1 ASSERTIONS

Assertions : constraints outside scope of built-in relational


.

model constraints

Not in
pg , only Oracle
, MySQL

2-2 TRIGGERS

event
Triggers : actions taken when occurs
-

event CECA rule )


components CS) condition , action

:
,

Before or after event

faction (function
/ procedure)
© vibha’s notes 2021
( can return) Cno ret)
Functions

Idf → list

Function : 0 or more params

Procedural language for psql plpgsql (we use)


:

others
-

can use

CREATE [OR REPLACE ] FUNCTION name


Cparams)
RETURNS type
LANGUAGE plpgsql
AS

$$
declare
- -
variable declaration ( local)

begin
logic
- -

end ;
$$

© vibha’s notes 2021


Trigger

CREATE TRIGGER -

/
BEFORE AFTER -

ON
-

FOR EACH ROW EXECUTE PROCEDURE

CREATE PROCEDURE
no return
cursor.cat/ 1)

"

call procedure cur .


execute (
"
CALL procedure lets ,%s) ,
( )
'
wall , Val 2 ) )
cur call proc ( tune
'
.
-
name ,
© vibha’s notes 2021
VIEW

virtual table


can make a view of a
join

strategies

modification
(a)
Query approach

to Csub
Maps view name
query query?

-

maps

(b) View materialization / Realisation

stores view
physically

Updatim strategies

© vibha’s notes 2021


-

immediate update
lazy update [most)
-

periodic update
-

Updation of views

■ A view with a single defining table is updatable if the view


attributes contain the primary key of the base relation, as well as
all attributes with the NOT NULL constraint that do not have
default values specified.

■ Views defined on multiple tables using joins are generally not


updatable.

■ Views defined using grouping and aggregate functions are not


updatable.

UPDATE < > SET C 7 WHERE C 7

view constraints

CREATE VIEW C > As c > WITH CHECK OPTION ;

Fails row constraint otherwise

view as an Authorisation mechanism


Restrict access to hidden details

Grant
permissions to users
.

© vibha’s notes 2021


© vibha’s notes 2021
OLAP


Online Analytical Processing


Allows data to be summarised and viewed in different ways
in an online fashion

Negligible delay

For schema
explanation

:

sales (item_name, color, clothes_size, quantity)

Measure attributes : measure some value that be


aggregated

can

upon
attribute
quantity of the sales relation
eg:
-


Dimension attributes : define the dimensions on which measure

attributes are viewed


attributes item name , color and size of the sales relation
eg
-
: -

.
Data that can be modelled as dimension attributes and
measure attributes are called multidimensional data

© vibha’s notes 2021


CROSS TABULATION
1.
/ PIVOT TABLE
-


ROW headers - values of one attr

column headers -

values of another attr

© vibha’s notes 2021


2. DATA CUBE


All combinations with summarisatims

Here : measure attribute


quantity

•5


Number of ways to
group tuples for aggregation
3×3×4 = 36


with all
4×4×5=80

For dimensions, all value combinations on every group


-

in the set 2h are computed for


power

23=8 groups
group by on each group © vibha’s notes 2021
3. PIVOT


cross -

tab is 2D view

dimensions used
change in cross tab

-

4. SLICING


Slice of data cube

5. ROLL UP

Fine granularity → coarse


granularity

6. DRILL DOWN


coarse granularity → fine
granularity

Must be generated

Implementation of OLAP


MOLAP : Multidimensional attr

ROLAP : Relational

HOLAP :
Hybrid

© vibha’s notes 2021

You might also like