Download as pdf or txt
Download as pdf or txt
You are on page 1of 93

Sarajane

 Marques  Peres,  Ph.D.  –  University  of  São  Paulo  


www.each.usp.br/sarajane  
Based  on  Elsmari,  Navathe  /  Silberschatz,  Korth,  Sudarshan‘s  books    

SQL  
SQL  Data  DefiniLon  and  Data  Types  
• SQL  uses  the  terms:  
– table,  row  and  column  
for  the  formal  relaLon  model  terms    
– relaLon,  tuple  and  aOribute  
respecLvely.  
 
• The  main  SQL  command  for  data  definiLon  is  the  CREATE  
statement.  In  a  basic  context,  we  have:  
– CREATE  SCHEMA  
– CREATE  TABLE  
– CREATE  DOMAIN  
SQL  Data  DefiniLon  and  Data  Types  

• Schema:  group  together  tables  and  other  constructs  that  belong  to  the  
same  database  applicaLon.  

– Scheme  elements  include  tables,  constraints,  views,  domains,  and  other  


constructs  (such  as  authorizaLon  grants)  that  describe  the  schema.  
– In  general,  not  all  users  are  authorized  to  create  schemas  and  schema  
elements.  
– A  catalog  always  contains  a  special  schema  called  INFORMATION_SCHEMA,  
which  provides  informaLon  on  all  the  schemas  in  the  catalog  and  all  the  
element  descriptors  in  these  schemas.  
– Integrity  constraints  such  as  referenLal  integrity  can  be  defined  between  
relaLons  only  if  they  exist  in  schemas  within  the  same  catalog.  
– Schemas  within  the  same  catalog  can  also  share  certain  elements,  such  as  
domain  definiLons.  
PostgreSQL  9.3.5  DocumentaLon  
PostgreSQL  9.3.5  DocumentaLon  
SQL  Data  DefiniLon  and  Data  Types  
• CREATE  TABLE  command  is  used  to  specify  a  new  relaLon  by  giving  it  a  name  and  
specifying  its  aOributes  and  iniLal  constraints.  
• The  key,  enLty  integrity,  and  referenLal  integrity  constraints  can  be  specified  
within  the  CREATE  TABLE  statement  a_er  the  aOributes  are  declared,  or  they  can  
be  added  later  using  the  ALTER  TABLE  command.  
• The  relaLons  declared  through  CREATE  TABLE  statements  are  called  base  tables  
(or  base  relaLons).  They  are  disLnguished  from  virtual  relaLons,  created  through  
the  CREATE  VIEW  statement.  
SQL  Data  DefiniLon  and  Data  Types  
SQL  Data  DefiniLon  and  Data  Types  

L  

J  
SQL  Data  DefiniLon  and  Data  Types  
SQL  Data  DefiniLon  and  Data  Types  
• The  basic  data  types  available  for  aOributes  include  numeric,  character  
string,  bit  string,  Boolean,  date  and  Lme.  
– CLOB  (a  special  type  of  character  string)  
– BLOB  (a  special  type  of  bit  string)  

• AddiLonal  data  types:  


– Timestamp  
– Interval  

• Domains:  this  makes  it  easier  to  change  the  data  type  for  a  domain  that  is  
used  by  numerous  aOributes  in  a  schema,  and  improves  schema  
readability.  
PostgreSQL  9.3.5  DocumentaLon  
Specifying  Constraints  in  SQL  
• Specifying  AOribute  Constraints  and  AOribute  Defaults  
– Constraint  NOT  NULL  
– DEFAULT  <value>  
– CHECK  
Specifying  Constraints  in  SQL  
• Specifying  Key  and  ReferenLal  Integrity  Constraints  
– PRIMARY  KEY  
– UNIQUE  
– FOREIGN  KEY  
• ReferenLal  triggered  acLon  (ON  DELETE  or  ON  UPDATE)  
– SET  NULL  
– CASCAFE  
– SET  DEFAULT  
Specifying  Constraints  in  SQL  
PostgreSQL  9.3.5  DocumentaLon  
PostgreSQL  9.3.5  DocumentaLon  
PostgreSQL  9.3.5  DocumentaLon  
PostgreSQL  9.3.5  DocumentaLon  
Tests  
PostgreSQL  9.3.5  DocumentaLon  
Test  
Test  
Test  
Test  
Basic  Retrieval  Queries  in  SQL  
• IMPORTANT:  SQL  allows  a  table  (relaLon)  to  have  two  or  
more  tuples  that  are  idenLcal  in  all  their  aOribute  values.  
 
• The  SELECT-­‐FROM-­‐WHERE  Structure  of  Basic  SQL  Queries  
Basic  Retrieval  Queries  in  SQL  
Retrieve  the  birth  date  and  address  of  the  employee(s)  whose  name  is  ‘John  B.  
Smith’.  

Retrieve  the  name  and  address  of  all  employees  who  work  for  the  ‘Research’  
department.  
Basic  Retrieval  Queries  in  SQL  
For  every  project  located  in  ‘Stafford’,  list  the  project  number,  the  controlling  
department  number,  and  the  department  manager’s  last  name,  address,  and  
birth  date.  
Basic  Retrieval  Queries  in  SQL  
• Ambiguous  AOribute  Names,  Aliasing,  Renaming,  and  Tuple  
Variables  

For  each  employee,  retrieve  the  employee’s  first  and  last  name  and  the  first  
and  last  name  of  his  or  her  immediate  supervisor.  
Basic  Retrieval  Queries  in  SQL  
• Unspecified  WHERE  Clause  and  Use  of  the  Asterisk  

Select  all  EMPLOYEE  Ssns.  


 
Select  all  combinaLons  of  EMPLOYEE  Ssn  and  DEPARTAMENT  Dname  in  the  
database  
Basic  Retrieval  Queries  in  SQL  
Retrieve  all  the  aOribute  values  of  any  EMPLOYEE  who  works  in  DEPARTMENT  
number  5.  
 
Retrieve  all  the  aOributes  of  an  EMPLOYEE  and  the  aOributes  of  the  
DEPARTMENT  in  which  he  or  she  works  for  every  employee  of  the  ‘Research’  
department.  
Basic  Retrieval  Queries  in  SQL  
• Tables  as  Sets  in  SQL  

Retrieve  the  salary  of  every  employee  and  all.  


 
Retrieve  all  disLnct  salary  values.  
Basic  Retrieval  Queries  in  SQL  
Make  a  list  of  all  project  numbers  for  projects  that  involve  an  employee  whose  
last  name  is  ‘Smith’,  either  as  a  worker  or  as  a  manager  of  the  department  
that  controls  the  project.  

Duplicate  tuples  are  eliminated  form  the  result.    


Use  [UNION  |  EXCEPT  |  INTERSECT]  ALL  if  you  want  to  implement  mulGset  
operaGons.  
Basic  Retrieval  Queries  in  SQL  
• Substring  PaOern  Matching  and  ArithmeLc  Operators  

Retrieve  all  employees  whose  address  is  in  Houston,  Texas.  

Find  all  employees  who  were  born  during  the  1950s.  


Basic  Retrieval  Queries  in  SQL  
Show  the  resulLng  salaries  if  every  employee  working  on  the  ‘ProductX’  
project  is  given  a  10  percent  raise.  

Retrieve  all  employees  in  department  5  whose  salary  is  between  $30,000  and  
$40,000.  
Basic  Retrieval  Queries  in  SQL  
• Ordering  of  Query  Results  

Retrieve  a  list  of  employee  and  the  projects  they  are  working  on,  ordered  by  
department  and,  within  each  department,  ordered  alphabeLcally  by  last  
name,  then  first  name.  
INSERT,  DELETE  and  UPDATE  
Statements  in  SQL  
• The  INSERT  Command  
INSERT,  DELETE  and  UPDATE  
Statements  in  SQL  
• The  DELETE  Command  
INSERT,  DELETE  and  UPDATE  
Statements  in  SQL  
• The  UPDATE  Command  
More  SQL  

Retrieve  the  names  of  all  employees  who  do  not  have  supervisors  
More  SQL  
• Nested  queries  
More  SQL  
• Nested  queries  
Make  a  list  of  all  project  numbers  for  projects  that  involve  an  employee  whose  
last  name  is  ‘Smith’,  either  as  a  worker  or  as  a  manager  of  the  department  
that  controls  the  project.  
More  SQL  
• Nested  queries  
More  SQL  
• Nested  queries  

Select  the  Essns  of  all  employees  who  work  the  same  (project,  hours)  
combinaLon  on  some  project  that  employee  ‘John  Smith’  (whose  Ssn=  
“123456789”  works  on.  
More  SQL  
• Nested  queries  
More  SQL  
• Nested  queries  

List  the  names  of  employees  whose  salary  is  greater  than  the  salary  of  all  the  
employees  in  department  5.  
More  SQL  
• Nested  queries  
More  SQL  
• Nested  queries  

Retrieve  the  name  of  each  employee  who  has  a  dependent  with  the  same  first  
name  and  is  the  same  sex  as  the  employee.  
More  SQL  
• EXISTS  and  UNIQUE  FuncLons  
More  SQL  
• EXISTS  and  UNIQUE  FuncLons  

Retrieve  the  name  of  each  employee  who  has  a  dependent  with  the  same  first  
name  and  is  the  same  sex  as  the  employee.  
More  SQL  
• EXISTS  and  UNIQUE  FuncLons  
More  SQL  
• EXISTS  and  UNIQUE  FuncLons  

Retrieve  the  names  of  employees  who  have  no  dependents.  


More  SQL  
• EXISTS  and  UNIQUE  FuncLons  
More  SQL  
• EXISTS  and  UNIQUE  FuncLons  

List  the  names  of  managers  who  have  at  least  one  dependent.  
More  SQL  
• EXISTS  and  UNIQUE  FuncLons  
More  SQL  
• EXISTS  and  UNIQUE  FuncLons  

Retrieve  the  name  of  each  employee  who  works  on  all  the  projects  controlled  
by  department  number  5.  
More  SQL  
• EXISTS  and  UNIQUE  FuncLons  
More  SQL  
• EXISTS  and  UNIQUE  FuncLons  

Is  the  project  in  depto  5?  

Does  E.Essn  
work  in  that  
project?  
EMP   Project   Project  
A   1   5   A   1  
B   2   5   A   2  
C   3   3   B   1   SSN  =  B  (?)  
C   3   A,1   False  
SSN  =  A  (?)   A,2   True  
A,1   Is  project  1  in  depto  5?     IN   B,1   False  
YES   C,3   False  
Does  A  work  in  project  1   NOT  
YES   EXIST  
SSN  =  C  (?)  
True  AND  False  
A,1   True  
False  
A,2   True  
A,2   False  
B,1   True  
B,1   False  
C,3   False  
C,3   False  
NOT  EXIST  =  True   YES  =  A  
More  SQL  
• EXISTS  and  UNIQUE  FuncLons  

Retrieve  the  name  of  each  employee  who  works  on  all  the  projects  controlled  
by  department  number  5.  
More  SQL  
• Joins  
More  SQL  
• Joins  
More  SQL  
• Aggregate  FuncLons  
Aggregate  FuncLons  and  NULL  values  
More  SQL  
• Group  by  and  Having  
More  SQL  
More  SQL  
More  SQL  
• Group  by  and  Having  
PostgreSQL  -­‐  SELECT  
PostgreSQL  -­‐  WITH  
PostgreSQL  –  OVER  /  PARTITION  
Window  FuncLon  
PostgreSQL  –  Limit  /  Offset  
PostgreSQL  -­‐  Lateral  
Review  
Queries  (consultas)  
• Liste  os  nomes  dos  instrutores  junto  com  os  wtulos  dos  cursos  que  eles  
ministram.  
• Encontre  os  nomes  de  todos  instrutores  que  recebem  um  salário  mais  alto  
do  que  algum  instrutor  de  “Ciência  da  Computação”.  
• Encontre  os  nomes  de  todos  os  instrutores  cujos  nomes  incluem  a  
substring  “dar”.  
• Liste  os  nomes  de  todos  os  instrutores,  em  ordem  alfabéLca.  
• Encontre  os  cursos  que  ocorream  durante  o  Inverno  de  2009  ou  a  
Primavera  de  2010.  
• Encontre  o  número  total  de  instrutores  que  ministram(ministraram)  um  
curso  durante  a  primavera  de  2010.  
• Encontre  os  nomes  e  médias  de  salários  de  todos  departamentos  cuja  
média  de  salários  é  maior  que  42000.  
• Encontre  todos  os  estudantes  que  estão  cursando  todos  os  cursos  
ofertados  pelo  departamento  de  Biologia.  
Review  
List  the  names  of  instructors  along  with  the  
Ltles  of  courses  that  they  teach.  
select name, title
from instructor natural join teaches, course
where teaches.course_id = course.course_id;"

select name, title


from (instructor natural join teaches)
join course using(course_id);"
Review  
• Find  the  names  of  all  instructors  who  have  a  
higher  salary  than  some  instructor  in  “Comp.  
Sci”.  

select distinct T. name


from instructor as T, instructor as S
where T.salary > S.salary and S.dept_name = ‘Comp. Sci.’"
Review  
• Find  the  names  of  all  instructors  whose  name  
includes  the  substring  “dar”.  
select name
"from instructor
"where name like '%dar%'  
Review  
• List  in  alphabeLc  order  the  names  of  all  
instructors  
select distinct name
"from instructor
" order by name"
Review  
• Find  courses  that  ran  in  Fall  2009  or  in  Spring  
2010.  

(select  course_id  from  sec+on  where  sem  =  ‘Fall’ and  year  =  2009)  
 union  
(select  course_id  from  sec+on  where  sem  =  ‘Spring’ and  year  =  2010)  
Review  
• Find  the  total  number  of  instructors  who  
teach  a  course  in  the  Spring  2010  semester.  

select count (distinct ID)


from teaches
where semester = ’Spring’ and year = 2010"
Review  
• Find  the  names  and  average  salaries  of  all  
departments  whose  average  salary  is  greater  
than  42000  

select  dept_name,  avg  (salary)  


from  instructor  
group  by  dept_name  
having  avg  (salary)  >  42000;  
Review  
• Find  all  students  who  have  taken  all  courses  
offered  in  the  Biology  department.  

select  disGnct  S.ID,  S.name  


from  student  as  S  
where  not  exists  (  (select  course_id  
                                                                 from  course  
                                                                 where  dept_name  =  ’Biology’)  
                                                             except  
                                                                 (select  T.course_id  
                                                                     from  takes  as  T  
                                                                     where  S.ID  =  T.ID));  
Review  
• Find  the  average  instructors’  salaries  of  those  
departments  where  the  average  salary  is  
greater  than  $42,000.  

select dept_name, avg_salary


from (select dept_name, avg (salary) as avg_salary
from instructor
group by dept_name)
where avg_salary > 42000;"
Review  
∏instructor.ID,course_id (σdept_name=“Physics” (
σ instructor.ID=teaches.ID (instructor x teaches)))"

∏instructor.ID,course_id (σinstructor.ID=teaches.ID (
σ dept_name=“Physics” (instructor) x teaches))"

∏  name,  +tle  (σ  dept_name=“Comp.  Sci.”  (instructor          teaches          course))  

dept_name        avg(salary)  (instructor)  


Review  
• RelaLonal  model  

license  
Review  
• Find  the  total  number  of  people  who  owned  cars  
that  were  involved  in  accidents  in  1989  

• Ou?  
 
select  count  (disGnct  name)  
from  (((car  join  parLcipated  on  car.license  =  parLcipated.car)  
natural  join  owns)  natural  join  person)  join  accident  on  
accident.report_number  =  parLcipated.report_number  
where  date  between  ‘1989-­‐01-­‐01’  and  ‘1989-­‐12-­‐31’    
Review  
• Add  a  new  accident  to  the  database;  assume  
any  values  for  required  aOributes.  
Name  =  Jones                        model  =  Toyota  
Review  
• Delete  the  Mazda  belonging  to  ‘John  Smith’.  
Review  
• RelaLonal  Model  
Review  
• Find  the  company  that  has  the  most  employees.  
Review  
• Write  an  efficient  relaLonal-­‐algebra  
expression  that  is  equivalent  to  this  query:  
Sarajane  Marques  Peres,  Ph.D.  –  University  of  São  Paulo  
www.each.usp.br/sarajane  
Based  on  Elsmari,  Navathe  /  Silberschatz,  Korth,  Sudarshan‘s  books    

SQL  

You might also like