SQL Practice Set
SQL Practice Set
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
• Teaches
ID Course_id Sec_id Semester year
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
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
• 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 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’);
• 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’);
• 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
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;
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
• 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.
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