SQL Sub Queries
SQL Sub Queries
Complex Joins
*
Kindly refer to Lecture Notes section
Example: Find the parcel with the highest estimated loss from a fire
SELECT *
FROM FIRES
WHERE ESTLOSS =
(SELECT MAX(ESTLOSS)
FROM FIRES);
Alternatively, include the subquery as an inline "table" in the FROM clause:
SELECT F.*
FROM FIRES F,
(SELECT MAX(ESTLOSS) MAXLOSS
FROM FIRES) M
WHERE F.ESTLOSS = M.MAXLOSS;
SELECT *
FROM PARCELS
WHERE PARCELID NOT IN
(SELECT PARCELID
FROM FIRES);
SELECT *
FROM PARCELS P
WHERE NOT EXISTS
(SELECT NULL
FROM FIRES F
WHERE P.PARCELID = F.PARCELID);
SELECT *
FROM PARCELS
WHERE (PID, WPB) NOT IN
(SELECT PID, WPB
FROM PERMITS);
SELECT *
FROM PARCELS P
WHERE NOT EXISTS
(SELECT NULL
FROM FIRES F
WHERE P.PARCELID = F.PARCELID);
Example: Find the paper numbers in the URISA database for papers that use both
keyword code 601 AND 602.
The following query does not work, because it is not possible for value for a single
column in a single row to contain two values at the same time:
SELECT PAPER
FROM MATCH
WHERE CODE = 601
AND CODE = 602;
This type of query requires a self-join, which acts as if we had two copies of the MATCH
table and are joining them to each other.
SELECT M1.PAPER
FROM MATCH M1, MATCH M2
WHERE M1.PAPER = M2.PAPER
AND M1.CODE = 601
AND M2.CODE = 602;
If you have trouble imagining the self-join, pretend that we actually created two copies of
MATCH, M1 and M2:
CREATE TABLE M1 AS
SELECT * FROM MATCH;
CREATE TABLE M2 AS
SELECT * FROM MATCH;
SELECT M1.PAPER
FROM M1, M2
WHERE M1.PAPER = M2.PAPER
AND M1.CODE = 601
AND M2.CODE = 602;
The self-join allows us to perform this sort of operation without actually having to copy
the table. We can just act as if we had two copies.
Now, let's add the titles to the paper numbers:
Example: Find the time that passed between a fire on a parcel and all fires
occurring within 300 days later on the same parcel
*
Kindly refer to Lecture Notes section
use of lookup tables to categorize
ownership of properties seeking
zoning variances. (These topics are
the focus of next week's lecture and
lab #3.)
Zoning Variance Database Stages of evolution of the ZONING
Evolution Chart* variance database
*
Kindly refer to Lecture Notes section