Megan Taylor

front-end dev, volunteacher, news & data junkie, bibliophile, Flyers fan, sci-fi geek and kitteh servant

Intro to Databases: SQL Subqueries in FROM and SELECT

Expressions involving subqueries: nested SELECT statements in FROM and SELECT clauses

Demo: simple college admissions database
College (cName, state, enrollment)
Student (sID, sName, GPA, sizeHS)
Apply (sID, cName, major, decision)

Return all students whose scaled GPA changes GPA by more than 1
select sID, sName, GPA, GPA*(sizeHS/1000.0) as scaled GPA
from Student
where GPA*(sizeHS/1000.0) – GPA > 1.0 or GPA – GPA*(sizeHS/1000.0) > 1.0;

simplify where clause
select sID, sName, GPA, GPA*(sizeHS/1000.0) as scaled GPA
from Student
where abs(GPA*(sizeHS/1000.0) – GPA) > 1.0;

simplify more with subquery in FROM clause
select *
from (select sID, sName, GPA, GPA*(sizeHS/1000.0) as scaled GPA
from Student) G
where abs(G.scaledGPA – GPA) > 1.0;

Find colleges and pair with highest GPA among applicants
select distinct College.cName, state, GPA
from College, Apply, Student
where College.cNAme = Apply.cName
and Apply.sID = Student.sID
and GPA >= all
(select GPA from Student, Apply
where Student.sID = Apply.sID
and Apply.cName = College.cName);

with subquery in select clause
select cName, state,
(select distinct GPA
from Apply, Student
where College.cName = Apply.cName
and Apply.sID = Student.sID
and GPA >= all
(select GPA from Student, Apply
where Student.sID = Apply.sID
and Apply.cName = College.cName)) as GPA
from College;

Pair colleges with names of applicants
select cName, state,
(select distinct sName
from Apply, Student
where College.cName = Apply.cName
and Apply.sID = Student.sID) as sName
from College;
ERROR subquery in select clause must return exactly one row

November 5, 2011 | Comments Off on Intro to Databases: SQL Subqueries in FROM and SELECT | Categories: Posts | Permalink

Comments are closed.

%d bloggers like this: