SQL Lecture Notes
SQL Lecture Notes
Lecture 3
A rela on has a:
Structural defini on
Rela on name
A set of a ribute names and their domains
Data Part
Each row represents a data item
Primary Key set – would include data that is unique in that table, eg id number, employee id.
It also cannot be null or else it will give you an error.
A rela onship is named associa on between a number of en es that is governed by certain
rules and some mes qualified with its own a ributes
Rela ng 2 tables together that rela onship can have its’ own par cular a ributes.
2 Important proper es of a rela onship design are:
Cardinality
Par cipa on
For a binary rela onship, the number of these cardinality possibili es is four namely:
1. One to one eg. Person to Passport (1 – 1)
2. One to many eg. Class to Student (1 – N)
3. Many to one (N – 1)
4. Many to many eg. Employee to Project (M – N)
The op ons are total, all instances must par cipate in at least one rela onship, par al does
not have to have a rela onship
Total Par cipa on – student MUST be enrolled to a course
Par al Par cipa on – Course CAN have one or more students or none
Foreign Keys are used to join tables or navigate between tables together. Specifically, foreign
keys build rela onships.
The a ributes in FK have the same domain(s) as the primary key a ributes PK
Value of FK in a table t1 of the current state r1(R1) either occurs as a value of PK for some tuple
t2 in the current state r2(R2) or is NULL
If the rela onship is total, then NULL values in the foreign key are prohibited. Therefore the
null constraint must be resent to implement a total rela onship
Each a ribute is associated with domain of values – datatypes in a Rela onal DBMS
Each datatype take space on physical storage
Eg. SELECT 1+2 AS;
SELECT abs(-2)AS;
We also need datatype conversion func ons for example from a number to string and vice
versa
SELECT cast(1+1 AS varchar);
SELECT cast(‘1’ AS integer) + cast(‘1’ AS integer);
Whenever a number is enclosed ‘’ it means that it’s actually a string type not integer
From date to an integer:
SELECT CURRENT_DATE ”Today is”;
SELECT cast(to_char(CURRENT_DATE,”J”)AS integer) ”ThatJulianDate”;
Some latent problems exists when comparing or conver ng datatypes:
Comparing with == and <> on FLOATs
Trunca on (i.e rounding dot zero)
Generic Types
Numeric: INTEGER, DECIMAL, REAL, SERIAL
Money: MONEY
Character: VARCHAR(n), TEXT, CHAR(n)
Date Time: TIMESTAMP, TIME DATE, INTERVAL
Booleans: BOOLEAN
We can also create our datatypes by crea ng new domains.
For example, the following domain describes our grade table:
CREATE DOMAIN uni_grade
CHAR(1) NOT NULL DEFAULT ’I’
CHECK (VALUE(‘A’,’B’,’C’,’D’,’F’,’I’));
Constraints so far:
NOT NULL – specifies that we cannot input a record and leave that a par cular a ribute
empty
UNIQUE – cannot have 2 records with the same value
CHECK - we define a par cular set of values and that field has to abide with that par cular
condi on
Referen al Constraints – introduce a foreign key between tables student and faculty
ALTER TABLE student
ADD CONSTRAINT stud_faculty_
FOREIGN KEY (sfaculty)
REFERENCES faculty(fid);
Lecture 4
Code:
Lecture 5
SELECT*FROM university.student
Lecture 6
Rela onal Joins
Are you used to join tables together when we’re selec ng our data
CJ Date database is well known with simple structure and easy to recall its data content that is it’s easy
to verify yourself that all is well with your query a empt (most likely schema for exam)
Eg. Give work schedule details with product’s colour and weight for RED coloured parts. Note wrk.p is a
FK in table spj and prd.p is a PK in table p
SELECT wrk.s, wrk.j, prd.p, prd.colour, prd.weight (you need to state exactly the table of each field)
FROM date.spj wrk, date.p prd (you can give it a variable name)
OR
Comparing Foreign Key to Primary Key to retrieve data when crea ng the join
FROM date.spj wrk INNER JOIN Joining the spj and product table
eg. Give work schedule details with product’s colour and weight for non RED coloured parts, and
supplier’s city.
In the first join we have wrk.p is a FK in table spj and prd.p is a PK in table p, and in the second join
spls.s is a PK in table s and wrk.s is a FK in table spj
prd.weight, spl.city
VALUES
(1,2,97,'A'),(1,3,85,'A'),
(1,4,70,'B'),(1,5, 62,'C'),
(2,1, 75,'B'),(2,2,73,'B'),
(2,3,65,'C'),(2,4,61,'C'),
(2,6, 45,'D'),(3,2,88,'A'),(3,3,76,'A'),
(3,4,70,'B'),(3,6, 61,'C'),(4,2,88,'A'),(4,3,76,'A'),
(6,2, 61,'C');
SELECT *
FROM university.grade
FROM university.grade g
FROM university.grade g
Eg. Give details of work schedule for RED coloured parts and where jobs and parts are collocated. In
the first join we have wrk.p is a FK in table spj and prd.p is a PK in table p, in the second join spl.s is a
PK in table s and wrk.s is a FK int able spj and in the third join condi on we require coloca on – have
the same city value- between project and supplier
Outer Joins
What if we want to see all co-located parts and jobs and ensure that all the job ci es are men oned;
even if not co-located with any part
ORDER BY job.city;
RIGHT OUTER JOIN means keep all of the RIGHT table’s – i.e job tuples – a ribute values
Note: the ‘null’ values for columns that come from the non right table(s) where no match is sa sfied
IF you do not want to generate any nulls in our output THEN use the COALESCE() func on
job.j, job.city
ORDER BY job.city;
SELECT prd.p, job.j, prd.city
ORDER BY prd.city;
All matching records together with the le record, vice versa for the Right join and for the full
join is the matching records and everything else
prd.city AS “PartCity”,
job.city AS “JobCity”
ORDER BY prd.city;
Self Join
When we have a table and we are crea ng two instances of the same table
Self joins are self joins characterised by using a table more than once in the from list of tables list an
example will be pairs of projects that are co-located
First A empt
SELECT j1.j,j2.j,j1.city
The join comparison expression between a ributes uses a non equality operator; for example >.
Consider the query to name pairs of parts with one part ‘ having more weight’ than the second
SELECT ‘Part’,
p1.p
p2.p
‘by’,
p1.weight – p2.weight
How can one build all possible pairs? This is an example of Cross Product
date.p prd
Nested Queries
)]
)]
(The one with 3 nested queries is not going to be for the exam)
Views are ideal for retrieving data from reports, forms, genera ng structure and content of datasets.
AS query