0% found this document useful (0 votes)
23 views

SQL Practice Set

The document provides information about SQL commands and constraints. It explains how to create databases and tables, insert data, and apply constraints. It also includes examples of creating a university database with tables for classes, departments, courses, instructors, students, and their relationships.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

SQL Practice Set

The document provides information about SQL commands and constraints. It explains how to create databases and tables, insert data, and apply constraints. It also includes examples of creating a university database with tables for classes, departments, courses, instructors, students, and their relationships.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 110

SQL

Create DataBase
Syntax:
CREATE DATABASE databasename;

Example:
CREATE DATABASE placement;
Create Table
Syntax:
CREATE TABLE table_name (
    column1 datatype,
    column2 datatype,
    column3 datatype,
   ....
);

Example:
CREATE TABLE Sales (
    "customer_id" VARCHAR(1),
"order_date" DATE,
"product_id" INTEGER);
Create Table Using Another Table
Syntax:
CREATE TABLE new_table_name AS
    SELECT column1, column2,...
    FROM existing_table_name
    WHERE ....;
Example:
CREATE TABLE TestTable AS
SELECT customername, contactname
FROM customers;
INSERT INTO Statement
Syntax:
1. Specify both the column names and the values to be
inserted:
INSERT INTO table_name (column1, column2, column3, ...
)
VALUES (value1, value2, value3, ...);

2. If you are adding values for all the columns of the table
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
Alter Table
• The ALTER TABLE statement is used to add, delete, or modify columns
in an existing table.
• The ALTER TABLE statement is also used to add and drop various
constraints on an existing table.
ALTER TABLE -
• ADD Column
Syntax:
ALTER TABLE table_name
ADD column_name datatype;

• DROP COLUMN
Syntax:
ALTER TABLE table_name
DROP COLUMN column_name;
ALTER TABLE -
• MODIFY Column
Syntax:
ALTER TABLE table_name
MODIFY COLUMN column_name datatype;
Constraints
Syntax:

CREATE TABLE table_name (
    column1 datatype constraint,
    column2 datatype constraint,
    column3 datatype constraint,
    ....
);
Constraints – NOT NULL
• on CREATE TABLE
CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255) NOT NULL,
    Age int
);
Constraints - NOT NULL
• on ALTER TABLE

Syntax:
ALTER TABLE Persons
MODIFY Age int NOT NULL;
Constraints - UNIQUE
• on CREATE TABLE
Syntax:
CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    UNIQUE (ID)
);
CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    CONSTRAINT UC_Person UNIQUE (ID,LastName)
);
Constraints – UNIQUE
• On ALTER TABLE
ALTER TABLE Persons
ADD UNIQUE (ID);

ALTER TABLE Persons
ADD CONSTRAINT UC_Person UNIQUE (ID,LastName);

• DROP
ALTER TABLE Persons
DROP INDEX UC_Person;
Constraint – PRIMARY KEY
• on CREATE TABLE
CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    PRIMARY KEY (ID)
);

CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);
Constraint – PRIMARY KEY

• on ALTER TABLE
ALTER TABLE Persons
ADD PRIMARY KEY (ID);

ALTER TABLE Persons
ADD CONSTRAINT PK_Person PRIMARY KEY (ID,LastName);

• Drop
ALTER TABLE Persons
DROP PRIMARY KEY;
Constraints – FOREIGN KEY
• on CREATE TABLE
CREATE TABLE Orders (
    OrderID int NOT NULL,
    OrderNumber int NOT NULL,
    PersonID int,
    PRIMARY KEY (OrderID),
    FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

CREATE TABLE Orders (
    OrderID int NOT NULL,
    OrderNumber int NOT NULL,
    PersonID int,
    PRIMARY KEY (OrderID),
    CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID)
    REFERENCES Persons(PersonID)
);
Constraint – FOREIGN KEY
• on ALTER TABLE
ALTER TABLE Orders
ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);

ALTER TABLE Orders
ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);

• DROP
ALTER TABLE Orders
DROP FOREIGN KEY FK_PersonOrder;
Constraint - CHECK
• on CREATE TABLE
CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    CHECK (Age>=18)
);

CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    City varchar(255),
    CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')
);
Constraint - CHECK
• on ALTER TABLE
ALTER TABLE Persons
ADD CHECK (Age>=18);

ALTER TABLE Persons
ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City='Sa
ndnes’);

• DROP
ALTER TABLE Persons
DROP CHECK CHK_PersonAge;
Constraint - DEFAULT
• on CREATE TABLE
CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    City varchar(255) DEFAULT ’NCR’
);

CREATE TABLE Orders (
    ID int NOT NULL,
    OrderNumber int NOT NULL,
    OrderDate date DEFAULT CURRENT_DATE()
);
Constraint - DEFAULT
• on ALTER TABLE
ALTER TABLE Persons
ALTER City SET DEFAULT ’NCR’;

• DROP
ALTER TABLE Persons
ALTER City DROP DEFAULT;
Construct the University Database

• Classroom
building Room_num capacity
building varchar(15), room_number varchar(7), capacity numeric(4,0),
primary key (building, room_number)
• Department
Dept_name builiding budget
dept_name varchar(20), building varchar(15), budget numeric(12,2)
Note – budget of the department should more than 0.
• Course
course_id title Dept_name credits
course_id varchar(8), title varchar(50), dept_name varchar(20),
credits numeric(2,0) check (credits > 0), primary key (course_id),
foreign key (dept_name) references department (dept_name) on
delete set null
• Instructor

ID idvarchar(5), name varchar(20)


name Dept_name salary not null, dept_name varchar(20),
salary numeric(8,2) check (salary > 29000), primary key (ID)
Note – Make dept_name as a foreign key and make it null if the
dept_name is deleted from parent table
• Section
Course_id Sec_id semester year building Room_num Time_slot_id

course_id varchar(8), sec_id varchar(8), semester varchar(6) check


(semester in ('Fall', 'Winter', 'Spring', 'Summer’)), year numeric(4,0) check
(year > 1701 and year < 2100), building varchar(15), room_num varchar(7),
time_slot_idvarchar(4), foreign key (course_id) references course
(course_id) on delete cascade, foreign key (building, room_number)
references classroom (building, room_number) on delete set null

• Teaches
ID Course_id Sec_id Semester year

ID varchar(5), course_id varchar(8), sec_id varchar(8), semester


varchar(6), year numeric(4,0), foreign key (course_id, sec_id, semester,
year) references section (course_id, sec_id, semester, year), foreign key (ID)
references instructor (ID)
Note – Both foreign keys are set on cascading delete mode.
• student
Id Name Dept_name

ID varchar(5), name varchar(20) not null, dept_name varchar(20),


tot_cred numeric(3,0) check (tot_cred >= 0), primary key (ID), foreign
key (dept_name) references department (dept_name) on delete set
null
• takes
Id Coure_id Sec_id Semester Year grade
ID varchar(5), course_id varchar(8), sec_id varchar(8), semester
varchar(6), year numeric(4,0), grade varchar(2), primary key (ID,
course_id, sec_id, semester, year), foreign key (course_id, sec_id,
semester, year) references section (course_id, sec_id, semester, year)
on delete cascade, foreign key (ID) references student (ID) on delete
cascade
• advisor
S_ID i_ID

s_ID varchar(5), i_ID varchar(5), primary key (s_ID), foreign key (i_ID)
references instructor (ID) on delete set null, foreign key (s_ID) references
student (ID) on delete cascade
time_slot day Start_hr Start_min End_hr End_min
•Time_slot_id

time_slot_idvarchar(4), day varchar(1), start_hr numeric(2) check (start_hr >=


0 and start_hr < 24), start_min numeric(2) check (start_min >= 0 and
start_min < 60), end_hr numeric(2) check (end_hr >= 0 and end_hr < 24),
end_min numeric(2) check (end_min >= 0 and end_min < 60), primary key
(time_slot_id, day, start_hr, start_min)
Prereq Prereq_id
• Course_id

course_id varchar(8), prereq_id varchar(8), primary key (course_id,


prereq_id), foreign key (course_id) references course (course_id) on delete
cascade, foreign key (prereq_id) references course (course_id)
Q. Point out the correct statement.

a) CHECK constraints enforce domain integrity


b) UNIQUE constraints enforce the uniqueness of the values in
a set of columns
c) In a UNIQUE constraint, no two rows in the table can have
the same value for the columns
d) All of the mentioned
Q. Which of the following constraint does not enforce
uniqueness?

a) UNIQUE
b) Primary key
c) Foreign key
d) None of the mentioned
Q. Constraints can be applied on ___________

a) Column
b) Table
c) Field
d) All of the mentioned
Q. Which of the following is not Constraint in SQL?
a) Primary Key
b) Not Null
c) Check
d) Union
Q. What operator tests column for absence of data

a) NOT Operator
b) Exists Operator
c) IS NULL Operator
d) None of the above
Q. If we have not specified ASC or DESC after a SQL ORDER BY
clause, the following is used by default

a) DESC
b) ASC
c) There is no default value
d) None of the mentioned
Q. _____________ express the number of entities to which
another entity can be associated via a relationship set.

a) Mapping Cardinality
b) Relational Cardinality
c) Participation Constraints
d) None of the mentioned
Q. Drop Table cannot be used to drop a table referenced by a
_________ constraint.

a) Local Key
b) Primary Key
c) Composite Key
d) Foreign Key
Q. Drop Table cannot be used to drop a table referenced by a
_________ constraint.
a) Local Key
b) Primary Key
c) Composite Key
d) Foreign Key
Q. Here which of the following displays unique values of the
column?
select __________ department_name
from instructor;
a) Name
b) All
c) Distinct
d) from
Q. If we want to retain all the duplicates, we must write ____ in place
of union.
a) Union some
b) Union all
c) Duplicate
d) Intersect all
Q. Select name ____ instructor_name, course_id
from instructor, teaches
where instructor . id = teaches . Id
Which keyword is used to rename the field name?
a) Rename
b) As
c) Join
Q. CREATE TABLE temp ( id INT, name VARCHAR(100) ); INSERT INTO
temp VALUES (1, "abc");
INSERT INTO temp VALUES (2, "abc");
INSERT INTO temp VALUES (3, "bcd");
INSERT INTO temp VALUES (4, "cde");
What is the output of the following query
SELECT Count(*) FROM temp GROUP BY name;
Q.
Table
Id
A
Name
Table
Age
B Id Name Age
12 Arun 60 15 Shreya 24
15 Aman 24 25 Hari 40
99 Ayan 11 98 Rohit 20
How many tuples does 99the result
Rohit How
11 many tuples does
the result of the following SQL query contains?
SELECT A.id
FROM A
WHERE A.age > ALL (SELECT B.age
FROM B
WHERE B. name = "arun")
Q. Consider database table Loan_Record
Borrower Bank_Manager Loan_Amount
Alic John 10000
Bob Mark 15000
Jack John 70000

What is the output of the following SQL query?


SELECT Count(*) FROM ( ( SELECT Borrower, Bank_Manager FROM
Loan_Records) AS S NATURAL JOIN ( SELECT Bank_Manager,
Loan_Amount FROM Loan_Records) AS T );
• Find the name of all instructors.
• Find the names of all departments from instructor, and remove duplicates.
• Find the names of all departments from instructor with duplicates.
• Find the monthly salary of all instructors.
• find all instructors in Comp. Sci. dept with salary > 80000.
• Find the names of all instructors with salary between 90,000 and 100,000
(that is  90,000 and  100,000)
• Find the Cartesian product instructor and teaches.
• Find courses that ran in Fall 2009 or in Spring 2010
• Find courses that ran in Fall 2009 and in Spring 2010
• Find courses that ran in Fall 2009 but not in Spring 2010
• For all instructors who have taught some course, find their names and the
course ID of the courses they taught.
• Find the course ID, semester, year and title of each course offered by the
Comp. Sci. department
• Find the name of all instructors.
select name
from instructor
• Find the names of all departments from instructor, and remove duplicates.
select distinct dept_name
from instructor
• Find the names of all departments from instructor with duplicates.
select all dept_name
from instructor
• Find the monthly salary of all instructors.
• find all instructors in Comp. Sci. dept with salary > 80000.
• Find the names of all instructors with salary between 90,000 and 100,000 (that is  90,000 and 
100,000)
• Find the Cartesian product instructor and teaches.
• Find courses that ran in Fall 2009 or in Spring 2010
• Find courses that ran in Fall 2009 and in Spring 2010
• Find courses that ran in Fall 2009 but not in Spring 2010
• For all instructors who have taught some course, find their names and the course ID of the courses
they taught.
• Find the course ID, semester, year and title of each course offered by the Comp. Sci. department
• Find the monthly salary of all instructors.
select ID, name, salary/12
from instructor
• find all instructors in Comp. Sci. dept with salary > 80000.
select name
from instructor
where dept_name = ‘Comp. Sci.' and salary > 80000
• Find the names of all instructors with salary between 90,000 and 100,000 (that is  90,000 and
 100,000)
select name
from instructor
where salary between 90000 and 100000
• Find the Cartesian product instructor and teaches.
• Find courses that ran in Fall 2009 or in Spring 2010
• Find courses that ran in Fall 2009 and in Spring 2010
• Find courses that ran in Fall 2009 but not in Spring 2010
• For all instructors who have taught some course, find their names and the course ID of the
courses they taught.
• Find the course ID, semester, year and title of each course offered by the Comp. Sci.
department
• Find the Cartesian product instructor and teaches.
select 
from instructor, teaches
• Find courses that ran in Fall 2009 or in Spring 2010
(select course_id from section where sem = ‘Fall’ and year = 2009)
union
(select course_id from section where sem = ‘Spring’ and year = 2010)
• Find courses that ran in Fall 2009 and in Spring 2010
(select course_id from section where sem = ‘Fall’ and year = 2009)
intersect
(select course_id from section where sem = ‘Spring’ and year = 2010)
• Find courses that ran in Fall 2009 but not in Spring 2010
(select course_id from section where sem = ‘Fall’ and year = 2009)
except
(select course_id from section where sem = ‘Spring’ and year = 2010)
• For all instructors who have taught some course, find their names and
the course ID of the courses they taught.
select name, course_id
from instructor, teaches
where instructor.ID = teaches.ID
• Find the course ID, semester, year and title of each course offered by
the Comp. Sci. department
select section.course_id, semester, year, title
from section, course
where section.course_id = course.course_id and
dept_name = ‘Comp. Sci.'
• List in alphabetic order the names of all instructors
• Find the average salary of instructors in the Computer Science
department
• Find the total number of instructors who teach a course in the Spring
2010 semester
• Find the number of tuples in the course relation
• Find the average salary of instructors in each department
• Check weather the query is correct
select dept_name, ID, avg (salary)
from instructor
group by dept_name;
• Find the names and average salaries of all departments whose
average salary is greater than 42000
• List in alphabetic order the names of all instructors
select distinct name
from instructor
order by name
• Find the average salary of instructors in the Computer Science department
select avg (salary)
from instructor
where dept_name= ’Comp. Sci.’;
• 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
• Find the number of tuples in the course relation
• Find the average salary of instructors in each department
• Check weather the query is correct
select dept_name, ID, avg (salary)
from instructor
group by dept_name;
• Find the names and average salaries of all departments whose average salary is greater than
42000
• Find the number of tuples in the course relation
select count (*)
from course;
• Find the average salary of instructors in each department
select dept_name, avg (salary)
from instructor
group by dept_name;
• Check weather the query is correct
select dept_name, ID, avg (salary)
from instructor
group by dept_name;
• Find the names and average salaries of all departments whose
average salary is greater than 42000
• Check weather the query is correct
select dept_name, ID, avg (salary)
from instructor
group by dept_name;
• 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;
• Find the names of all instructors whose name includes the substring
“dar”.
• Find all instructors whose salary is null.
• unknown or true = ?
• unknown or false = ?
• unknown or unknown = ?
• true and unknown = ?
• false and unknown = ?
• unknown and unknown = ?
• not unknown = ?
• Find the names of all instructors whose name includes the substring
“dar”.

• Find all instructors whose salary is null.


• unknown or true = ?
• unknown or false = ?
• unknown or unknown = ?
• true and unknown = ?
• false and unknown = ?
• unknown and unknown = ?
• not unknown = ?
• Find the names of all instructors whose name includes the substring “dar”.
select name
from instructor
where name like '%dar%’

• Find all instructors whose salary is null.


select name
from instructor
where salary is null

• unknown or true = ?
• unknown or false = ?
• unknown or unknown = ?
• true and unknown = ?
• false and unknown = ?
• unknown and unknown = ?
• not unknown = ?
• Find the names of all instructors whose name includes the substring “dar”.
select name
from instructor
where name like '%dar%’

• Find all instructors whose salary is null.


select name
from instructor
where salary is null

• unknown or true = true


• unknown or false = unknown
• unknown or unknown = unknown
• true and unknown = unknown,
• false and unknown = false,
• unknown and unknown) = unknown
• not unknown = unknown
• Find the names of all student whose name starts with ‘S’.
• Find the names of all student whose name with second and third
character “an”
• Find all the names of instructors whose names are neither “Mozart”
nor “Einstein”.
• List all departments’ records sorted by budget.
• Find the names of all student whose name starts with ‘S’.
Select Name
From Student
Where name like ’s%’ ;

• Find the names of all student whose name with second and third
character “an”
• Find all the names of instructors whose names are neither “Mozart”
nor “Einstein”.
• List all departments’ records sorted by budget.
• Find the names of all student whose name starts with ‘S’.
Select Name
From Student
Where name like ’s%’ ;

• Find the names of all student whose name with second and third character “an”
Select Name
From Student
Where name like ’__an%’ ;

• Find all the names of instructors whose names are neither “Mozart” nor “Einstein”.
• List all departments’ records sorted by budget.
• Find the names of all student whose name starts with ‘S’.
Select Name
From Student
Where name like ’s%’ ;

• Find the names of all student whose name with second and third character “an”
Select Name
From Student
Where name like ’__an%’ ;

• Find all the names of instructors whose names are neither “Mozart” nor “Einstein”.
SELECT DISTINCT NAME
FROM INSTRUCTOR
WHERE NAME NOT IN ('MOZART', 'EINSTEIN’);

• List all departments’ records sorted by budget.


• Find the names of all student whose name starts with ‘S’.
Select Name
From Student
Where name like ’s%’ ;

• Find the names of all student whose name with second and third character “an”
Select Name
From Student
Where name like ’__an%’ ;

• Find all the names of instructors whose names are neither “Mozart” nor “Einstein”.
SELECT DISTINCT NAME
FROM INSTRUCTOR
WHERE NAME NOT IN ('MOZART', 'EINSTEIN’);

• List all departments’ records sorted by budget.


SELECT DEPT_NAME, BUILDING, BUDGET
FROM DEPARTMENT
ORDER BY BUDGET ;
• Find all instructors earning the highest salary (there may be more
than one with the same salary).
• Increase the salary of each instructor in the Comp. Sci. department by
10%.
• Delete all courses that have never been offered (that is, do not occur
in the section relation).
• Insert every student whose tot_cred attribute is greater than 100 as
an instructor in the same department, with a salary of $10,000.
• Find the total salary of instructors.
• Find all instructors earning the highest salary (there may be more than one
with the same salary).
select ID, name
from instructor
where salary = (select max(salary) from instructor)

• Increase the salary of each instructor in the Comp. Sci. department by 10%.
• Delete all courses that have never been offered (that is, do not occur in the
section relation).
• Insert every student whose tot_cred attribute is greater than 100 as an
instructor in the same department, with a salary of $10,000.
• Find the total salary of instructors.
• Find all instructors earning the highest salary (there may be more than one with the same
salary).
select ID, name
from instructor
where salary = (select max(salary) from instructor)

• Increase the salary of each instructor in the Comp. Sci. department by 10%.
update instructor
set salary = salary * 1.10
where dept name = Compu. Sci.

• Delete all courses that have never been offered (that is, do not occur in the section relation).
• Insert every student whose tot_cred attribute is greater than 100 as an instructor in the
same department, with a salary of $10,000.
• Find the total salary of instructors.
• Find all instructors earning the highest salary (there may be more than one with the same
salary).
select ID, name
from instructor
where salary = (select max(salary) from instructor)

• Increase the salary of each instructor in the Comp. Sci. department by 10%.
update instructor
set salary = salary * 1.10
where dept name = Compu. Sci.

• Delete all courses that have never been offered (that is, do not occur in the section relation).
delete from course
where course_id not in (select course id from section)

• Insert every student whose tot_cred attribute is greater than 100 as an instructor in the
same department, with a salary of $10,000.
• Find the total salary of instructors.
• Find all instructors earning the highest salary (there may be more than one with the same salary).
select ID, name
from instructor
where salary = (select max(salary) from instructor)

• Increase the salary of each instructor in the Comp. Sci. department by 10%.
update instructor
set salary = salary * 1.10
where dept name = Compu. Sci.

• Delete all courses that have never been offered (that is, do not occur in the section relation).
delete from course where course_id not in (select course id from section)

• Insert every student whose tot_cred attribute is greater than 100 as an instructor in the same
department, with a salary of $10,000.
insert into instructor select ID, name, dept name, 10000
from student
where tot red > 100
• Find the total salary of instructors.
Select sum(salary) from instructor;
• Find courses offered in Fall 2009 and in Spring 2010. (using subquery)
• Find courses offered in Fall 2009 but not in Spring 2010.
• Find the total number of (distinct) students who have taken course
sections taught by the instructor with ID 10101.
• Find names of instructors with salary greater than that of some (at
least one) instructor in the Biology department.
• Find names of instructors with salary greater than that of some (at
least one) instructor in the Biology department.(using some )
• Find courses offered in Fall 2009 and in Spring 2010. (using subquery)
select distinct course_id
from section
where semester = ’Fall’ and year= 2009 and
course_id in (select course_id
from section
where semester = ’Spring’ and year= 2010);
• Find courses offered in Fall 2009 but not in Spring 2010.
• Find the total number of (distinct) students who have taken course
sections taught by the instructor with ID 10101.
• Find names of instructors with salary greater than that of some (at least
one) instructor in the Biology department.
• Find names of instructors with salary greater than that of some (at least
one) instructor in the Biology department.(using some )
• Find courses offered in Fall 2009 and in Spring 2010. (using subquery)
select distinct course_id
from section
where semester = ’Fall’ and year= 2009 and
course_id in (select course_id
from section
where semester = ’Spring’ and year= 2010);
• Find courses offered in Fall 2009 but not in Spring 2010.
select distinct course_id
from section
where semester = ’Fall’ and year= 2009 and
course_id not in (select course_id
from section
where semester = ’Spring’ and year= 2010);
• Find the total number of (distinct) students who have taken course sections taught by the
instructor with ID 10101.
• Find names of instructors with salary greater than that of some (at least one) instructor in the
Biology department.
• Find names of instructors with salary greater than that of some (at least one) instructor in the
Biology department.(using some )
• Find the total number of (distinct) students who have taken course
sections taught by the instructor with ID 10101.
• Find names of instructors with salary greater than that of some (at
least one) instructor in the Biology department.
select distinct T.name
from instructor as T, instructor as S
where T.salary > S.salary and S.dept_name = ’Biology’;
• Find names of instructors with salary greater than that of some (at
least one) instructor in the Biology department.(using some )
select name
from instructor
where salary > some (select salary
from instructor
where dept_name = ’Biology’);
Definition of Some Clause

0 0
(5<some 5 )=? (5=some 5 )=?
6 6

0 0
(5>some 5 )=? (5 != some 5 )=?
6 6

0
(5<some 5 )=?
Definition of Some Clause

0 0
(5<some 5 ) = True (5=some 5 ) = True
6 6

0 0
(5>some 5 ) = True (5 != some 5 ) = True
6 6

0
(5<some 5 ) = False
• Find the names of all instructors whose salary is greater than the
salary of all instructors in the Biology department. (using all clause)
• Find the names of all instructors whose salary is greater than the
salary of all instructors in the Biology department.
select name
from instructor
where salary > all (select salary
from instructor
where dept_name = ’Biology’);
Definition of All Clause

0 0
(5 < all 5 )=? (5 = all 5 )=?
6 6

0 0
(5 > all 5 )=? (5 != all 7 )=?
6 6

6
(5 < all 7 )=?
Definition of All Clause

0 0
(5 < all 5 ) = False (5 = all 5 ) = False
6 6

0 0
(5 > all 5 ) = False (5 != all 7 ) = True
6 6

6
(5 < all 7 ) = True
• Which one is the correct output of the following query
select course_id
from section as S
where semester = ’Fall’ and year= 2009 and
exists (select *
from section as T
where semester = ’Spring’ and year= 2010
and S.course_id= T.course_id);

1. all courses taught in the Fall 2009 semester but not in the Spring 2010 semester
2. all courses taught in both the Fall 2009 semester and only in the Spring semester
3. all courses taught in both the Fall 2009 semester and in the Spring 2010 semester
4. all courses taught in the Fall 2009 semester but not in the Spring 2010 semester
• Which one is the correct output of the following query
select course_id
from section as S
where semester = ’Fall’ and year= 2009 and
exists (select *
from section as T
where semester = ’Spring’ and year= 2010
and S.course_id= T.course_id);

1. all courses taught in the Fall 2009 semester but not in the Spring 2010 semester
2. all courses taught in both the Fall 2009 semester and only in the Spring semester
3. all courses taught in both the Fall 2009 semester and in the Spring 2010 semester
4. all courses taught in the Fall 2009 semester but not in the Spring 2010 semester
• To find “the average instructors’ salaries of those departments where
the average salary is greater than $42,000” which of the following
query is correct
1. select dept_name, avg_salary
from (select dept_name, avg (salary) as avg_salary
from instructor
group by dept_name)
where avg_salary > 42000;
2. select dept_name, avg_salary
from (select dept_name, avg (salary)
from instructor
group by dept_name)
as dept_avg (dept_name, avg_salary)
where avg_salary > 42000;
• To find “the average instructors’ salaries of those departments where
the average salary is greater than $42,000” which of the following
query is correct
1. select dept_name, avg_salary
from (select dept_name, avg (salary) as avg_salary
from instructor
group by dept_name)
where avg_salary > 42000;
2. select dept_name, avg_salary
from (select dept_name, avg (salary)
from instructor
group by dept_name)
as dept_avg (dept_name, avg_salary)
where avg_salary > 42000;
• Output of the following query

with dept _total (dept_name, value) as


(select dept_name, sum(salary)
from instructor
group by dept_name),
dept_total_avg(value) as
(select avg(value)
from dept_total)
select dept_name
from dept_total, dept_total_avg
where dept_total.value >= dept_total_avg.value;
• Output of the following query

with dept _total (dept_name, value) as


(select dept_name, sum(salary)
from instructor
group by dept_name),
dept_total_avg(value) as
(select avg(value)
from dept_total)
select dept_name
from dept_total, dept_total_avg
where dept_total.value >= dept_total_avg.value;

all departments where the total salary is greater than the average of the total salary at all
departments
• Output of the following query
select dept_name,
(select count(*)
from instructor
where department.dept_name = instructor.dept_name)
as num_instructors
from department;
• Output of the following query
select dept_name,
(select count(*)
from instructor
where department.dept_name = instructor.dept_name)
as num_instructors
from department;

Ans. Counting of the instructor department wise


• Find the name of the instructor, whose salary *10 is more than
department’s budget.
• Find the name of the instructor, whose salary *10 is more than
department’s budget.

Ans. select name


from instructor
where salary * 10 >
(select budget from department
where department.dept_name = instructor.dept_name)
• Delete all instructors
• Delete all instructors from the Finance department
• Delete all tuples in the instructor relation for those instructors
associated with a department located in the Watson building.
• Delete all instructors
delete from instructor

• Delete all instructors from the Finance department

• Delete all tuples in the instructor relation for those instructors


associated with a department located in the Watson building.
• Delete all instructors
delete from instructor

• Delete all instructors from the Finance department


delete from instructor
where dept_name= ’Finance’;

• Delete all tuples in the instructor relation for those instructors


associated with a department located in the Watson building.
• Delete all instructors
delete from instructor
• Delete all instructors from the Finance department
delete from instructor
where dept_name= ’Finance’;
• Delete all tuples in the instructor relation for those instructors
associated with a department located in the Watson building.
delete from instructor
where dept_name in (select dept_name
from department
where building = ’Watson’);
Which of the following query is correct to perform the action:” Increase salaries of instructors
whose salary is over $100,000 by 3%, and all others receive a 5% raise”

1.update instructor
set salary = salary * 1.03
where salary > 100000;
update instructor
set salary = salary * 1.05
where salary <= 100000;
2. update instructor
set salary = salary * 1.05
where salary <= 100000;
update instructor
set salary = salary * 1.03
where salary > 100000;
Which of the following query is correct to perform the action:” Increase salaries of
instructors whose salary is over $100,000 by 3%, and all others receive a 5% raise”

1.update instructor
set salary = salary * 1.03
where salary > 100000;
update instructor
set salary = salary * 1.05
where salary <= 100000;
2. update instructor
set salary = salary * 1.05
where salary <= 100000;
update instructor
set salary = salary * 1.03
where salary > 100000;

Ans. 1 is correct
• Write the query to perform the following update using CASE
Statement
“ Increase salaries of instructors whose salary is over $100,000 by 3%,
and all others receive a 5% raise”
• Write the query to perform the following update using CASE
Statement
“ Increase salaries of instructors whose salary is over $100,000 by 3%,
and all others receive a 5% raise”

• update instructor
set salary = case
when salary <= 100000 then salary * 1.05
else salary * 1.03
end
Views
• In some cases, it is not desirable for all users to see the entire logical model
(that is, all the actual relations stored in the database.)
• Consider a person who needs to know an instructors name and department,
but not the salary. This person should see a relation described, in SQL, by

select ID, name, dept_name


from instructor

• A view provides a mechanism to hide certain data from the view of certain
users.
• Any relation that is not of the conceptual model but is made visible to a user
as a “virtual relation” is called a view.
View Definition
• We define a view in SQL by using the create view command.
• To define a view, we must give the view a name and must state the query that computes
the view.
• A view is defined using the create view statement which has the form
create view v as < query expression >

where <query expression> is any legal SQL expression. The view name is represented by v.
• Once a view is defined, the view name can be used to refer to the virtual relation that the
view generates.
• View definition is not the same as creating a new relation by evaluating the query
expression
• Rather, a view definition causes the saving of an expression; the expression is
substituted into queries using the view.
View Definition
• the view relation conceptually contains the tuples in the query result,
but is not precomputed and stored.
• Instead, the database system stores the query expression associated
with the view relation.
• Whenever the view relation is accessed, its tuples are created by
computing the query result.
• Thus, the view relation is created whenever needed, on demand.

• A view of instructors without their salary - ?


• A view of instructors without their salary
create view faculty as
select ID, name, dept_name
from instructor

• Is the following query correct (faculty is virtual relation)


select name
from faculty
where dept_name = ‘Biology’
• Is the following query correct (faculty is virtual relation)
select name
from faculty
where dept_name = ‘Biology’
Query is correct, since View names may appear in a query any place
where a relation name may appear.

• What is the output of following query


create view departments_total_salary(dept_name, total_salary) as
select dept_name, sum (salary)
from instructor
group by dept_name
• What is the output of following query
create view departments_total_salary(dept_name, total_salary) as
select dept_name, sum (salary)
from instructor
group by dept_name
• It create the virtual relation with dept_name and its total salary.
View Implementation

• Views are usually implemented as follows.


• When we define a view, the database system stores the definition of
the view itself, rather than the result of evaluation of the query
expression that defines the view.
• Wherever a view relation appears in a query, it is replaced by the
stored query expression.
• Thus, whenever we evaluate the query, the view relation is
recomputed.
Views Defined Using Other Views
• create view physics_fall_2009 as
select course.course_id, sec_id, building, room_number
from course, section
where course.course_id = section.course_id
and course.dept_name = ’Physics’
and section.semester = ’Fall’
and section.year = ’2009’;
• create view physics_fall_2009_watson as
select course_id, room_number
from physics_fall_2009
where building= ’Watson’;
View Expansion
• A way to define the meaning of views defined in terms of other views.
• Let view v1 be defined by an expression e1 that may itself contain uses of
view relations.
• View expansion of an expression repeats the following replacement step:
repeat
Find any view relation vi in e1
Replace the view relation vi by the expression defining vi
until no more view relations are present in e1
• As long as the view definitions are not recursive, this loop will terminate
Select *
From physics_fall_2009
Where building= ’Watson’;

Using view expansion, the above query became as

Select *
From (select course.course_id, sec_id, building, room_number
from course, section
where course.course_id = section.course_id
and course.dept_name = ’Physics’
and section.semester = ’Fall’
and section.year = ’2009’)
Where building= ’Watson’;
Update of View
There are certain conditions needed to be satisfied to update a view. If
any one of these conditions is not met, then we will not be allowed to
update the view.
1.The SELECT statement which is used to create the view should not
include GROUP BY clause or ORDER BY clause.
2.The SELECT statement should not have the DISTINCT keyword.
3.The View should have all NOT NULL values.
4.The view should not be created using nested queries or complex
queries.
5.The view should be created from a single table. If the view is created
using multiple tables then we will not be allowed to update the view.
Find the total number of (distinct) students who have taken course
sections taught by the instructor with ID 10101

select count (distinct ID)


from takes
where (course_id, sec_id, semester, year) in
(select course_id, sec_id, semester, year
from teaches
where teaches.ID= 10101);

You might also like