SlideShare a Scribd company logo
SQL

Chapter 8




            1
Outline
•   Data types
•   DDL
•   Views
•   DML




                           2
One preliminary note..
• SQL is case insensitive!!
 CREATE TABLE = create table = CreAte TAblE


• Quoted text, however, is case sensitive
   “Payroll” != “payroll”




                                              3
Data Types
• Each data item has an associated data type
   – Integer, Char, Date …
• the data type determines the range of values &
  the set of operators and functions that apply to
  it.




                                                     4
Data Types (choose carefully!)

                      Data Types

                                                                  UDT
Binary   Character                                 Numeric
         String        DateTime
String
                     date   time timestamp
                                             INT        DECIMAL

    CHAR      CLOB

BLOB
         VARCHAR


                                                                  5
Data Types
• Some data types require additional
  information
  – decimal(p, s) with precision p & scale s
  – char(n) where n is the (fixed) length of the
    string
  – varchar(n) where n is the max characters in
    the string
  – ……..

                                                   6
2 Basic SQL Classes
• DDL = Data Definition Language
• DML = Data Manipulation Language




                                     7
SQL DDL Operations...
• CREATE
  – CREATE <database object>
    • database, table, index, schema, view, alias, trigger
• DELETE
  – DROP <database object>
    • database, table, index, schema, view, alias, trigger,
• MODIFY
  – ALTER <database object> …
    • table



                                                              8
Create Table
CREATE TABLE student    (
    Number              INTEGER,
    Name                VARCHAR(50),
    Street              VARCHAR(20),
    City                VARCHAR(20),
    PostalCode          CHAR(7),
    Date_of_birth       DATE);


   Create Table is the most fundamental
          DDL statement in SQL
                                          9
Primary Keys
CREATE TABLE student   (
    Number             INTEGER,
    Name               VARCHAR(50),
    Street             VARCHAR(20),
    City               VARCHAR(20),
    PostalCode         CHAR(7),
    Date_of_birth      DATE,
    PRIMARY KEY (Number));
• many attributes can have unique
  constraints but there is only one primary
  key.
                                              10
Primary Keys (cont’d)
CREATE TABLE student (
Number         INTEGER PRIMARY KEY ,
Name           VARCHAR(50) NOT NULL,
Street         VARCHAR(20),
City           VARCHAR(20) NOT NULL,
Postal Code    CHAR(7) NOT NULL
Date_of_birth  DATE NOT NULL);


   •The primary key can be defined immediately
after the attribute if it is a single attribute primary
key.
                                                          11
Foreign Keys
CREATE TABLE Projects(
  Code            CHAR(4) PRIMARY KEY,
  Name            VARCHAR(30) NOT NULL,
  Start_date      Date,
  End_Date        Date,
  dnum            INTEGER,
  FOREIGN KEY (dnum) REFERENCES Department);
• The table referenced by a foreign key must have
  already been created
• If it hasn’t been, you can alter the table later to include
  the foreign key. This solves the “circular reference”
  problem.

                                                          12
Default Values
CREATE TABLE faculty(
  Number        INTEGER NOT NULL PRIMARY KEY,
  Name          VARCHAR(50) NOT NULL,
  Rank          VARCHAR(15) default “Assistant”,
  Phone         VARCHAR(15),
  Office        VARCHAR(10),
  Email         VARCHAR(30),
  Dcode         CHAR(4)REFERENCES department);
• A default value can be specified for an attribute
  if its value is unknown
• Note: a default value cannot be used for a
  primary key…why not?

                                                   13
Dropping an Object (con’t)
• When dropping an object, you may affect
  other objects that depend on it.
  – Eg. A view is defined using one or several
    base tables. If one of these base tables is
    dropped, the view is no longer valid.
• In some cases, the system repairs the
  damage, in other cases you may not be
  allowed to drop an object.

                                                  14
Modifying An Object
ALTER TABLE course
ADD status CHAR(5);
ALTER TABLE faculty
MODIFY email VARCHAR(75);

ALTER TABLE faculty
DROP PRIMARY KEY;

 • ALTER can be used to add columns, to increase the
   length of an existing VARCHAR attribute or to add
   or delete constraints
 • In other cases, you need to drop the table &
   recreate it.
                                                   15
Views
• Views are “virtual” tables derived from
  tables which exist in the database.
• Might be defined to omit some data from a
  table (for privacy), to combine two (or
  more tables) to contain summary data.




                                          16
Views
• we say that the tables defined in the schema
  are base tables
     • eg. course, section, faculty, department
• a view is a virtual table (ie. it does not
  physically exist in the database)
  – derived from one or more base tables
  – adapts the DB to the application without
    modification
  – CREATE VIEW V1 AS <SELECT CLAUSE>
                                                  17
Student ( number, street, city, province, postal_code,
  name, date_of_birth)
Faculty (number, name, rank, phone, office, email,
  dcode, salary)
Department (code, name, start_date, end_date, fnum)
Section (number, cnum, dcode, term, slot, faculty_num)
Course (number , dcode, title, description)
Enrolled (student_num, section_num, cnum, dcode)
Dept_phones (dcode, phone_number)

                                                 18
• Create a view thirdOffered which gives the
 dcode & couses whose number lise between
 3000 & 3999
CREATE VIEW thirdOffered AS
    SELECT number, dcode
    FROM course
    WHERE number >=3000
    AND number <= 3999

 • thirdOffered is a window on the course
   table
    – changes to course are visible in thirdOffered
    – changes to thirdOffered are applied to base     19

      tables
• Create a view ClassList which gives student
   number and name those who are enrolled for the
   course 3753 and section ‘X1’.
  CREATE VIEW ClassList AS
      SELECT student.Number, student.Name
      FROM student, enrolled
      WHERE student_num = number
      AND    cnum = 3753
      AND    section_num = ‘X1’

• ClassList is a window on a join between student
  and enrolled
  – changes to either table are visible in ClassList
  – changes to ClassList cannot be applied to base tables
                                                        20
Querying Views
SELECT *
FROM thirdOffered
WHERE dcode=‘COMP’

               Implemented As

SELECT number, dcode
FROM course
WHERE number >=3000
AND number <= 3999
AND dcode=‘COMP’

                                21
Advantages of Views
• allows same data to be seen in different
  ways by different users
• users perception of DB simplified
  – complex tables are reduced to needed data
• automatic security for data outside view
  – confidential data is left out of the view, making
    it “secure” for people to see the needed info


                                                   22
View Update Problem




                      23
Example 1

INSERT INTO thirdOffered
VALUES (3754, ‘COMP’)




          INSERT INTO course
           VALUES (3754, ‘COMP’, NULL, NULL)


                                       24
Example 2
CREATE VIEW offered AS
    SELECT number
    FROM course
    WHERE dcode = ‘COMP’

       What happens if we perform

   INSERT INTO offered
        VALUES (3754)


                                    25
Updating Views
• Is somewhat complicated – sometimes
  you can do it, and sometimes you can’t.
• Generally, an update to a view from a
  single table with no aggregate functions
  and including the primary (or candidate)
  keys is possible.
• Constraints concerning not null fields may
  cause the view update to fail.

                                          26
Updating Views (cont’d)
• Views created from two or more tables
  involving a join cannot be updated.
• Views containing aggregate functions or
  grouping cannot be updated.




                                            27
DML




      28
Our database (simple version)
Student ( number, street, city, province, postal_code,
  name, date_of_birth)
Faculty (number, name, rank, phone, office, email,
  dcode, salary)
Department (code, name, start_date, end_date, fnum)
Section (number, cnum, dcode, term, slot, faculty_num)
Course (number , dcode, title, description)
Enrolled (student_num, section_num, cnum, dcode)
Dept_phones (dcode, phone_number)

                                                  29
DML - Data Manipulation
          Language
• 4 main SQL statements:

  – INSERT
  – UPDATE
  – DELETE
  – SELECT



                              30
INSERT
INSERT INTO course VALUES
  (3753, ‘COMP’, ‘DBMS’, ‘Database Management Systems’)

INSERT INTO course (number, dcode, title)
     VALUES (3753, ‘COMP’, ‘DBMS’)

INSERT INTO course (number, dcode, title)
     VALUES (3753, ‘COMP’, ‘DBMS’),
             (3713, ‘COMP’, ‘OS’)

INSERT INTO course
     VALUES (&number, &dcode, &title, &description)

                                                          31
UPDATE
UPDATE course
    SET description = ‘A fun course!’
    WHERE title = ‘DBMS’


UPDATE course
    SET description = ‘A fun course!’
    WHERE number = 3753 AND
              dcode = ‘COMP’




                                        32
DELETE

DELETE FROM course
  •deletes the whole table

DELETE FROM course where dcode=‘HIST’
  •deletes the tuples where dcode=‘HIST’




                                           33
Queries (SELECT)
• Retrieval of some information from the
  database
• Result Set contains the “answer” for the
  query.
• Result “Sets” can contain duplicate rows
• Single value Result Sets are considered to
  be one row with one column
• Result Sets can be empty

                                           34
Simple Format

  SELECT <columns>
  FROM <tables>
  WHERE <condition>


Where:
•Columns = list of attributes to be retrieved
•Tables    = list of relations needed to process the query
•Condition = a boolean expression that identifies which
            tuples are to be retrieved

                                                             35
Example

SELECT <columns>
FROM <tables>
WHERE <condition>


 Example:

 SELECT title, description
 FROM   course
 WHERE dcode=‘COMP’

                             36
Important to note ..
• SQL allows duplicate tuples in the result
  set

• For example, retrieving “cnum” and
  “dcode” from Section, we will get identical
  tuples for courses with multiple sections.



                                                37
Important Note #2
• If you are trying to select on a field where
  the data type is VARCHAR(), then this
  select will do:
  – SELECT * FROM t1 WHERE name=‘BOB’
• If you are trying to select on a field where
  the data type is CHAR(5), then this select
  will do:
  – SELECT * FROM t1 WHERE name=‘BOB ’

                                                 38
Important Note #3
• Remember that selects on CHAR and
  VARCHAR types are case sensitive. The
  SELECTS:
  – SELECT * FROM t1 WHERE name=‘BOB’
  – SELECT * FROM t1 WHERE name=‘Bob’
  – SELECT * FROM t1 WHERE name=‘BoB’
• are all different to the DBMS.


                                          39
Example 1
List course number, department code, title
  and description of each course.
     SELECT number, dcode, title, description
     FROM course



       SELECT *
       FROM course

                                                40
Example 2
Find the faculty number and name of each
  faculty member in Computer Science with
  the rank of “Assistant”

SELECT number, name
FROM faculty
WHERE dcode = ‘COMP’ and rank = ‘Assistant’



                                              41
Example #3

Which computer science courses are being
 taught in the second term?

SELECT cnum
FROM section
WHERE dcode = ‘COMP’ and term = ‘X2’




                                           42
Aggregate Functions
• Aggregate functions cannot be expressed
  in regular relational algebra.
• Aggregate functions include simple
  mathematical functions that are useful in a
  DBMS environment such as:
  – sum, average, maximum, minimum, count




                                            43
Aggregate Functions (cont’d)
 Find the average salary of associate
   professors.

      SELECT AVG(salary) AS AverageSalary
      FROM faculty
      WHERE rank=‘Associate’

  •The result has one column called
“AverageSalary” with only one tuple.
                                            44
Aggregate Functions (con’t)
How many professors make more than
 $30,000?
    SELECT COUNT(*) as NumProfs
    FROM faculty
    WHERE salary > 30000

  •The result has one column called “NumProfs”
   with only one tuple.

                                                 45
Aggregate Functions (con’t)
How many different salary levels are paid to
 assistant professors?

    SELECT COUNT(DISTINCT salary)
    FROM faculty
    WHERE rank = ‘Assistant’

   •The result will be one column (which is
 nameless) with one tuple.

                                              46
Grouping
• Sometimes useful to group rows of a table
  together then apply a function to each group
  separately
• select rank wise minimum, maximum and avg
  salary of faculty

SELECT rank, AVG(salary) AS AV, MIN(salary)AS MinSalary,
MAX(salary) AS MaxSalary FROM faculty
GROUP BY rank


 • The result has 4 columns (rank, AV, MinSalary,
   MaxSalary) and one tuple for each rank.
                                                     47
• select rank wise minimum, maximum and avg
  salary of comp department faculties and their
  avg salary is greater than 10000.


SELECT rank, AVG(salary) AS AV,
       MIN(salary) AS MinSalary, MAX(salary) AS MaxSalary
FROM faculty
WHERE dcode = ‘comp’
GROUP BY rank
HAVING AV > 10000;



                                                    48
Expressions in SELECT
 • What is the difference between the start
   and end dates in the department table?
SELECT sdate, edate, (edate-sdate) AS TimeDiff
FROM department
  •The result has 3 attributes (sdate, edate,
timeDiff)
  •timeDiff is returned in a 8 digit number where
the
  first 4 digits are the years, the next two are the
  months, and the final two are the days.
                                                       49
The “Like” Predicate
Retrieve the average salary of professors
 with offices in Carnegie Hall.


SELECT AVG(salary) AS CSalary
FROM faculty
WHERE office LIKE ‘CAR%’




                                            50
Sorting
• rows of result relation can be sorted by
  values in one or more columns

           SELECT name, salary
           FROM faculty
           WHERE salary > 40000
           ORDER BY salary


                                             51
Sorting
Show all salaries less than 40000. Sort the
 output according to salary.

SELECT *                 SELECT *
FROM faculty             FROM faculty
WHERE salary < 40000     WHERE salary < 40000
ORDER BY salary          ORDER BY salary DESC


 Lowest to Highest             Highest to Lowest
                                                   52
“IN”
• The “IN” clause is useful as it allows us to
  match up on a set of data rather than just
  a single piece of data.
• Assuming that the subquery will return
  more than one item, we can match on
  anything in the subquery.



                                            53
Retrieval Using a Subquery
• Find Name & Salary of all department
  heads

 SELECT name, salary
 FROM faculty
 WHERE number
    IN
       (SELECT fnum
       FROM department)



                                         54
“EXISTS”
• We can check to see if a row exists in a
  subquery.
• The subquery does not return any values
  – only the existence of the row is checked.
• We can also use “NOT EXISTS” when the
  cases arises.



                                            55
EXISTS
• List the name, number and salary of all
  professors who are not department heads.

   SELECT name, number, salary
   FROM faculty
   WHERE NOT EXISTS
       (SELECT *
       FROM department
       WHERE fnum = faculty.number)
                                         56
Correlated subqueries
• A correlated sub-query is a sub-query (a query nested
  inside another query) that uses values from the outer
  query in its WHERE clause. The sub-query is evaluated
  once for each row processed by the outer query.
• Example
• Find the list of employees (employee number and names)
  having more salary than the average salary of all
  employees in that employee's department.

  SELECT employee_number, name
  FROM employee AS e1
  WHERE salary > (SELECT avg(salary) FROM
  employee
  WHERE department = e1.department);
                                                     57
• In the above query the outer query is
      SELECT employee_number, name
      FROM employee AS e1
      WHERE salary >
• And the inner query is,

      (SELECT avg(salary) FROM employee
      WHERE department = e1.department);

• In the above nested query the inner query has to be
   executed for every employee as the department will
   change for every row.
• Hence the average salary will also change.
                                                        58
Join
q   Find Name & Salary of all department
    heads
SELECT name, salary
FROM faculty, department
WHERE faculty.number = department.fnum


     For a join, you need to specify all the tables
    which you will use in getting the information.

                                                      59
Join (con’t)
Find the course title, number and section for all
  sections taught by department heads.
SELECT     course.title, section.number, course.number,
          course.dcode, faculty.name
FROM      section, course,
          department, faculty
WHERE section.cnum = course.number
  AND section.dcode = department.dcode
  AND department.fnum = faculty.number


                                                    60
Renaming (Aliasing)

Find the course title, number and section for all
  sections taught by department heads.
SELECT     C.title, S.number, C.number,
           C.dcode, F.name
FROM       section as S, course as C,
           department as D, faculty as F
WHERE      S.cnum = C.number
  AND      S.dcode = D.dcode
  AND      D.fnum = F.number

                                                    61
Set Operations
• Set operations DO exist in SQL
  – UNION
  – INTERSECT
  – EXCEPT (difference)




                                   62

More Related Content

What's hot

SImple SQL
SImple SQLSImple SQL
SImple SQL
John Cutajar
 
Les09
Les09Les09
Adbms 21 sql 99 schema definition constraints and queries
Adbms 21 sql 99 schema definition constraints and queriesAdbms 21 sql 99 schema definition constraints and queries
Adbms 21 sql 99 schema definition constraints and queries
Vaibhav Khanna
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)
Sabana Maharjan
 
Sql Basics | Edureka
Sql Basics | EdurekaSql Basics | Edureka
Sql Basics | Edureka
Edureka!
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
Stewart Rogers
 
Lab
LabLab
Access 04
Access 04Access 04
Access 04
Alexander Babich
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
BG Java EE Course
 
SQL : introduction
SQL : introductionSQL : introduction
SQL : introduction
Shakila Mahjabin
 
Sql database object
Sql database objectSql database object
Sql database object
Harry Potter
 

What's hot (12)

SImple SQL
SImple SQLSImple SQL
SImple SQL
 
Dbms record
Dbms recordDbms record
Dbms record
 
Les09
Les09Les09
Les09
 
Adbms 21 sql 99 schema definition constraints and queries
Adbms 21 sql 99 schema definition constraints and queriesAdbms 21 sql 99 schema definition constraints and queries
Adbms 21 sql 99 schema definition constraints and queries
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)
 
Sql Basics | Edureka
Sql Basics | EdurekaSql Basics | Edureka
Sql Basics | Edureka
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
Lab
LabLab
Lab
 
Access 04
Access 04Access 04
Access 04
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
 
SQL : introduction
SQL : introductionSQL : introduction
SQL : introduction
 
Sql database object
Sql database objectSql database object
Sql database object
 

Similar to Revision sql te it new syllabus

SQL Presentation & explaination short I.pptx
SQL Presentation & explaination short I.pptxSQL Presentation & explaination short I.pptx
SQL Presentation & explaination short I.pptx
lankanking4
 
Database
Database Database
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdf
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdfComplete SQL Tutorial In Hindi By Rishabh Mishra.pdf
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdf
ssuserb5bb0e
 
lec02-data-models-sql-basics.pptx
lec02-data-models-sql-basics.pptxlec02-data-models-sql-basics.pptx
lec02-data-models-sql-basics.pptx
cAnhTrn53
 
BTEC- HND In Computing-Creating Table_Week6.pptx
BTEC- HND In Computing-Creating Table_Week6.pptxBTEC- HND In Computing-Creating Table_Week6.pptx
BTEC- HND In Computing-Creating Table_Week6.pptx
TTKCreation
 
Unit4_Lecture-sql.ppt and data science relate
Unit4_Lecture-sql.ppt and data science relateUnit4_Lecture-sql.ppt and data science relate
Unit4_Lecture-sql.ppt and data science relate
umang2782love
 
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
Md.Mojibul Hoque
 
Chapter 2: Ms SQL Server
Chapter 2: Ms SQL ServerChapter 2: Ms SQL Server
Chapter 2: Ms SQL ServerNgeam Soly
 
Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)
Achmad Solichin
 
MS SQL Server
MS SQL ServerMS SQL Server
MS SQL Server
Md. Mahedee Hasan
 
[Www.pkbulk.blogspot.com]dbms10
[Www.pkbulk.blogspot.com]dbms10[Www.pkbulk.blogspot.com]dbms10
[Www.pkbulk.blogspot.com]dbms10
AnusAhmad
 
6_SQL.pdf
6_SQL.pdf6_SQL.pdf
6_SQL.pdf
LPhct2
 
dbs class 7.ppt
dbs class 7.pptdbs class 7.ppt
dbs class 7.ppt
MARasheed3
 

Similar to Revision sql te it new syllabus (20)

SQL Presentation & explaination short I.pptx
SQL Presentation & explaination short I.pptxSQL Presentation & explaination short I.pptx
SQL Presentation & explaination short I.pptx
 
Database
Database Database
Database
 
plsql Les09
 plsql Les09 plsql Les09
plsql Les09
 
Les09
Les09Les09
Les09
 
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdf
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdfComplete SQL Tutorial In Hindi By Rishabh Mishra.pdf
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdf
 
lec02-data-models-sql-basics.pptx
lec02-data-models-sql-basics.pptxlec02-data-models-sql-basics.pptx
lec02-data-models-sql-basics.pptx
 
BTEC- HND In Computing-Creating Table_Week6.pptx
BTEC- HND In Computing-Creating Table_Week6.pptxBTEC- HND In Computing-Creating Table_Week6.pptx
BTEC- HND In Computing-Creating Table_Week6.pptx
 
Dbms sql-final
Dbms  sql-finalDbms  sql-final
Dbms sql-final
 
Unit4_Lecture-sql.ppt and data science relate
Unit4_Lecture-sql.ppt and data science relateUnit4_Lecture-sql.ppt and data science relate
Unit4_Lecture-sql.ppt and data science relate
 
SQL.pptx
SQL.pptxSQL.pptx
SQL.pptx
 
Sql basics
Sql  basicsSql  basics
Sql basics
 
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
 
Chapter 2: Ms SQL Server
Chapter 2: Ms SQL ServerChapter 2: Ms SQL Server
Chapter 2: Ms SQL Server
 
Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)
 
MS SQL Server
MS SQL ServerMS SQL Server
MS SQL Server
 
[Www.pkbulk.blogspot.com]dbms10
[Www.pkbulk.blogspot.com]dbms10[Www.pkbulk.blogspot.com]dbms10
[Www.pkbulk.blogspot.com]dbms10
 
Unit - II.pptx
Unit - II.pptxUnit - II.pptx
Unit - II.pptx
 
6_SQL.pdf
6_SQL.pdf6_SQL.pdf
6_SQL.pdf
 
dbs class 7.ppt
dbs class 7.pptdbs class 7.ppt
dbs class 7.ppt
 
SQL
SQL SQL
SQL
 

More from saurabhshertukde (19)

Oodbms ch 20
Oodbms ch 20Oodbms ch 20
Oodbms ch 20
 
Introduction er & eer
Introduction er & eerIntroduction er & eer
Introduction er & eer
 
Introduction er & eer
Introduction er &  eerIntroduction er &  eer
Introduction er & eer
 
Integrity & security
Integrity & securityIntegrity & security
Integrity & security
 
Er model
Er modelEr model
Er model
 
Er & eer to relational mapping
Er & eer to relational mappingEr & eer to relational mapping
Er & eer to relational mapping
 
Eer case study
Eer case studyEer case study
Eer case study
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
 
Chapter 9
Chapter 9Chapter 9
Chapter 9
 
J2 ee archi
J2 ee archiJ2 ee archi
J2 ee archi
 
J2 ee architecture
J2 ee architectureJ2 ee architecture
J2 ee architecture
 
Software project-scheduling
Software project-schedulingSoftware project-scheduling
Software project-scheduling
 
Softwareproject planning
Softwareproject planningSoftwareproject planning
Softwareproject planning
 
Pressman ch-3-prescriptive-process-models
Pressman ch-3-prescriptive-process-modelsPressman ch-3-prescriptive-process-models
Pressman ch-3-prescriptive-process-models
 
Design concepts and principles
Design concepts and principlesDesign concepts and principles
Design concepts and principles
 
Analysis modelling
Analysis modellingAnalysis modelling
Analysis modelling
 
Analysis concepts and principles
Analysis concepts and principlesAnalysis concepts and principles
Analysis concepts and principles
 
Risk analysis
Risk analysisRisk analysis
Risk analysis
 

Recently uploaded

Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 

Recently uploaded (20)

Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 

Revision sql te it new syllabus

  • 2. Outline • Data types • DDL • Views • DML 2
  • 3. One preliminary note.. • SQL is case insensitive!! CREATE TABLE = create table = CreAte TAblE • Quoted text, however, is case sensitive “Payroll” != “payroll” 3
  • 4. Data Types • Each data item has an associated data type – Integer, Char, Date … • the data type determines the range of values & the set of operators and functions that apply to it. 4
  • 5. Data Types (choose carefully!) Data Types UDT Binary Character Numeric String DateTime String date time timestamp INT DECIMAL CHAR CLOB BLOB VARCHAR 5
  • 6. Data Types • Some data types require additional information – decimal(p, s) with precision p & scale s – char(n) where n is the (fixed) length of the string – varchar(n) where n is the max characters in the string – …….. 6
  • 7. 2 Basic SQL Classes • DDL = Data Definition Language • DML = Data Manipulation Language 7
  • 8. SQL DDL Operations... • CREATE – CREATE <database object> • database, table, index, schema, view, alias, trigger • DELETE – DROP <database object> • database, table, index, schema, view, alias, trigger, • MODIFY – ALTER <database object> … • table 8
  • 9. Create Table CREATE TABLE student ( Number INTEGER, Name VARCHAR(50), Street VARCHAR(20), City VARCHAR(20), PostalCode CHAR(7), Date_of_birth DATE); Create Table is the most fundamental DDL statement in SQL 9
  • 10. Primary Keys CREATE TABLE student ( Number INTEGER, Name VARCHAR(50), Street VARCHAR(20), City VARCHAR(20), PostalCode CHAR(7), Date_of_birth DATE, PRIMARY KEY (Number)); • many attributes can have unique constraints but there is only one primary key. 10
  • 11. Primary Keys (cont’d) CREATE TABLE student ( Number INTEGER PRIMARY KEY , Name VARCHAR(50) NOT NULL, Street VARCHAR(20), City VARCHAR(20) NOT NULL, Postal Code CHAR(7) NOT NULL Date_of_birth DATE NOT NULL); •The primary key can be defined immediately after the attribute if it is a single attribute primary key. 11
  • 12. Foreign Keys CREATE TABLE Projects( Code CHAR(4) PRIMARY KEY, Name VARCHAR(30) NOT NULL, Start_date Date, End_Date Date, dnum INTEGER, FOREIGN KEY (dnum) REFERENCES Department); • The table referenced by a foreign key must have already been created • If it hasn’t been, you can alter the table later to include the foreign key. This solves the “circular reference” problem. 12
  • 13. Default Values CREATE TABLE faculty( Number INTEGER NOT NULL PRIMARY KEY, Name VARCHAR(50) NOT NULL, Rank VARCHAR(15) default “Assistant”, Phone VARCHAR(15), Office VARCHAR(10), Email VARCHAR(30), Dcode CHAR(4)REFERENCES department); • A default value can be specified for an attribute if its value is unknown • Note: a default value cannot be used for a primary key…why not? 13
  • 14. Dropping an Object (con’t) • When dropping an object, you may affect other objects that depend on it. – Eg. A view is defined using one or several base tables. If one of these base tables is dropped, the view is no longer valid. • In some cases, the system repairs the damage, in other cases you may not be allowed to drop an object. 14
  • 15. Modifying An Object ALTER TABLE course ADD status CHAR(5); ALTER TABLE faculty MODIFY email VARCHAR(75); ALTER TABLE faculty DROP PRIMARY KEY; • ALTER can be used to add columns, to increase the length of an existing VARCHAR attribute or to add or delete constraints • In other cases, you need to drop the table & recreate it. 15
  • 16. Views • Views are “virtual” tables derived from tables which exist in the database. • Might be defined to omit some data from a table (for privacy), to combine two (or more tables) to contain summary data. 16
  • 17. Views • we say that the tables defined in the schema are base tables • eg. course, section, faculty, department • a view is a virtual table (ie. it does not physically exist in the database) – derived from one or more base tables – adapts the DB to the application without modification – CREATE VIEW V1 AS <SELECT CLAUSE> 17
  • 18. Student ( number, street, city, province, postal_code, name, date_of_birth) Faculty (number, name, rank, phone, office, email, dcode, salary) Department (code, name, start_date, end_date, fnum) Section (number, cnum, dcode, term, slot, faculty_num) Course (number , dcode, title, description) Enrolled (student_num, section_num, cnum, dcode) Dept_phones (dcode, phone_number) 18
  • 19. • Create a view thirdOffered which gives the dcode & couses whose number lise between 3000 & 3999 CREATE VIEW thirdOffered AS SELECT number, dcode FROM course WHERE number >=3000 AND number <= 3999 • thirdOffered is a window on the course table – changes to course are visible in thirdOffered – changes to thirdOffered are applied to base 19 tables
  • 20. • Create a view ClassList which gives student number and name those who are enrolled for the course 3753 and section ‘X1’. CREATE VIEW ClassList AS SELECT student.Number, student.Name FROM student, enrolled WHERE student_num = number AND cnum = 3753 AND section_num = ‘X1’ • ClassList is a window on a join between student and enrolled – changes to either table are visible in ClassList – changes to ClassList cannot be applied to base tables 20
  • 21. Querying Views SELECT * FROM thirdOffered WHERE dcode=‘COMP’ Implemented As SELECT number, dcode FROM course WHERE number >=3000 AND number <= 3999 AND dcode=‘COMP’ 21
  • 22. Advantages of Views • allows same data to be seen in different ways by different users • users perception of DB simplified – complex tables are reduced to needed data • automatic security for data outside view – confidential data is left out of the view, making it “secure” for people to see the needed info 22
  • 24. Example 1 INSERT INTO thirdOffered VALUES (3754, ‘COMP’) INSERT INTO course VALUES (3754, ‘COMP’, NULL, NULL) 24
  • 25. Example 2 CREATE VIEW offered AS SELECT number FROM course WHERE dcode = ‘COMP’ What happens if we perform INSERT INTO offered VALUES (3754) 25
  • 26. Updating Views • Is somewhat complicated – sometimes you can do it, and sometimes you can’t. • Generally, an update to a view from a single table with no aggregate functions and including the primary (or candidate) keys is possible. • Constraints concerning not null fields may cause the view update to fail. 26
  • 27. Updating Views (cont’d) • Views created from two or more tables involving a join cannot be updated. • Views containing aggregate functions or grouping cannot be updated. 27
  • 28. DML 28
  • 29. Our database (simple version) Student ( number, street, city, province, postal_code, name, date_of_birth) Faculty (number, name, rank, phone, office, email, dcode, salary) Department (code, name, start_date, end_date, fnum) Section (number, cnum, dcode, term, slot, faculty_num) Course (number , dcode, title, description) Enrolled (student_num, section_num, cnum, dcode) Dept_phones (dcode, phone_number) 29
  • 30. DML - Data Manipulation Language • 4 main SQL statements: – INSERT – UPDATE – DELETE – SELECT 30
  • 31. INSERT INSERT INTO course VALUES (3753, ‘COMP’, ‘DBMS’, ‘Database Management Systems’) INSERT INTO course (number, dcode, title) VALUES (3753, ‘COMP’, ‘DBMS’) INSERT INTO course (number, dcode, title) VALUES (3753, ‘COMP’, ‘DBMS’), (3713, ‘COMP’, ‘OS’) INSERT INTO course VALUES (&number, &dcode, &title, &description) 31
  • 32. UPDATE UPDATE course SET description = ‘A fun course!’ WHERE title = ‘DBMS’ UPDATE course SET description = ‘A fun course!’ WHERE number = 3753 AND dcode = ‘COMP’ 32
  • 33. DELETE DELETE FROM course •deletes the whole table DELETE FROM course where dcode=‘HIST’ •deletes the tuples where dcode=‘HIST’ 33
  • 34. Queries (SELECT) • Retrieval of some information from the database • Result Set contains the “answer” for the query. • Result “Sets” can contain duplicate rows • Single value Result Sets are considered to be one row with one column • Result Sets can be empty 34
  • 35. Simple Format SELECT <columns> FROM <tables> WHERE <condition> Where: •Columns = list of attributes to be retrieved •Tables = list of relations needed to process the query •Condition = a boolean expression that identifies which tuples are to be retrieved 35
  • 36. Example SELECT <columns> FROM <tables> WHERE <condition> Example: SELECT title, description FROM course WHERE dcode=‘COMP’ 36
  • 37. Important to note .. • SQL allows duplicate tuples in the result set • For example, retrieving “cnum” and “dcode” from Section, we will get identical tuples for courses with multiple sections. 37
  • 38. Important Note #2 • If you are trying to select on a field where the data type is VARCHAR(), then this select will do: – SELECT * FROM t1 WHERE name=‘BOB’ • If you are trying to select on a field where the data type is CHAR(5), then this select will do: – SELECT * FROM t1 WHERE name=‘BOB ’ 38
  • 39. Important Note #3 • Remember that selects on CHAR and VARCHAR types are case sensitive. The SELECTS: – SELECT * FROM t1 WHERE name=‘BOB’ – SELECT * FROM t1 WHERE name=‘Bob’ – SELECT * FROM t1 WHERE name=‘BoB’ • are all different to the DBMS. 39
  • 40. Example 1 List course number, department code, title and description of each course. SELECT number, dcode, title, description FROM course SELECT * FROM course 40
  • 41. Example 2 Find the faculty number and name of each faculty member in Computer Science with the rank of “Assistant” SELECT number, name FROM faculty WHERE dcode = ‘COMP’ and rank = ‘Assistant’ 41
  • 42. Example #3 Which computer science courses are being taught in the second term? SELECT cnum FROM section WHERE dcode = ‘COMP’ and term = ‘X2’ 42
  • 43. Aggregate Functions • Aggregate functions cannot be expressed in regular relational algebra. • Aggregate functions include simple mathematical functions that are useful in a DBMS environment such as: – sum, average, maximum, minimum, count 43
  • 44. Aggregate Functions (cont’d) Find the average salary of associate professors. SELECT AVG(salary) AS AverageSalary FROM faculty WHERE rank=‘Associate’ •The result has one column called “AverageSalary” with only one tuple. 44
  • 45. Aggregate Functions (con’t) How many professors make more than $30,000? SELECT COUNT(*) as NumProfs FROM faculty WHERE salary > 30000 •The result has one column called “NumProfs” with only one tuple. 45
  • 46. Aggregate Functions (con’t) How many different salary levels are paid to assistant professors? SELECT COUNT(DISTINCT salary) FROM faculty WHERE rank = ‘Assistant’ •The result will be one column (which is nameless) with one tuple. 46
  • 47. Grouping • Sometimes useful to group rows of a table together then apply a function to each group separately • select rank wise minimum, maximum and avg salary of faculty SELECT rank, AVG(salary) AS AV, MIN(salary)AS MinSalary, MAX(salary) AS MaxSalary FROM faculty GROUP BY rank • The result has 4 columns (rank, AV, MinSalary, MaxSalary) and one tuple for each rank. 47
  • 48. • select rank wise minimum, maximum and avg salary of comp department faculties and their avg salary is greater than 10000. SELECT rank, AVG(salary) AS AV, MIN(salary) AS MinSalary, MAX(salary) AS MaxSalary FROM faculty WHERE dcode = ‘comp’ GROUP BY rank HAVING AV > 10000; 48
  • 49. Expressions in SELECT • What is the difference between the start and end dates in the department table? SELECT sdate, edate, (edate-sdate) AS TimeDiff FROM department •The result has 3 attributes (sdate, edate, timeDiff) •timeDiff is returned in a 8 digit number where the first 4 digits are the years, the next two are the months, and the final two are the days. 49
  • 50. The “Like” Predicate Retrieve the average salary of professors with offices in Carnegie Hall. SELECT AVG(salary) AS CSalary FROM faculty WHERE office LIKE ‘CAR%’ 50
  • 51. Sorting • rows of result relation can be sorted by values in one or more columns SELECT name, salary FROM faculty WHERE salary > 40000 ORDER BY salary 51
  • 52. Sorting Show all salaries less than 40000. Sort the output according to salary. SELECT * SELECT * FROM faculty FROM faculty WHERE salary < 40000 WHERE salary < 40000 ORDER BY salary ORDER BY salary DESC Lowest to Highest Highest to Lowest 52
  • 53. “IN” • The “IN” clause is useful as it allows us to match up on a set of data rather than just a single piece of data. • Assuming that the subquery will return more than one item, we can match on anything in the subquery. 53
  • 54. Retrieval Using a Subquery • Find Name & Salary of all department heads SELECT name, salary FROM faculty WHERE number IN (SELECT fnum FROM department) 54
  • 55. “EXISTS” • We can check to see if a row exists in a subquery. • The subquery does not return any values – only the existence of the row is checked. • We can also use “NOT EXISTS” when the cases arises. 55
  • 56. EXISTS • List the name, number and salary of all professors who are not department heads. SELECT name, number, salary FROM faculty WHERE NOT EXISTS (SELECT * FROM department WHERE fnum = faculty.number) 56
  • 57. Correlated subqueries • A correlated sub-query is a sub-query (a query nested inside another query) that uses values from the outer query in its WHERE clause. The sub-query is evaluated once for each row processed by the outer query. • Example • Find the list of employees (employee number and names) having more salary than the average salary of all employees in that employee's department. SELECT employee_number, name FROM employee AS e1 WHERE salary > (SELECT avg(salary) FROM employee WHERE department = e1.department); 57
  • 58. • In the above query the outer query is SELECT employee_number, name FROM employee AS e1 WHERE salary > • And the inner query is, (SELECT avg(salary) FROM employee WHERE department = e1.department); • In the above nested query the inner query has to be executed for every employee as the department will change for every row. • Hence the average salary will also change. 58
  • 59. Join q Find Name & Salary of all department heads SELECT name, salary FROM faculty, department WHERE faculty.number = department.fnum For a join, you need to specify all the tables which you will use in getting the information. 59
  • 60. Join (con’t) Find the course title, number and section for all sections taught by department heads. SELECT course.title, section.number, course.number, course.dcode, faculty.name FROM section, course, department, faculty WHERE section.cnum = course.number AND section.dcode = department.dcode AND department.fnum = faculty.number 60
  • 61. Renaming (Aliasing) Find the course title, number and section for all sections taught by department heads. SELECT C.title, S.number, C.number, C.dcode, F.name FROM section as S, course as C, department as D, faculty as F WHERE S.cnum = C.number AND S.dcode = D.dcode AND D.fnum = F.number 61
  • 62. Set Operations • Set operations DO exist in SQL – UNION – INTERSECT – EXCEPT (difference) 62

Editor's Notes

  1. 5
  2. 5
  3. 5
  4. 19
  5. 20
  6. 20
  7. 21
  8. 22
  9. 23
  10. 24
  11. 26
  12. 6
  13. 7
  14. 7
  15. 7
  16. 11
  17. 7
  18. 7
  19. 9
  20. 9
  21. 13
  22. 14
  23. 14
  24. 14