Introduction To SQL: Structured Query Language ( Sequel')
Introduction To SQL: Structured Query Language ( Sequel')
Introduction To SQL: Structured Query Language ( Sequel')
Introduction to SQL
Example:
More Examples
Examples Contd.
DATE Example
‘1999-03-03’ (No Y2K problems)
TIME Examples
‘15:30:29’
‘15:30:29.3875’
Deleting a Relation/Table in SQL
Can use DEFAULT even with regular definition (as in Slide 69)
INSERT command
INSERT
INTO Students
VALUES (‘53688’,’Mark’,’mark2345’,23,3.9)
DELETE
FROM Students S
WHERE S.name = ‘Smith’
UPDATE command
UPDATE Students S
SET S.age=S.age+1, S.gpa=S.gpa-1
WHERE S.sid = ‘53688’
CS 5614: Basic Data Definition and Modification in SQL 73
Domains
junkaddress Email,
fromaddress Email,
toaddress Email,
....
Keys
To Specify Keys
Use PRIMARY KEY or UNIQUE
Declare alongside attribute
For multiattribute keys, declare as a separate line
CREATE TABLE takes
( sid CHAR(9),
courseid CHAR(6),
PRIMARY KEY (sid,courseid)
);
Creating Indices/Indexes
Why?
Speeds up query processing time
For Students
Other Properties
"!$#&%('*),+.-&/10(2$35462748%(0(09':!;/&-<=!$#&>?2@2A-&%CBD2@>?2$;!FEG/&2$>:<H0(IJ&KL/1ILKL2@'?ML>N2$O&>N2$'?2$;!;IP!;%C+L&'Q/&'N2$-%(SR$+LJT
U /&&RV!;%(+JW48%X!;#W!$#&2
>?2$0CIY!;%C+L&IJ0L)"+.-&2$0CZ\[]#&2
^&>N'!_%('9>N2$0(IP!;%C+L&IJ0.IL0(KJ2$`&>NIL3GILQIL0CKL2$`&>NIL%CR_IJ&-AO1>?+.R$2$-1/&>?IJ0
46I<Hab+J>]R$>?2@IY!;%C&Kc&2N4d>?2@0(IY!$%(+J&']ab>?+J)eKL%gfD2$+L12$'?Zh[]#&2Q'?2$R@+L&-%(']i*IY!;IJ0(+JKL3548#&%(RY#%(']0(+JKL%CR$IL0jIL&-
-&2$R@0(IL>NIY!$%XfD2h%(&IY!$/&>?2,k:'!;/1-&2$;!;']abIL)"%(0C%(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%(1s?Z2]&+4KJ%XfD2!;#12
!$#&>?2$2
>N2$O&>?2@'?2$;!;IP!;%(+J&']+La5!;#128/1&%(+J}>?2@0(IY!$%(+J&±
² ³k'?%C),O10(2$3j>?%(KJ#!$µs
¶·?¸
¹?º
¹?»¹¼½~¾À¿Á
·?¸¹º¹»¹?¼|½Â
¶·?¸
¹?º
¹?»¹¼½~¾À¿Ã
·?¸¹º¹»¹?¼|½Â
Ä*+Y!;%CR$2S!$#&IY!!$#&2SfÀIL>N%(IL`10(2$'
¸ ¹º¹?»
¹?¼ IJ>?2)"2$>?2@0X<(O10(ILR@2$#&+L0C-&2$>N'?Q/&'?2@-ab+J>O&IY!N!;2$>N
)"IY!$R¡#1%(&KJ1462uR$+J/&0(-#&IfD2W48>?%g!?!$2$F!;#&2QIL`v+fD2W!46+cIL'N±
¶·?Å
¹?Æ
¹;ǹȽ~¾À¿Á
·?Źƹǹ?È|½Â
¶·?É
¹?Ê
¹?˹̽~¾À¿Ã
·?ɹʹ˹?Ì|½Â
·?ÃGÍÀÎGÍÀÏG¶ÑÐ
óLó
ôGÁõö©Á½
÷GøùÀõ;ø
·?ÃGÍÀÎGÍÀÏG¶ÑÐ
ôGÁõö©Ã½
² ³
¶·?¸
¹?º
¹?»¹¼½~¾À¿Á
·?¸¹º¹»¹?¼|½D¹ø|õ;¶©Ã
·?¸¹º¹»¹?¼|½Â
·?ÃGÍÀÎGÍÀÏG¶ÑÐ
ôGÁõö©Á½
ÍGÏÀÍÀ¶
·?ÃGÍÀÎGÍÀÏG¶ÑÐ
ôGÁõö©Ã½
Z Y¥¯$¬Gý°$¬Gþ.¯$¦¨§v¥§vª
«¬G¨®&¯@¦¨§v¥l°±
[]#&2]%(;!;2$>N'?2$RV!;%(+JF² ³´+La!46+Q>?2$0CIY!$%(+L1'² IJ&-,³´%('j!$#&2]'?2V!
+Ja2$0C2$)"2$!$'l!$#&IY!8IJ>?2A%C
²IL&-}³
Z]*KLIL%C&31462*IL'?'N/&)"2h!;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ÉFEGÎhÂ)-.Å/ÀÉ
ø
Áh¨ÅGÈGÈFG0 É211
E ÎhÂÅÀÈGÈF0GÉJ1F1
£ Z8«¬G¥l®l¦¥uj±\[]#1%('h%(' U /&':!FIcR$+.+J0v!$#&%(1KL39%(R$IJ'?2W462Q#&IfD2W!;+.+")"IL;<H&IL)"%(1KcR$+Ll1%(RN!$']IL&-
R$+J&ab/&'N%(+L1'uIL>N%('?%C&KLZ72cR@IL}/1'?2*!;#1%('h+LOv2$>?IP!;+J>]!$+>?2@&IL)"2AI>N2$0(IP!;%C+L&C't&IJ),2zIL&-1ML+L>Q+J&2
+J>t)"+L>N28+Ja
%X!;']IP!?!$>?%(`1/J!;2$'NZu v+L>]2NIL)"O&0C2$39IL'N'?/&)"2h4u2]4uIL;!t!$+,>N2$&IJ),28²
!$+ IJ&-})"I 2
%g!;'hR$+L0C/&),1'!;+`v2AR@IL0(0C2$- e £ 3 e ú IL1- e ZQ[]#&%C't%C't)"+L':!F/&'N2$ab/&0548%X!$#=>N2$0(IP!;%C+L&IJ0IJ0(KL2@`&>?IJ3
0C% 2h'?+L±
5
CS 5614: Misc. SQL Stuff, Safety in Queries 81
Declaring constraints
Domain Constraints
Referential Integrity (Foreign Keys)
More SQL Stuff
Subqueries
Aggregation
SQL Peculiarities
Strange Phenomena
More on Bag Semantics
Ifs and Buts
Triggers
Read Cow Book or Boat Book
More SQL Gory Details
Already Seen
NOT NULL
UNIQUE, PRIMARY KEY etc.
In General
Foreign Keys
An attribute a of R1 is a foreign key if it “references”
the primary key (say b) of another relation R2
In addition, there is a ref. integrity constraint from R1 to R2.
Example
login is a FOREIGN KEY for Students
CREATE TABLE Students
(sid CHAR(9) PRIMARY KEY,
name VARCHAR(20),
login CHAR(8)
REFERENCES Accounts(acct),
age INTEGER,
gpa REAL
);
Alternatively
SQL Subqueries
Given
Students(sid,name,login,age,gpa)
HasCar(sid,carname)
Find
the car of the student with login=”mark”
Traditional Way
SELECT carname
FROM Students, HasCar
WHERE Students.login=’mark’
AND Students.sid=HasCar.sid;
The ‘Subway’
SELECT carname
FROM HasCar
WHERE sid=
(SELECT sid FROM Students
WHERE login=’mark’);
CS 5614: Misc. SQL Stuff, Safety in Queries 87
Aggregation
Given
Students(sid,name,login,age,gpa)
Find
the average of the ages of all the students
Solution
SELECT AVG(age)
FROM Students;
Other Operations
SUM (summation of all the values in a column)
MIN (least value)
MAX (highest value)
COUNT (the number of values), e.g.
SELECT COUNT(*)
FROM Students;
Ordering
Given
Students(sid,name,login,age,gpa)
List
the students in (ascending) alphabetical order of name
Solution
SELECT *
FROM Students
ORDER BY name;
SELECT *
FROM Students
ORDER BY name DESC;
Default is ASC
CS 5614: Misc. SQL Stuff, Safety in Queries 89
Grouping
Given
Students(sid,name,login,age,gpa)
Find
the names of students with gpa=4.0 and
group people with like ages together
Solution
SELECT name
FROM Students
WHERE gpa=4.0
GROUP BY name;
More on Grouping
Given
Students(sid,name,login,age,gpa)
Find
the names of students with gpa=4.0 and
group people with like ages together and
show only those groups that have more than 2 students in it
Solution
SELECT name
FROM Students
WHERE gpa=4.0
GROUP BY name
HAVING COUNT(*) > 2;
CS 5614: Misc. SQL Stuff, Safety in Queries 91
General Form
SELECT <attribute(s)>
FROM <relation(s)>
WHERE <condition(s)>
GROUP BY <attribute(s)>
HAVING <grouping condition(s)>
Order of Execution
FROM
WHERE
GROUP BY
HAVING
SELECT
Views
Example:
SELECT *
FROM GoodStudents
WHERE name=’Mark’;
SELECT R.A
FROM R,S,T
WHERE R.A = S.A or R.A = T.A
Confusion Reigns!
CS 5614: Misc. SQL Stuff, Safety in Queries 95
Safety in Queries
Answer: Yes!
Golden Rule
Any variable that appears anywhere must also
appear in a non-negated body part
In this case, id causes the query to be unsafe
Example of a Safe Query
More Dangers
Find all those numbers that are greater than the age of some student
Answer(x) <- Student(id,age), x>age.
Given
a relation Composite(x)
which lists all the composite numbers
Write a query to find
the prime numbers
Wrong Way
Prime(x) <- NOT Composite(x).
Right Way
Prime(x) <- Number(x), NOT Composite(x).
Safety in Other Notations
Relational Algebra: via the subtraction operator
SQL: via the EXCEPT construct
Notice how SQL and Relational Algebra do not allow unsafe queries
because there is no way to write such queries with the given constructs
how clever, eh? :-)
It is always amazing how “languages” force you to think in a certain manner
a problem long studied by philosophers
CS 5614: Misc. SQL Stuff, Safety in Queries 99
Recursion in Queries
Example
Given only the following relation
Person(name,parent)
Solution in Datalog
why?
CS 5614: Misc. SQL Stuff, Safety in Queries 101
Recursion in SQL3
Example
(SELECT *
FROM Person)
UNION
(SELECT Person.name,Ancestor.ans
FROM Person, Ancestor
WHERE Person.parent=Ancestor.name)
Use with caution: Some kinds of recursive queries will not be allowed!
example: the following Datalog query might not be allowed in SQL3
Ancestor(x,y) <- Ancestor(x,z), Ancestor(z,y).
Final Example
Illegal in SQL3
not because of mutual recursion
but due to the fact that there is no “unique interpretation” to the query
Eg: 6 could be either in Odd or in Even; both are acceptable!
Example Systems
CORAL (Univ. Wisc.)
LDL++ (MCC)
XSB Systems (SUNY, Stony Brook)
Can be viewed as
extending PROLOG-type systems with secondary storage
extending RDBMSs with deductive functionality
Mappings: Commonalities between PROLOG and DBMSs
Predicate: Relation
Argument: Attribute
Ground Fact: Tuple
Extensional Definition: Table (defined by data)
Intensional Definition: Table (defined by a view)
Characteristics of PROLOG
Tuple-at-a-time
Backward Chaining
Top-Down
Goal-Oriented
Fixed-Evaluation Strategy (Depth-First)
Characteristics of RDBMSs
Set-at-a-time (recall relational algebra)
Forward Chaining
Bottom-Up
Query Optimizer figures a good evaluation strategy
Example
ancestor(X,X). parent(amy,bob).
ancestor(X,Y) <- parent(X,Z), ancestor(Z,Y).
Query
Find the ancestors of bob: ancestor(X,bob)?
CS 5614: Misc. SQL Stuff, Safety in Queries 105
PROLOG Pitfalls
Previous Example
Linear Recursion
Tail Recursion
What if we reverse the order of clauses in
ancestor(X,Y) <- parent(X,Z), ancestor(Z,Y).
PROLOG goes into an infinite loop (why?)
What if we make it
ancestor(X,Y) <- ancestor(X,Z), ancestor(Z,Y).
“Not Linear” Recursion
Inference = Resolution + Unification
Entailment in First Order Logic is Semi-decidable
Why?
There are some things we cannot do with SQL alone
e.g. preserving complex states, looping, branching etc.
Typically embed SQL in a host-language interface
Solution
easy when SELECT returns only one row
Vendor-Specific Implementations
ORACLE: PL/SQL (procedural extensions to SQL)
Tradeoffs
ODBC
originated by Microsoft in 1991
adds one more abstraction layer
not as fast as a native API (does not exploit “special features”)
least-common denominator approach
constantly evolving
PL/SQL etc.
“tailored” to the details of the underlying DBMS
might not extend to heterogeneous domains
modeled after a specific programming language (e.g. Ada for Pl/SQL)
SELECT name
FROM Students, Classroll
WHERE Students.name = Classroll.studentname
AND Students.gpa = 4.0
AND Classroll.coursename = ‘CS5614’
Two Strategies
Do join and then filter out the ones with gpa <> 4.0 and course <> CS5614
Filter first the ones with gpa <> 4.0 and course <> CS5614 and then Join
Which is Better?
Always good to “push selections” as far down into the query parse tree
Three Requirements
A Search Space of “Plans”
A Cost Model (for Plan evaluation)
An Enumeration Algorithm
Ideally
Search Space: contains both good and efficient plans
Cost Models: cheap to compute and accurate
Enumeration Algorithm: efficient (not a monkey-typewriter algorithm)
Example of a Search Space
See Previous Slide
Examples of Cost Models
#(tuples) evaluation
#(main memory locations) etc.
Example of an enumeration algorithm
Sequential enumeration of a lattice of plans
Dynamic Programming vs. Greedy Approaches
CS 5614: Misc. SQL Stuff, Safety in Queries 113
#(Tuples) in a query
Range of Values
Minimum: 0
In-between: #(R) (if Y is a foreign key for R and a key for S)
Maximum: #(R)#(S) (if Y’s in R and S are all the same)
Assumptions for Join Size Estimation
Containment of Value Sets
Preservation of Value Sets
Containment of Value Sets
If V(R,Y) <= V(S,Y) then the Y’s in R are a subset of the Y’s in S
Satisfied when Y is a foreign key in R and a key in S
Preservation of Value Sets
#(R Join S,X) = #(R,X)
#(R Join S,Z) = #(S,Z)
why is this reasonable?
CS 5614: Misc. SQL Stuff, Safety in Queries 115
SELECT movietitle
FROM Actors,ActedIn
WHERE Actors.name = ActedIn.actorname
AND Actors.age = 23
What is T(n)?
Sample Values
1: 1
2: 1
3: 2
4: 5
5: 14
A formula
T(1) = 1 (Basis)
T(n) = T(1)T(n-1) + T(2)T(n-2) + ..... + T(n-1)T(1)
Classifications
Left-Deep Trees: All right children are leaves
Right-Deep Trees: All left children are leaves
Bushy Trees: Neither Left-Deep nor Right-Deep
Choosing a Join Order: Restricted to Left-Deep Trees
By Dynamic Programming: O(n!)
Greedy Approach: Make local selections
Example
Consider
R(a,b): #(R) = 1000, V(R,a) = 100, V(R,b) = 200
S(b,c): #(S) = 1000, V(S,b) = 100, V(S,c) = 500
T(c,d): #(T) = 1000, V(T,c) = 20, V(T,d) = 50
Possible Join Orders
(R Join S) Join T
(S Join R) Join T (same as above; why?)
(R Join T) Join S
(T Join R) Join S (same as above)
(S Join T) Join R
(T Join S) Join R (same as above)
Cost Estimation = Sizes of Intermediate Relations
(R Join S) Join T: 5000
(R Join T) Join S: 1000000
(S Join T) Join R: 2000
Best Plan = (S Join T) Join R
CS 5614: Misc. SQL Stuff, Safety in Queries 119
To normalize or not to
Sacrificing Redundancy Elimination
Sacrificing Dependency Elimination
Several Choices of Normalized Schemas
Vertical Partitioning Applications
Recomputing Indices
Histograms etc. might be outdated
Restricting Uses of Subqueries
Unnesting query blocks by Joins
Declining the Use of Indices
Table Scans for Small Tables
Rule-based optimization: Rewrite A=6 as “A+0=6”
Provide Redundant Tables
Decision-Support/ Data Mining Queries