Download presentation
Presentation is loading. Please wait.
Published byKevin Blair Modified over 7 years ago
1
Part2 The Relational Database Chapter 03- Structured Query Language (SQL)
Database Systems Lu Wei College of Software and Microelectronics Northwestern Polytechnical University
2
Outline Introduction Basic SQL Setting Up and Using PostgreSQL
Advanced SQL Embeded SQL Lu Wei
3
Outline Introduction Basic SQL Setting Up and Using PostgreSQL
Advanced SQL Embeded SQL Lu Wei
4
Introduction What is SQL Objectives of SQL
SQL is abbreviation of Structured Query Language. It is the way we access the database. Objectives of SQL Allow a user to Create the database and relation structure. Perform basic data management tasks. (Insertion, modification, and deletion of data from relation) Perform both simple and complex queries Perform these tasks with minimal user effort Lu Wei
5
Introduction History of SQL
E.F.Codd – ‘A relational model of data for large shared data banks’ (1970) 1974, D.Chamberlin defined the Structured English Query Language (SEQUEL) 1976, a revised version SEQUEL/2 – SQL IBM, System R based on SEQUEL/2 Lu Wei
6
Introduction Late 1970s, the first commercial implementation of relational DBMS based on SQL – ORACLE IBM, 1982, SQL/DS; 1983, DB2 1982, the American National Standards Institute began work on a Relational Database Language (RDL) based on a concept paper from IBM. SQL-86, SQL-89, SQL-92(SQL2), SQL-99(SQL3) Lu Wei
7
Introduction Features of SQL
Non-procedual - based on relational algebra and relational calculus Easy to learn Lu Wei
8
Introduction Importance of SQL
SQL is the first and, so far, only standard database language to gain wide acceptance. Lu Wei
9
Introduction SQL can be used in two ways
Use SQL interactively by entering the statements at a terminal Embed SQL statements in a procedural language (programmatic SQL) Lu Wei
10
Outline Introduction Basic SQL Setting Up and Using PostgreSQL
Advanced SQL Embeded SQL Lu Wei
11
Basic SQL Writing SQL Commands Data Definition Language (DDL)
Data Manipulation Language (DML) Lu Wei
12
Basic SQL Writing SQL Commands Data Definition Language (DDL)
Data Manipulation Language (DML) Lu Wei
13
Writing SQL Commands An SQL statement consists of reserved words and user-defined words. Most components of an SQL statement are case insensitive. Usually a statement terminator (;) is used to end each SQL statement. (Although the standard does not require it) Lu Wei
14
Writing SQL Commands Although SQL is free-format, an SQL statement or set of statements is more readable if indentation and lineation are used. Each clause in a statement should begain on a new line; The beginning of each clause should line up with the beginning of other clause; If a clause has several parts, they should each appear on a separate line and be indented. … Lu Wei
15
Writing SQL Commands We use the extended form of the Backus Naur Form (BNF) notation to define SQL statement. Uper-case letters represent reserved words; Lower-case letters represent user-defined words; A vertical bar(|) indicates a choice among alternatives; Curly braces({}) indicate a required element; Square brackets([]) indicate an optional element; An ellipsis(…) indicate optional repetition of an item. Lu Wei
16
Basic SQL Writing SQL Commands Data Definition Language (DDL)
Data Manipulation Language (DML) Lu Wei
17
Data Definition Language (DDL)
The ISO SQL Data Types Integrity Enhancement Feature (IEF) Data Definition Lu Wei
18
Data Definition Language (DDL)
The ISO SQL Data Types Integrity Enhancement Feature (IEF) Data Definition Lu Wei
19
The ISO SQL Data Types SQL Identifiers
Used to identify objects in the database, such as table names, view names, and columns. Character set A…Z, a…z 0…9 Underscore(_) Restrictions An identifier can be no longer than 128 characters An identifier must start with a letter An identifier cannot contain spaces Lu Wei
20
The ISO SQL Data Types SQL Scalar Data Types Lu Wei
21
The ISO SQL Data Types Examples branchNo CHAR(4) address VARCHAR(30)
rooms SMALLINT salary DECIMAL(7,2) viewDate DATE Lu Wei
22
The ISO SQL Data Types Scalar operators +,-,*,/
LOWER,UPPER,TRIM,SUBSTRING CURRENT_USER, SESSION_USER … Lu Wei
23
Data Definition Language (DDL)
The ISO SQL Data Types Integrity Enhancement Feature (IEF) Data Definition Lu Wei
24
Integrity Enhancement Feature (IEF)
NOT NULL Constraints position VARCHAR(10) NOT NULL Lu Wei
25
Integrity Enhancement Feature (IEF)
Domain Constraints sex CHAR NOT NULL CHECK (sex IN(‘M’,’F’)) CREATE DOMAIN SexType AS CHAR DEFAULT ‘M’ CHECK(VALUE IN(‘M’,’F’)); sex SexType NOT NULL Lu Wei
26
CREATE DOMAIN DomainName [AS] dataType [DEFAULT defaultOption]
Domain definition CREATE DOMAIN DomainName [AS] dataType [DEFAULT defaultOption] [CHECK(searchCondition)] DROP DOMAIN DomainName [RESTRICT|CASCADE] CREATE DOMAIN BranchNumber AS CHAR(4) CHECK(VALUE IN(SELECT branchNo FROM Branch)); Lu Wei
27
Integrity Enhancement Feature (IEF)
Entity Integrity The primary key of a table must contain a unique, non-null value for each row. The PRIMARY KEY clause can be specified only once per table. PRIMARY KEY (columnName[,columnName]) PRIMARY KEY (propertyNo) PRIMARY KEY (sNo) PRIMARY KEY (clientNo,propertyNo) PRIMARY KEY (sNo,cNo) Lu Wei
28
Integrity Enhancement Feature (IEF)
Alternate keys can be ensured uniqueness using the keyword UNIQUE. Every column that appears in a UNIQUE clause must be declared as NOT NULL. UNIQUE (columnName[,columnName]) UNIQUE (clientNo,propertyNo) Lu Wei
29
Integrity Enhancement Feature (IEF)
Referential Integrity Referential integrity is implemented through FOREIGN KEY. A value in the foregin key must refer to an existing valid row in the parent table or be null. Define the foreign key FOREIGN KEY (columnName[,columnName]) REFERENCES TableName[(columnName[,columnName])] [ON DELETE|UPDATE CASCADE|SET NULL|SET DEFAULT|NO ACTION] Lu Wei
30
Integrity Enhancement Feature (IEF)
Exmples FOREIGN KEY stuffNo REFERENCES Staff ON DELETE SET NULL Lu Wei
31
Integrity Enhancement Feature (IEF)
Enterprise Constraints The CREATE ASSERTION statement is an integrity constaint that is not directly linked with a table definition. CREATE ASSERTION AssertionName CHECK (searchCondition) CREATE ASSERTION StaffNotHandlingTooMuch CHECK (NOT EXISTS (SELECT staffNo FROM PropertyForRent GROUP BY staffNo HAVING COUNT(*)>100)) Lu Wei
32
Data Definition Language (DDL)
The ISO SQL Data Types Integrity Enhancement Feature (IEF) Data Definition Lu Wei
33
Data Definition Creating a Database
The ISO standard does not specify how database are created, and each dialect generally has a different approach. Lu Wei
34
Data Definition Creating a table (CREATE TABLE) CREATE TABLE TableName
{(columnName dataType [NOT NULL][UNIQUE] [DEFAULT defaultOption][CHECK(searchCondition)][,…]} [PRIMARY KEY (listOfColumns),] {[UNIQUE (listOfColumns),][,…]} {[FOREIGN KEY (listOfForeignKeyColumns) REFERENCES ParentTableName[(listOfCandidateKeyColumns)], [MATCH {PARTIAL|FULL} [ON UPDATE referentialAction] [ON DELETE referentialAction]][,…]} {[CHECK(searchCondition)][,…]}) Lu Wei
35
Data Definition Student (sNo, sName, sSex, sAge, sDept)
Course (cNo, cName, cPNo, cCredit) SC (sNo, cNo, score) example1table.sql Branch (branchNo, street, city, postcode) Staff (staffNo, fName, lName, position, sex, DOB, salary, branchNo) PropertyForRent (propertyNo, street, city, postcode, type, rooms, rent, ownerNo, staffNo, branchNo) Client (clientNo, fName, lName, telNo, prefType, maxRent) PrivateOwner (ownerNo, fName, lName, address, telNo) Viewing (clientNo, propertyNo, viewDate, comment) Registration (clientNo, branchNo, staffNo, dateJoined) example2table.sql Lu Wei
36
Data Definition Changing a Table Definition (ALTER TABLE)
ALTER TABLE TableName [ADD [COLUMN] columnName dataType [NOT NULL][UNIQUE] [DEFAULT defaultOption][CHECK(searchCondition)]] [DROP [COLUMN] columnName [RESTRICT|CASCADE]] [ADD [CONSTRAINT [constraintName]] tableConstraintDefinition] [DROP CONSTRAINT constraintName [RESTRICT|CASCADE]] [ALTER [COLUMN] SET DEFAULT defaultOption] [ALTER [COLUMN] DROP DEFAULT] Lu Wei
37
Data Definition Examples ALTER TABLE Staff
ALTER position DROP DEFAULT; ALTER TABLE Student ALTER sSex SET DEFAULT ‘M’; Lu Wei
38
Data Definition Removing a Table (DROP TABLE)
DROP TABLE TableName [RESTRICT|CASCADE] DROP TABLE Student; DROP TABLE Staff; Lu Wei
39
Basic SQL Writing SQL Commands Data Definition Language (DDL)
Data Manipulation Language (DML) Lu Wei
40
Data Manipulation Language (DML)
Query Data Update Lu Wei
41
Data Manipulation Language (DML)
Query Data Update Lu Wei
42
Query General form The purpose of the SELECT statement is to retrive and display data from one or more database tables. It is capable of performing the equivalent of the relational algebra’s Selection, Projection, and Join operations in a single statement SELECT [DISTINCT|ALL]{*|[columnExpression[AS newName]][,…]} FROM TableName[alias][,…] [WHERE condition] [GROUP BY columnList][HAVING condition] [ORDER BY columnList] Lu Wei
43
Query SELECT A1 , A2 , ..., An FROM R1,R2,…,Rm WHERE F
πA1,A2,...,An(σF(R1× R2×...×Rm)) Lu Wei
44
Query Retrieve all columns, all rows
SELECT staffNo,fName,position,sex,DOB, salary,branchNo FROM Staff; SELECT * FROM Staff; SELECT * FROM Student; Lu Wei
45
Query Retrieve specific columns, all rows
SELECT staffNo,fName,lName,salary FROM Staff; SELECT sNo,sName FROM Student; Lu Wei
46
Query Use DISTINCT eliminate the duplicates
SELECT DISTINCT propertyNo FROM Viewing; SELECT DISTINCT sNo FROM SC; Lu Wei
47
Query Calculated fields SELECT staffNo,fName,lName,salary/12
FROM Staff; SELECT sName, 2008-sAge FROM Student; SELECT staffNo,fName,lName, salary/12 AS monthlySalary FROM Staff; Lu Wei
48
Query Row selection (WHERE clause)
Basic search conditions in WHERE clause Condition Predicates(谓词) comparison Comparison operators(=,>,<,<>,<=,>=,!=) range BETWEEN AND, NOT BETWEEN AND set membership IN, NOT IN pattern match LIKE, NOT LIKE null IS NULL, IS NOT NULL logical operators AND, OR,NOT Lu Wei
49
Query (1) comparison SELECT staffNo,fName,lName,positon,salary FROM Staff WHERE salary > 10000; SELECT sName FROM Student WHERE sDept = 'CS'; Lu Wei
50
Query (2)range SELECT staffNo,fName,lName,positon,salary FROM Staff WHERE salary BETWEEN AND 30000; SELECT staffNo,fName,lName,positon,salary FROM Staff WHERE salary >= AND salary <= 30000; SELECT sName, sDept, sAge FROM Student WHERE sAge NOT BETWEEN 20 AND 23; Lu Wei
51
Query (3)set membership
SELECT staffNo,fName,lName, FROM Staff WHERE position IN (‘Manager',‘Supervisor'); SELECT staffNo,fName,lName, FROM Staff WHERE position = ‘Manager’ OR position = ‘Supervisor'; SELECT sName, sSex FROM Student WHERE sDept NOT IN ('IS', 'MA', 'CS'); Lu Wei
52
Query (4)pattern match %--represents any sequence of zero or more characters (wildcard) _--represents any single character Escape character--\,# Lu Wei
53
Query SELECT clientNo,fName,lName,address,telNo
FROM PrivateOwner WHERE address LIKE ‘%Glasgow%’; SELECT sName, sNo, sSex FROM Student WHERE sName LIKE ‘刘%’; 查询以”DB_”开头,且倒数第三个字符为i的课程的详细情况 SELECT * FROM Course WHERE cName LIKE ’DB\_%i__’ ESCAPE ’\’; Lu Wei
54
Query (5)null List the details of all viewings on property PG4 where a comment has not been supplied SELECT clientNo,viewDate FROM Viewing WHERE propertyNo = ‘PG4’ AND comment = ‘’; SELECT clientNo,viewDate FROM Viewing WHERE propertyNo = ‘PG4’ AND comment IS NULL; Lu Wei
55
Query (6)logical operators
SELECT sName FROM Student WHERE sDept='CS' AND Sage<20; SELECT * FROM Branch WHERE city=‘London' OR city=‘Glasgow’; Lu Wei
56
Query Sorting Results (ORDER BY clause)
In general, the rows of an SQL query result table are not arranged in any particular order. We can user ORDER BY clause in the SELECT statement to sort the results. The ORDER BY clause must always be the last clause of the SELECT statement. ASC—ascending order, default order DESC—descending order Lu Wei
57
Query Examples SELECT staffNo,fName,lName,salary FROM Staff
ORDER BY salary DESC; ORDER BY 4 DESC SELECT sNo, score FROM SC WHERE cNo=‘001' ORDER BY score DESC; Lu Wei
58
Query SELECT propertyNo,type,rooms,rent FROM PropertyForRent ORDER BY type,rent DESC; SELECT * FROM Student ORDER BY sDept, sAge DESC; Which is the place for null? Lu Wei
59
Query Using the SQL Aggregate Functions
The ISO standard defines five aggregate functions COUNT([DISTINCT|ALL] *) COUNT([DISTINCT|ALL] <columnName>) SUM([DISTINCT|ALL] <columnName>) AVG([DISTINCT|ALL] < columnName >) MAX([DISTINCT|ALL] < columnName >) MIN([DISTINCT|ALL] < columnName >) Lu Wei
60
Query COUNT, MIN, and MAX apply to both numeric and non-numeric fields, but SUM and AVG may be used on numeric field only. Apart from COUNT(*), each function eliminates nulls first and operates only on the remaining non-null values. Aggregate functions can be used only in the SELECT list and in the HAVING clause. Lu Wei
61
Query SELECT COUNT(*) FROM Student;
SELECT COUNT(*) AS my_count FROM PropertyForRent WHERE rent > 350; Lu Wei
62
Query SELECT COUNT(DISTINCT propertyNo) AS mycount FROM Viewing
WHERE viewDate BETWEEN ’01-May-08’ AND ‘31-May-08’; SELECT COUNT(DISTINCT sNo) FROM SC; Lu Wei
63
Query Find the total number of Managers and the sum of their salaries
SELECT COUNT(staffNo) AS my_count, SUM(salary) AS my_sum FROM Staff WHERE position = ‘Manager’; Lu Wei
64
Query SELECT AVG(score) FROM SC WHERE Cno='1';
SELECT MAX(score) FROM SC WHERE cNo='1'; SELECT MIN(salary),MAX(salary), AVG(salary) FROM Staff; Lu Wei
65
Query Grouping Results (GROUP BY clause)
All column names in the SELECT list must appear in the GROUP BY clause unless the name is used only in an aggregate function. When the WHERE clause is used with GROUP BY, the WHERE clause is applied first. The ISO standard considers two nulls to be equal for purposes of the GROUP BY clause. Lu Wei
66
Query Find the number of staff working in each branch and the sum of their salaries. SELECT branchNo,COUNT(staffNo),SUM(salary) FROM Staff GROUP BY branchNo ORDER BY branchNo; Lu Wei
67
Query SELECT branchNo,(SELECT COUNT(staffNo) FROM Staff s
WHERE s.branchNo=b.branchNo), (SELECT SUM(salary) WHERE s.branchNo=b.branchNo) FROM Branch b ORDER BY branchNo; Lu Wei
68
Query Restricting groupings (HAVING clause)
HAVING clause is designed for use with the GROUP BY clause to restrict the groups that appear in the final result table. Similar in syntax, HAVING and WHERE serve different purposes. The ISO standard requires that column names used in the HAVING clause must also appear in the GROUP BY list or be contained within an aggregate function. The HAVING clause is not a necessary part of SQL. Lu Wei
69
Query SELECT branchNo,COUNT(staffNo),SUM(salary) FROM Staff
GROUP BY branchNo HAVING COUNT(staffNo)> 1 ORDER BY branchNo; SELECT sNo FROM SC WHERE score>60 GROUP BY sNo HAVING COUNT(*)>3; Lu Wei
70
Query Subqueries In SQL statement, a SELECT-FROM-WHERE statement is called a query block. A query block embedded within WHERE or HAVING clause of another query block is called a subquery or nested query. Subqueries may also appear in INSERT, UPDATE, and DELETE statements. Lu Wei
71
Query There three types of subquery
A scalar subquery returns a single column and single row. A row subquery returns multiple columns, but again only a single row. A table subquery returns one or more columns and multiple rows. Lu Wei
72
Query (1) use of IN predicate
List the students who study in the same department as ‘刘晨’ SELECT sDept FROM Student WHERE sName=‘刘晨’; Suppose the result is ‘IS’ SELECT sNo, sName, sDept FROM Student WHERE sDept='IS'; Lu Wei
73
Query SELECT sNo, sName, sDept FROM Student WHERE sDept IN (SELECT sDept FROM Student WHERE sName=‘刘晨’); SELECT sNo, sName, sDept FROM Student S1, Student S2 WHERE S1.sDept = S2.sDept AND S2.sName =‘刘晨‘; Lu Wei
74
Query List the students who elect the course ‘IS’
SELECT sNo, sName FROM Student WHERE sNo IN SELECT sNo FROM SC WHERE cNo IN (SELECT cNo FROM Course WHERE cName=‘IS’); Lu Wei
75
Query SELECT sNo, sName FROM Student, SC, Course WHERE Student.sNo=SC.sNo AND SC.cNo=Course.cNo AND Course.cName=‘IS’; Lu Wei
76
Query List the properties that are handled by staff who work in the branch at ‘163 Main St’ SELECT propertyNo,street,city,type,rooms FROM PropertyForRent WHERE staffNo IN (SELECT staffNo FROM Staff WHERE branchNo IN (SELECT branchNo FROM Branch WHERE street=‘163 Main St’)); Lu Wei
77
Query For all the subqueries we discuss above, each subquery executes only once and the result of the subquery is used by supquery. The condition of subquery is not dependent on the condition of supquery. We call this type of query independent query. Lu Wei
78
Query (2) use of comparison operators in subquery
The subquery must place after the comparison operator. The subquery SELECT list must consist of a single column name or expression, except for subqueries that use the keyword EXISTS. The ORDERBYclause may not be used in a subquery. Lu Wei
79
Query List the students who study in the same department as ‘刘晨’. We can rewrite the query as follow: SELECT sNo, sName, sDept FROM Student WHERE sDept = (SELECT sDept FROM Student WHERE sName=‘刘晨’); Lu Wei
80
Query SELECT sNo, sName, sDept FROM Student WHERE (SELECT sDept FROM Student WHERE sName='刘晨') = sDept; Lu Wei
81
Query List the students who elect the course ‘IS’. Can we rewrite the query as folow? SELECT sNo, sName FROM Student WHERE sNo SELECT sNo FROM SC WHERE cNo SELECT cNo FROM Course WHERE cName=‘IS’ ; IN = IN = Lu Wei
82
Query Can we use the ‘=’ replace the predicate ‘IN’ in the follow example we discuss above? SELECT propertyNo,street,city,type,rooms FROM PropertyForRent WHERE staffNo IN (SELECT staffNo FROM Staff WHERE branchNo IN (SELECT branchNo FROM Branch WHERE street=‘163 Main St’)); Lu Wei
83
Query (3) use aggregate function in subquery
List all staff whose salary is greater than the average salary, and show by how much their salary is greater than the average. SELECT staffNo,fName,lName, salary-(SELECT AVG(salary) FROM Staff) AS salDiff FROM Staff WHERE salary > (SELECT AVG(salary) FROM Staff); Lu Wei
84
Query (4)use ANY/ SOME and ALL in subquery
>ANY, <ANY, >=ANY, <=ANY, =ANY, <>ANY/!=ANY >ALL, <ALL, >=ALL, <=ALL, =ALL(no meaning), <>ALL/!=ALL Lu Wei
85
Query List the student who is not in department ‘IS’ and their age less then any student in department ‘IS’. Sort the result according to age in descending order. SELECT sName, sAge FROM Student WHERE sAge < ANY (SELECT sAge FROM Student WHERE sDept=‘IS’ ) AND sDept <> 'IS' ORDER BY sAge DESC; Lu Wei
86
Query SELECT sName, sAge FROM Student WHERE sAge < (SELECT MAX(sAge) FROM Student WHERE sDept='IS') AND sDept <> 'IS' ORDER BY sAge DESC; when using aggregate function to implement the query, usually the efficience is higher than using ANY or ALL Lu Wei
87
Query List the student who is not in department ‘IS’ and their age less then all student in department ‘IS’. Sort the result according to age in descending order. SELECT sName, sAge FROM Student WHERE sAge<ALL (SELECT sAge FROM Student WHERE sDept=‘IS’ ) AND sDept <> 'IS' ORDER BY sAge DESC; Lu Wei
88
Query SELECT sName, sAge FROM Student WHERE sAge < (SELECT MIN(sAge) FROM Student WHERE sDept='IS') AND sDept <> 'IS' ORDER BY sAge DESC; Lu Wei
89
Query Find all staff whose salary is largeer than the salary of at least one member of staff at branch ‘B003’ SELECT staffNo,fName,lName,position,salary FROM Staff WHERE salary > SOME(SELECT salary FROM Staff WHERE branchNo=‘B003’); Lu Wei
90
Query Find all staff whose salary is largeer than the salary of every member of staff at branch ‘B003’ SELECT staffNo,fName,lName,position,salary FROM Staff WHERE salary > ALL(SELECT salary FROM Staff WHERE branchNo=‘B003’); Lu Wei
91
Query Lu Wei
92
Query Muti-Table Queries
To combine columns from several tables into a result table we need to use a join operation. To obtain information from more than one table, the choice is between using a subquery and using a join. If the final result table is to contain columns from different tables, then we must use a join. Lu Wei
93
Query (1) equijoin and non-equijoin
List all students and the courses they elect. SELECT Student.*, SC.* FROM Student, SC WHERE Student.sNo=SC.sNo; SELECT Student.sNo, sName, sSex, sAge, sDept, cNo, score FROM Student, SC WHERE Student.sNo=SC.sNo; Lu Wei
94
Query List the names of all clients who have viewed a property along with any comment supplied. SELECT c.clientNo,fName,lName, propertyNo,comment FROM Client c,Viewing v WHERE c.clientNo = v.clientNo; Note: When Cartesian product appear? Lu Wei
95
Query (2) self-join List the interval prerequest courses of all courses. 查询每门课的间接选修课(即先修课的先修课) SELECT FIRST.cNo, SECOND.cPNo FROM Course FIRST, Course SECOND WHERE FIRST.cPNo=SECOND.cNo; Lu Wei
96
Query (3) outer join sNo sName sAge s1 … s2 s3 sNo cNo score s1 c1 …
List all students along with their elective courses even the student have not elect any course. Lu Wei
97
Query branchNo bCity B003 Glasgow B004 Bristol B002 London propertyNo
PropertyForRent1 branchNo bCity B003 Glasgow B004 Bristol B002 London propertyNo pCity PA14 Aberdeen PL94 London PG4 Glasgow List the branch offices and properties that are in the same city along with any unmatched branches. Lu Wei
98
Query SELECT s.*, sc.* FROM Student s, SC sc WHERE s.sNo = sc.sNo;
SELECT b.*, p.* FROM Branch1 b, PropertyForRent1 p WHERE b.bCity = p.pCity; Lu Wei
99
Query There three types of Outer join: Left outer join
Right outer join Full outer join Lu Wei
100
Query List all students along with their elective courses even the student have not elect any course. SELECT s.*, sc.* FROM Student s LEFT JOIN SC sc ON s.sNo = sc.sNo; SELECT s.*, sc.* FROM Student s, SC sc WHERE s.sNo = sc.sNo(*); Lu Wei
101
Query List the branch offices and properties that are in the same city along with any unmatched branches. SELECT b.*,p.* FROM Branch1 b LEFT JOIN PropertyForRent1 p ON b.bCity = p.pCity; SELECT b.*,p.* FROM Branch1 b,PropertyForRent1 p WHERE b.bCity = p.pCity(*); Lu Wei
102
Query SELECT s.*, sc.* FROM Student s RIGHT JOIN SC sc ON s.sNo = sc.sNo; SELECT b.*,p.* FROM Branch1 b RIGHT JOIN PropertyForRent1 p ON b.bCity = p.pCity; Lu Wei
103
Query SELECT s.*, sc.* FROM Student s FULL JOIN SC sc ON s.sNo = sc.sNo; SELECT b.*,p.* FROM Branch1 b FULL JOIN PropertyForRent1 p ON b.bCity = p.pCity; Lu Wei
104
Query Muti-table join SELECT b.branchNo,b.city,s.staffNo,fName,
lName,propertyNo FROM Branch b,Staff s,PropertyForRent p WHERE b.branchNo = s.branchNo AND s.staffNo = p.staffNo ORDER BY b.branchNo,s.staffNo,propertyNo; FROM (Branch b JOIN Staff s USING branchNo) AS bs JOIN PropertyForRent p USING staffNo; Lu Wei
105
Query ISO SQL syntax SELECT table1.column,tabel2.column FROM talbe1
[CROSS JOIN table2] | [NATURAL JOIN table2] | [JOIN table2 USING(column_name)] | [JOIN table2 ON(table1.column_name=table2.column_name)] | [LEFT|RIGHT|FULL OUTER JOIN table2 ON(table1.column_name=table2.column_name)]; Lu Wei
106
Query EXISTS and NOT EXISTS
EXISTS and NOT EXISTS is existential quantifiers. They produce a simple true/false result. Since EXISTS and NOT EXISTS check only for the existence or non-existence of rows in the subquery result table, the subquery can contain any number of columns. Usually we write the subquery as: (SELECT * FROM…) Lu Wei
107
Query Examples List the students who have not elected course ‘001’
SELECT sName FROM Student WHERE NOT EXISTS (SELECT * FROM SC WHERE sNo=Student.sNo AND cNo=‘001'); Can we use NOT IN to implement this query? Lu Wei
108
Query Find all staff who work in a London branch office
SELECT staffNo,fName,lName,postion FROM Staff s WHERE EXISTS (SELECT * FROM Branch b WHERE s.branchNo = b.branchNO AND city =‘Lodon'); Lu Wei
109
Query SELECT staffNo,fName,lName,postion FROM Staff s, Branch b WHERE s.branchNo = b.branchNO AND city =‘Lodon'); Lu Wei
110
Query Some subqueries using EXISTS or NOT EXISTS can be replace by subqueries with other form (IN etc.), but some can’t. Examples List the students who study in the same department as ‘刘晨’. (refer to page73) Lu Wei
111
Query SELECT sNo, sName, sDept FROM Student S1 WHERE EXISTS SELECT * FROM Student S2 WHERE S2.sDept=S1.sDept AND S2.sName='刘晨'; Lu Wei
112
Query (x)P ┐(x(┐P))
There is no direct expression for universal quantifier(全称量词) in SQL. We can use predication calculus to transform a predication using universal quantifiers to a predication using existential quantifiers. (x)P ┐(x(┐P)) Lu Wei
113
Query List the students who elect all courses.
SELECT sName FROM Student S WHERE NOT EXISTS (SELECT * FROM Course C WHERE NOT EXISTS (SELECT * FROM SC WHERE sNo=S.Sno AND cNo=C.cNo); Lu Wei
114
Query There is also no direct expression for implication(全称量词) in SQL. We can also tranform it to expression using existential quantifiers. p q ┐p ∨ q (y)pq ┐(y(┐(Pq))) ┐(y(┐(┐P∨q)) ┐y(P∧┐q) Lu Wei
115
Query List the students who elect the courses elected by ‘xxx’at least . SELECT DISTINCT sNo FROM SC SCX WHERE NOT EXISTS (SELECT * FROM SC SCY WHERE SCY.sNo=‘xxx' AND NOT EXISTS (SELECT * FROM SC SCZ WHERE SCZ.sNo=SCX.sNo AND SCZ.cNo=SCY.cNo); Lu Wei
116
Query Combining Result Tables (UNION, INTERSECT, EXCEPT)
In SQL, we can use the normal set operations of Union, Intersection, and Difference to combine the results of two or more queries into a single result table. The three set operators in the ISO standard are called UNION, INTERSECT, and EXCEPT Operator[ALL][CORRESPONDING [BY{column1[,…]}]] Lu Wei
117
Query Examples List the students who have elected course ‘001’ or ‘002’ (SELECT sNo FROM SC WHERE cNo=‘001‘) UNION (SELECT sNo FROM SC WHERE cNo=‘002‘); Lu Wei
118
Query List all cities where there is either a branch office or a property (SELECT city FROM Branch WHERE city IS NOT NULL) UNION (SELECT city FROM PropertyForRent WHERE city IS NOT NULL); Lu Wei
119
Query (SELECT * FROM Branch WHERE city IS NOT NULL) UNION CORRESPONDING BY city (SELECT * FROM PropertyForRent WHERE city IS NOT NULL); Lu Wei
120
Query List the students who have elected course ‘001’ and ‘002’
(SELECT sNo FROM SC WHERE cNo=‘001‘) INTERSECT (SELECT sNo FROM SC WHERE cNo=‘002‘); Lu Wei
121
Query SELECT sNo FROM SC WHERE cNo=‘001' AND sNo IN (SELECT sNo FROM SC WHERE cNo='2'); Lu Wei
122
Query Construct a list of all cities where there is both a branch office and a property (SELECT city FROM Branch) (INTERSECT SELECT city FROM PropertyForRent); (SELECT * FROM Branch) INTERSECT CORRESPONDING BY city (SELECT * FROM PropertyForRent); Lu Wei
123
Query SELECT DISTINCT b.city FROM Branch b,PropertyForRent p
WHERE b.city = p.city; SELECT DISTINCT b.city FROM Branch b WHERE EXISTS(SELECT * FROM PropertyForRent p WHERE b.city = p.city); Lu Wei
124
Query List the students who have elected course ‘001’ but have not elected course ‘002’ (SELECT sNo FROM SC WHERE cNo='1‘) EXCEPT (SELECT sNo FROM SC WHERE cNo='2‘); Lu Wei
125
Query SELECT sNo FROM SC WHERE cNo='1' AND sNo NOT IN (SELECT sNo FROM SC WHERE cNo='2'); Lu Wei
126
Query Construct a list of all cities where there is a branch office but no properties. (SELECT city FROM Branch) EXCEPT (SELECT city FROM PropertyForRent); (SELECT * FROM Branch) EXCEPT CORRESPONDING BY city (SELECT city FROM PropertyForRent); Lu Wei
127
Query SELECT DISTINCT city FROM Branch WHERE city NOT IN(SELECT city
FROM PropertyForRent); SELECT DISTINCT city FROM Branch b WHERE NOT EXISTS (SELECT * FROM PropertyForRent p WHERE b.city = p.city); Lu Wei
128
Query … Lu Wei
129
Data Manipulation Language (DML)
Query Data Update Lu Wei
130
Data Update Adding data to the database (INSERT)
Adds new rows of data to a table. There are two forms of INSERT statement. The first allows a single row to be inserted into a named talbe and has the following format: INSERT INTO TableName [(columnList)] VALUES (data ValueList) Lu Wei
131
Data Update The second form of the INSERT statement allows multiple rows to be copied from one or more tables to another, and has the following format: INSERT INTO TableName [(columnList)] SELECT … Lu Wei
132
Data Update Examples INSERT INTO Student VALUES (‘08020', '陈冬', '男', 18, 'IS' ); INSERT INTO SC(sNo, cNo) VALUES (‘08020', '1'); INSERT INTO Staff VALUES (‘SG44',‘Anne',‘Jones',‘Assistant', NULL,NULL,8100,’B003’); Lu Wei
133
Data Update CREATE TABLE DeptAge (sDept CHAR(15), avgage SMALLINT);
INSERT INTO DeptAge(sDept, avgage) (SELECT sDept, AVG(sAge) FROM Student GROUP BY sDept); Lu Wei
134
Data Update Assume that there is a table StaffPropCount that contains the names of staff and the number of properties they manage: StaffPropCount(staffNo,fName,lName,propCount) We can popolate the StaffPropCount table using details from the Staff and PropertyForRent tables. Lu Wei
135
Data Update INSERT INTO StaffPropCount (SELECT s.staffNo,fName,lName,COUNT(*) FROM Staff s,PropertyForRent p WHERE s.staffNo = p.staffNo GROUP BY s.staffNo,s.fName,lName) UNION (SELECT staffNo,fName,lName,0 FROM Staff WHERE staffNo NOT IN(SELECT DISTINCT staffNo FROM PropertyForRent)); Lu Wei
136
Data Update Modifying data in the database (UPDATE)
Modifies existing data in a table. UPDATE TableName SET columnName1=dataValue1[,columnName2=datavalue2…] [WHERE searchCondition] Lu Wei
137
Data Update Examples UPDATE Student SET sAge=22 WHERE Sno=‘06001’;
UPDATE Staff SET salary = salary*1.05 WHERE position = ‘Manager’; UPDATE Staff SET positon = ‘Manager’,salary = WHERE staffNo = ‘SG14’; Lu Wei
138
Data Update UPDATE Student SET sAge=sAge+1;
UPDATE Staff SET salary = salary*1.03; Lu Wei
139
Data Update UPDATE SC SET score=0 WHERE ‘CS’= (SELECT sDept
FROM Student WHERE Student.sNo=SC.sNo); Lu Wei
140
Data Update About consistency of update operation
UPDATE Student SET sNo=‘06089' WHERE Sno=‘07007'; UPDATE SC SET sNo=‘06089' WHERE sNo=‘07007'; Lu Wei
141
Data Update Deleting data from the database (DELETE)
Removes rows of data from a table DELETE FROM TableName [WHERE searchCondition] Lu Wei
142
Data Update DELETE FROM Student WHERE sNo=‘05019'; DELETE FROM Viewing
WHERE propertyNo = ‘PG4'; Lu Wei
143
Data Update DELETE FROM SC; DELETE FROM Viewing;
DELETE FROM SC WHERE 'CS'= (SELETE sDept FROM Student WHERE Student.sNo=SC.sNo); We should enccounter the same problem about consistency. Lu Wei
144
Data Update … Lu Wei
145
Summary In this part you should have learned: What is SQL
How to write basic SQL statement Lu Wei
146
Outline Introduction Basic SQL Setting Up and Using PostgreSQL
Advanced SQL Embeded SQL Lu Wei
147
Outline Introduction Basic SQL Setting Up and Using PostgreSQL
Advanced SQL Embeded SQL Lu Wei
148
Outline Introduction Basic SQL Setting Up and Using PostgreSQL
Advanced SQL Embeded SQL Lu Wei
149
Summary In this chapter you should have learned: Lu Wei
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.