Data Definition language (DDL)
Data Manipulation Language (DML)
Other Commands indexes, constraints, views, triggers, transactions, authorization, ...
Select A1, A2, ..., Am # What to return
From R1, R2, ..., Rm # Relations
Where condition # Combine and filter
College(cNAme, state, enrollment) Student(sID, sName, GPA, sizeHS) Apply(sID, cName, major, decision)
select sName, major # This returns duplicates. Why?
from Student, Apply
where student.sID = Apply.sID; # This gives a natural join on sID
select **distinct** sName, major
from Student, Apply
where student.sID = Apply.sID;
select cName # This will break. Why?
from College, apply
where college.cname = apply.cname
and enrollment > 20000 and major = 'CS';
select Student.sID, sName, GPA, Apply.cName, enrollment
from Student, College, Apply
where Apply.sID = Student.sID and Apply.cName = College.cName
**order by GPA desc, enrollment**; # default is ascending
select sID, major
from Apply
**where major like '%bio%'**;
select *
from Apply
**where major like '%bio%'**;
select sID, sName, GPA, sizeHS, GPA*(sizeHS/1000.0)
from Student;
select sID, sName, GPA, sizeHS, **GPA*(sizeHS/1000.0) as scaledGPA** # give the new column a name
from Student;
Select A1, A2, ..., Am
From R1, R2, ..., Rm # Table variables
Where condition
select S.sID, sName, GPA, A.cName, enrollment
**from Student S, College C, Apply A**
where A.sID = S.sID and A.cName = C.cName;
select S1.sID, S1.sName, S2.GPA, S2.sID, S2.sName, S2.GPA # What's the problem here?
from Student S1, Student S2
where S1.GPA = S2.GPA;
select S1.sID, S1.sName, S2.GPA, S2.sID, S2.sName, S2.GPA # Are we done yet?
from Student S1, Student S2
**where S1.GPA = S2.GPA and S1.sID <> S2.sID**; # Note that <> is not equals in SQL
select S1.sID, S1.sName, S2.GPA, S2.sID, S2.sName, S2.GPA
from Student S1, Student S2
**where S1.GPA = S2.GPA and S1.sID < S2.sID**;
select cName as name from College
union
select sName as name from Student;
select cName as name from College
union all
select sName as name from Student;
select sID from Apply where major = 'CS'
intersect
select sID from Apply where major = 'EE';
Not all DBs support intersection
select distinct A1.sID
from Apply A1, Apply A2
where A1.sID = A2.sID and A1.major = 'CS' and A2.major = 'EE';
select sID from Apply where major = 'CS'
except
select sID from Apply where major = 'EE';
Not all DBs support the except operator. We haven't learned the tools to write this without an except yet.
In [ ]: