SQL Query Practise
SQL Query Practise
1. Data definition: SQL lets a user define the structure and organization of the stored data
and relationships among the stored data items.
2. Data retrieval: SQL allows a user or an application program to retrieve stored data
from the database and use it.
3. Data manipulation: SQL allows a user or an application program to update the
database by adding new data, removing old data, and modifying previously stored data.
4. Access control: SQL can be used to restrict a user's ability to retrieve, add, and modify
data, protecting stored data against unauthorized access.
5. Data sharing: SQL is used to coordinate data sharing by concurrent users, ensuring that
they do not interfere with one another.
6. Data integrity: SQL defines integrity constraints in the database, protecting it from
corruption due to inconsistent updates or system failures.
What Can SQL do?
SQL can execute queries against a database
SQL can retrieve data from a database
SQL can insert records in a database
SQL can update records in a database
SQL can delete records from a database
SQL can create new databases
SQL can create new tables in a database
The DDL part of SQL permits database tables to be created or deleted. It also defines indexes
(keys), specify links between tables, and impose constraints between tables.
The most important DDL statements in SQL are:
CREATE DATABASE- creates a new database
ALTER DATABASE- modifies a database
CREATE TABLE- creates a new table
ALTER TABLE- modifies a table
DROP TABLE- deletes a table
CREATE INDEX- creates an index (search key)
DROP INDEX- deletes an index
Basic structure:
The basic structure of an SQL expression consists of three clauses: SELECT, FROM
and WHERE.
The SELECT clause corresponds to the projection operation of relational algebra. It is
used to list the attributes desired in the result of a query.
The FROM clause corresponds to the Cartesian product operation of relational algebra.
It is used to list the relations to be used in the evaluation of the expression.
The WHERE clause corresponds to the selection predicate of relational algebra. It
consists of a predicate in the attributes of the relations that appear in the FROM clause.
A typical SQL query has the form
SELECT A1, A2, …..,An
FROM R1, R2, …… ,Rn
WHERE P
Where each Ai represents an attribute, each Ri is a relation and P is a predicate.
Its equivalent relational algebra expression is:
A1, A2, …..,An p (R1 X R2 X ……X Rn))
The SQL SELECT Statement:
The SELECT statement is used to select data from a database. The result is stored in a result
table, called the result-set.
SQL SELECT Syntax:
SELECT column_name(s) FROM table_name
and
SELECT * FROM table_name
Note: SQL is not case sensitive. SELECT is the same as select.
IN Operator Example:
The following SQL statement selects all Sailors with a rating of 9 or 11:
SELECT *
FROM Sailors Its equivalent query by using OR
WHERE Rating IN (9, 11); operator is as below:
The result-set will look like this:
SELECT *
Sid sname Rating Age FROM Sailors
2 Robin 11 43 WHERE Rating=9 OR Rating=11;
4 Manoj 9 31
9 Sanjaya 9 42
The result-set will look like this: Sid sname Rating age
1 Ajaya 12 33
3 Ganga 32 28
7 Rahul 7 22
11 Raju 4 19
String operations:
SQL specifies strings by enclosing them in single quotes, for example ‗Pokhara‘. The most
commonly used operation on strings is pattern matching. It uses the operator LIKE. We
describe the patterns by using two special characters:
Percent (%): The % character matches any substring, even the empty string.
Underscore ( _ ): The underscore stands for exactly one character. It matches any
character.
To illustrate pattern matching, we consider the following examples:
‗A_Z‘: All string that starts with ‗A‘, another character and end with ‗Z‘. For example,
‗ABZ‘ and ‗A2Z‘ both satisfy this condition but ‗ABHZ‘ does not because between A
and Z there are two characters are present instead of one.
‗ABC%‘: All strings that start with ‗ABC‘.
‗%ABC‘: All strings that ends with ‗ABC‘.
‗%AN%‘: All strings that contains the pattern ‗AN‘ anywhere. For example, ‗ANGELS‘
,‘SAN‘, ‗FRANCISCO‘ etc.
‗_ _ _‘: matches any strings of exactly three characters.
‗_ _ _%‘: matches any strings of at least three characters.
Example:
SELECT * FROM Sailors
WHERE sname LIKE ‗%ya‘;
This SQL statement will match any Sailors first names that end with ‗ya‘.
The result-set will look like this:
Sid sname Rating age
1 Ajaya 12 33
9 Sanjaya 9 42
Set Operations:
Some time it is useful to combine query results from two or more queries into a single result.
SQL supports three set operators which are:
SQL Union
SQL Intersection and
SQL Except (Minus)
These operators have the pattern:
<query1> <set operator> <query2>
SQL Union Operation:
In SQL the UNION clause combines the results of two SQL queries into a single table of all
matching rows. The two queries must result in the same number of columns and
compatible data types in order to unite. Any duplicate records are automatically removed
unless UNION ALL is used.
Example: Find the names of sailors who have reserved a red or a green boat.
SELECT S.sname
FROM Sailors S, Reserves R, Boats B
WHERE S.sid = R.sid AND R.bid = B.bid
AND (B.color = `red' OR B.color = `green')
This query is difficult to understand (and also quite inefficient to execute, as it turns out). A
better solution for this query is to use UNION as follows:
SELECT S.sname
FROM Sailors S, Reserves R, Boats B
WHERE S.sid = R.sid AND R.bid = B.bid AND B.color = `red'
UNION
SELECT S2.sname
FROM Sailors S2, Boats B2, Reserves R2
WHERE S2.sid = R2.sid AND R2.bid = B2.bid AND B2.color = `green' ;
Example 6: Find the names of sailors who are older than the oldest sailor with a rating of 9.
SELECT S.sname
FROM Sailors S
WHERE S.age > (SELECT MAX (S2.age)
FROM Sailors S2
WHERE S2.rating =9);
The result-set will look like this: Sname
Robin
GROUP BY Clause:
The SQL GROUP BY clause is use to divide the rows in a table into groups. The GROUP BY
statement is used along with the SQL aggregate functions. In GROUP BY clause, the tuples
with same values are placed in one group.
Example: Find the age of the youngest sailor for each rating level.
SELECT rating, MIN(age)
FROM Sailors
GROUP BY rating; Rating Min(age)
The result-set will look like this:
4 19
7 22
9 31
11 43
12 33
32 28
This table display the minimum age of each group according to their rating.
SQL HAVING Clause:
The SQL HAVING clause allows us to specify conditions on the rows for each group. It is used
instead of the WHERE clause when Aggregate Functions are used. HAVING clause should
follow the GROUP BY clause if we are using it.
Example: let‘s take an instance S3 of Sailors,
S3
Sid sname Rating age
1 Ajaya 12 33
2 Robin 11 43
3 Ganga 32 28
4 Manoj 9 31
7 Rahul 7 22
9 Sanjaya 9 42
11 Raju 4 19
22 Robin 11 54
32 Anish 7 21
Example: Find the age of the youngest sailor who is eligible to vote (i.e., is at least 18 years
old) for each rating level with at least two such sailors.
SELECT S.rating, MIN (S.age) AS minage
FROM Sailors S
WHERE S.age >= 18
GROUP BY S.rating
HAVING COUNT (*) > 1
The result-set will look like this: Rating Minage
7 21
9 31
11 43
Example 2: Find the average age of sailors who are of voting age (i.e., at least 18 years old)
for each rating level that has at least two sailors.
SELECT S.rating, AVG ( S.age )
FROM Sailors S
WHERE S. age >= 18
GROUP BY S.rating
HAVING 1 < (SELECT COUNT (*)
FROM Sailors S2
WHERE S.rating = S2.rating );
NULL Values:
SQL allows the use of NULL values to indicate absence of information about the value of an
attribute. It has a special meaning in the database- the value of the column is not currently
known but its value may be known at a later time.
A special comparison operator IS NULL is used to test a column value for NULL. It has
following general format:
Value1 IS [NOT] NULL;
This comparison operator return true if value contains NULL, otherwise return false. The
optional NOT reverses the result.
Following syntax is illegal in SQL:
WHERE attribute=NULL;
Find all sailors that appear in S4 relation with NULL values for rating and age:
SELECT sname
FROM S4
WHERE rating IS NULL AND age IS NULL;
The result-set will look like this: Sname
Sanjaya
Robin
Anish
Nested Sub-queries:
A nested query is a query that has another query embedded within it; the embedded query is
called a sub-query. The result of sub query is used by the main query (outer query). We can
place the sub-query in a number of SQL clauses including:
The WHERE clause
The HAVING clause
The FROM clause
A common use of sub-queries is to perform tasks for set membership and make set comparison.
Set Membership:
The IN connective is used to test a set membership, where set is a collection of values produced
by SELECT clause in sub-query. The NOT IN connective is used to test for absence of set
membership.
Example1: Find the names of sailors who have reserved boat 41.
SELECT sname
FROM Sailors
WHERE sid IN ( SELECT sid
FROM Reserves Sname
WHERE bid=41); Ajaya
The result-set will look like this: Raju
Example 2: Find the names of sailors who have reserved a red boat.
SELECT sname
FROM sailors
WHERE sid IN (SELECT sid
FROM Reservs
WHERE bid IN ( SELECT bid
FROM Boats
WHERE color=’Red’));
The result-set will look like this: sname
Ajaya
Robin
Sanjaya
Example 3: Find the names of sailors who have not reserved a red boat.
SELECT sname
FROM sailors
WHERE sid NOT IN (SELECT sid
FROM Reservs
WHERE bid IN ( SELECT bid
FROM Boats
WHERE color=’Red’));
Sname
Ganga
The result-set will look like this: Manoj
Rahul
Raju
Set Comparison:
The comparison operators are used to compare sets in nested sub-query. SQL allows following
set comparisons:
< SOME, <= SOME, > SOME, >= SOME, = SOME, < > SOME
<ALL, <=ALL, >ALL, >=ALL, = ALL, < >ALL
The keyword ANY is synonymous to SOME in SQL.
Example 1: let’s take an instance S4 of Sailors as:
S4
Sid Sname Rating Age
1 Ajaya 12 33
2 Robin 11 43
3 Ganga 32 28
4 Manoj 9 31
7 Rahul 7 22
9 Sanjaya 9 42
11 Raju 4 19
8 Rahul 6 76
Find the id and names of sailors whose rating is better than some sailor called “Rahul”.
SELECT sid, sname
FROM S4
WHERE rating >ANY (SELECT rating
FROM S4
WHERE sname=’Rahul’);
The result-set will look like this:
Sid Sname
1 Ajaya
2 Robin
3 Ganga
4 Manoj
7 Rahul
9 Sanjaya
Example 2: Find the id and names of sailors whose rating is better than every sailor called
“Rahul”.
SELECT sid, sname
FROM S4
WHERE rating >ALL (SELECT rating
FROM S4
WHERE sname=’Rahul’);
The result-set will look like this:
Sid Sname
1 Ajaya
2 Robin
3 Ganga
4 Manoj
9 Sanjaya
Example 3: Find the id and name of sailor with height rating.
SELECT sid, sname
FROM S4
WHERE rating >=ALL (SELECT rating
FROM S4);
The result-set will look like this:
Sid Sname
3 Ganga
Note: IN and NOT IN are equivalent to =ANY and < > respectively.
Views:
A database view is a logical table. It does not physically store data like tables but
represent data stored in underlying tables in different formats. A view does not require desk
space and we can use view in most places where a table can be used.
Since the views are derived from other tables thus when the data in its source tables are updated,
the view reflects the updates as well. They also can be used by DBA to enforce database
security.
Advantages of Views:
Database security: view allows users to access only those sections of database that
directly concerns them.
View provides data independence.
Easier querying
Shielding from change
Views provide group of users to access the data according to their criteria.
Vies allow the same data to be seen by different users in different ways at the same time.
1.Insertion:
To insert data into a relation, we either specify a tuple to be inserted or write a query
whose result is a set of tuples to be inserted.
Example 1: suppose we need to insert a new record of Sailors of id is11, name is ―Rahul‖,
rating is 9 and of age is 29 then we write following SQL query,
INSERT INTO Sailors
VALUES (11,’Rahul’, 9, 29);
OR
INSERT INTO Sailors (sid, sname, rating, age)
VALUES (11,’Rahul’, 9, 29);
More generally, we might want to insert tuples on the basis of the result of query.
Example 2: suppose we have already some tuples on the relation ‗Sailores‘. Suppose we need to
insert those tuples of sailors into their own relation whose rating is less than 7, this can be write
as,
INSERT INTO Sailors
SELECT *
FROM Sailors
WHERE rating<7;
2. Deletion:
It is used to remove whole records or rows from the table.
Syntax:
DELETE FROM table_name
WHERE <predicate>
Example 1: suppose we need to remove all tuples of Sailors whose age is 32,
DELETE FROM Sailors
WHERE age=32;
Example 2: Remove all tuples of Sailors whose age is less than 30 and rating greater than 7,
DELETE FROM Sailors
WHERE age<32 AND rating>7;
3. Updates:
If we need to change a particular value in a tuple without changing all values in the tuple, then
for this purpose we use update operation.
Syntax:
UPDATE table_name
SET <column i> = <expression i>;
Example: suppose we need to increase the rating of those sailors whose age is greater than 40
by 20%, this can be write as,
UPDATE sailors
SET rating=rating + rating*0.2
WHERE age>40;
Joined relations:
An SQL JOIN clause is used to combine rows from two or more tables, based on a common
field between them.
The types the different SQL JOINs are:
INNER JOIN
LEFT OUTER JOIN
RIGHT OUTER JOIN
FULL OUTER JOIN
INNER JOIN:
It is most common type of join. An SQL INNER JOIN return all rows from multiple tables
where the join condition is met.
SQL INNER JOIN Syntax:
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;
SELECT *
FROM loan NATURAL LEFT OUTER JOIN borrower;
SELECT *
FROM loan NATURAL RIGHT OUTER JOIN borrower;
CREATE DATABASE:
The CREATE DATABASE statement is used to create a database.
Syntax:
CREATE DATABASE dbname;
Example:
CREATE DATABASE my_db;
ALTER DATABASE:
Allow us to modify existing database name.
Syntax:
CREATE TABLE:
Allow us to create a new table within given database.
Syntax:
CREATE TABLE <table_name>
(
<column1> <data type> [not null] [unique][<integrity constraint>],
<column2> <data type> [not null] [unique][<integrity constraint>],
……………….
………………
<column n> <data type> [not null] [unique][<integrity constraint>]
)
Note: [ ]: optional
Example:
CREATE TABLE Sailors
(
Sid INTEGER NOT NULL,
Sname VARCHAR(12),
Rating INTEGER,
Age INTEGER,
PRIMARY KEY (sid)
)
ALTER TABLE:
Allow us to modify a given table.
The structure of given table can be changed either of the following:
By adding new column in existing table
By deleting some columns from an existing table and
By modifying some columns of given table
A new column can be added to the table as follows:
Syntax:
ALTER TABLE <table name>
ADD (<column_name> <datatype>);
Example: suppose we want to add a new column ‗addresses‘ to an existing table Sailors,
ALTER TABLE Sailors
ADD (addresses varchar(15));
Example: suppose we want to remove an existing column ‗addresses‘ from the table sailors as,
ALTER TABLE Sailors
DROP (addresses);
DROP TABLE
It allows us to remove an existing table from the database.
Syntax:
DROP TABLE <table name>
Example: if we want to remove a table ‗Sailors‘ from the database my_db as,
DROP TABLE Sailors;
Embedded SQL:
The programming language in which SQL queries are embedded is called host language.
And the SQL structures permitted in the host language is called embedded SQL. They are
compiled by the embedded SQL processor.
EXEC SQL statement is used to identify embedded SQL request to the preprocessor
Syntax: EXEC SQL <embedded SQL statement > END-EXEC
Note: this varies by language. E.g. the Java embedding uses # SQL { …. } ;
Example: From within a host language, find the name of sailors who uses red boats.
Specify the query in SQL and declare a cursor for it
EXEC SQL
declare c cursor for
select sname
from Sailors S, Boats B ,Reserver R
where S.sid=R.sid
and R.bid=B.bid
and B.color=”Red”;
END-EXEC
Writing queries in SQL is usually much easier than coding same query in a programming
language. However, a programmer must access to a database from a general purpose
programming language for following two reasons:
Not all queries can be expressed in SQL
Non-declarative actions such as printing a report, interacting with user, or sending the
result of query to a graphical user interface etc. cannot be done from the SQL.
Dynamic SQL:
The dynamic SQL component of SQL allows programs to construct and submit SQL
queries at run time. In contrast, embedded SQL statements must be completely present at
compile time; they are compiled by the embedded SQL preprocessor.
Example: The use of dynamic SQL from within a C program.
Example:
Example: Assumed simple relational database is as follows.
g. List all customer whose name should be “smith” and address should be “Kathmandu”.
SELECT customer_name FROM customer
WHERE customer_name = ‗smith‘
OR customer_ address = ‗Kathmandu‘
i. List account no, balance whose balance is between 200 to 700.
SELECT account_no, balance FROM account
WHERE balance BETWEEN 200 AND 700;
j. What happen if we execute the statement?
SELECT account_no, balance FROM account
WHERE balance NOT BETWEEN 200 AND 700;
k. Write SQL statement for (i) using only AND logical connectives and comparison
operatives.
SELECT account_no, balance FROM account
WHERE balance <= 700 AND balance >= 200;
Note: We can retrieve the information from multiple tables; there should be a common attribute
between two tables. i.e., table should be related and we require to join condition.
l. List the customer_id, account_id and balance whose balance is more than 300.
SELECT depositor. customer_id, depositor. account_no, account. balance
FROM depositor, account
WHERE depositor.account_no = account.account_no AND account.balance > 300;
m. List all customers and corresponding balance.
SELECT c.customer_name, a.balance
FROM customer c, account a, depositor d
WHERE d.account_no =a.account_no AND d.customer_id =c.customer_id;
1. Find the names of all Juniors (Level = JR) who are enrolled in a class taught by I. Teach.
2. Find the age of the oldest student who is either a History major or is enrolled in a course
taught by I. Teach.
3. Find the names of all classes that either meet in room R128 or have five or more
students
enrolled.
4. Find the names of all students who are enrolled in two classes that meet at the same
time.
5. Find the names of faculty members who teach in every room in which some class is
taught.
6. Find the names of faculty members for whom the combined enrollment of the courses
that they teach is less than _ve.
7. Print the Level and the average age of students for that Level, for each Level.
8. Print the Level and the average age of students for that Level, for all Levels except JR.
9. Find the names of students who are enrolled in the maximum number of classes.
10. Find the names of students who are not enrolled in any class.
Exercise 5: Consider the following insurance database, where primary keys are underlined:
Teacher (Tid, Tname, Address, Age)
Student (Sid,Sname, Age, sex)
Takes (sid, course-id)
Course (course-id,course_name, text_book)
Teaches(Tid, Cousrse-id)
Taught-by{Sid, Tid}
Construct the following RA expressions for this relational database
a. Fine name, age and sex of all students who takes course ―DBMS‖
b. Find total number of students who are taught by the teacher ―T01‖
c. List all course names text books taught by teaher ―T16‖
d. Find average age of teachers for each course.
e. Insert the record of new teacher ―T06‖ named ―Bhupi‖ of age 27 into
database who lives in ―Balkhu‖.
Exercise 6: Consider the following employee database, where primary keys are underlined.
employee (employee-name, street, city, salary)
works (employee-name, company-name,)
company (company-name, city)
manages (employee-name, manager-name)
Give an expression in SQL for each of the following queries.
a. Find the names of all employees who work for Second Bank Corporation.
b. Find the names, street and cities of residence of all employees whose salary
is more than average salary.
c. Find the names, street addresses, and cities of residence of all employees to
whom company is not assigned yet.
d. Find the names of all employees who work under the manager ―Devi
Prasad‖.
e. Increase the salary of employees by 10% if their salary is less than 10,000
and by 8% otherwise.
a. Find the names of all employees who work for First Bank Corporation.
select employee-name
from works
where company-name = ‘First Bank Corporation‘
b. Find the names and cities of residence of all employees who work for First Bank
Corporation.
select e.employee-name, city
from employee e, works w
where w.company-name = ‘First Bank Corporation‘ and
w.employee-name = e.employee-name
c. Find the names, street address, and cities of residence of all employees who work for First
Bank Corporation and earn more than $10,000.
Soln:- If people may work for several companies, the following solution will only list those
who earn more than $10,000 per annum from ―First Bank Corporation‖ alone.
select *
from employee
where employee-name in (select employee-name from works
where company-name = ‘First Bank Corporation‘ and salary > 10000)
As in the solution to the previous query, we can use a join to solve this one also.
d. Find all employees in the database who live in the same cities as the companies for which
they work.
select e.employee-name
from employee e, works w, company c
where e.employee-name = w.employee-name and e.city = c.city and
w.company -name = c.company -name
e. Find all employees in the database who live in the same cities and on the same streets as
do their managers.
select P.employee-name
from employee P, employee R, manages M
where P.employee-name = M.employee-name and M.manager-
name=R.employee-name and P.street = R.street and P.city = R.city;
f. Find all employees in the database who do not work for First Bank Corporation.
The following solution assumes that all people work for exactly one company.
select employee-name
from works
where company-name ≠ ‘First Bank Corporation‘
If one allows people to appear in the database (e.g. in employee) but not appear in works, or
if people may have jobs with more than one company, the solution is slightly more
complicated.
select employee-name
from employee
where employee-name not in (select employee-name from works
where company-name = ‘First Bank Corporation‘)
g. Find all employees in the database who earn more than every employee of Small Bank
Corporation.
The following solution assumes that all people work for at most one company.
select employee-name
from works
where salary > all (select salary from works
where company-name = ‘Small Bank Corporation‘)
h. Assume that the companies may be located in several cities. Find all companies located in
every city in which Small Bank Corporation is located.
select S.company-name
from company S
where not exists ((select city from company where company-name = ‘Small Bank Corporation‘
)
except
(
select city
from company T
where S.company-name = T.company-name))
i. Find all employees who earn more than the average salary of all employees of their
company.
select employee-name
from works T
where salary > (select avg (salary) from works S
where T.company-name = S.company-name)
update works T
set T.salary = T.salary * 1.1
where T.employee-name in (select manager-name from manages)
and T.salary * 1.1 <= 100000 and T.company-name = ‘First Bank Corporation‘
update works T
set T.salary = T.salary ∗ (case when (T.salary ∗ 1.1 > 100000) then 1.03 else 1.1)
where T.employee-name in (select manager-name from manages) and
T.company-name = ‘First Bank Corporation‘
e. Delete all tuples in the works relation for employees of Small Bank Corporation.
delete works
where company-name = ‘Small Bank Corporation‘
Exercise 7: Consider the following insurance database, where primary keys are underlined:
Student (StuName, StuId, Class, Major)
Course (CourseName, CourseNumber, CreditHours, Department)
Section (SectionId, CourseNumber, Semester, Year, Instructor-Name)
GradeReport (StuId, SectionId, Grade)
Prerequisite (CourseNumber, PrerequisiteNumber)
Construct the following RA expressions for this relational database
Display name and Id of those students whose major is finance and study in 4 th
semester.
Display the number of courses taught by ‗Bhupi‘
Change credit hours of course which course number equal to 19 to 44.
Insert a new student {‗Raju‘, 10, 12, ‗DBMS‘} in student relation.
Display student name, class and instructor name who taught ―DBMS‖
Exercise 8: Consider the following employee database, where primary keys are underlined.
DOCTOR (name, age, address)
WORKS (name, deptno)
DEPARTMENT (deptno, floor, room)
Give an expression in SQL for each of the following queries.
a. List the room and floor of the doctors whose name is ‗Aayan‘ and of age 49.
b. Count the number of doctors working in top floor.