SlideShare a Scribd company logo
SQL Tutorial
Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414
COMPUTER EDUCATION
DIVISION
ABRO&SIS
A Group of Artist and Computer S/W & H/W Professional
SQL Tutorial 2
amit@abroandsis.com, amit_abros@yahoo.com
SQL
SQL stands for Structured Query Language. It is a Fourth Generation Language
(4 GL). SQL commands can be divided into Five major categories with regard to
their functionality. They are :
(i) Data Definition Language (DDL).
(ii) Data Manipulation Language (DML).
(iii) Transaction Control Commands
(iv) Session Control Commands
(v) System Control Command.
Data Definition Language (DDL)
DDL stands for Data definition language. It provides facility/ commands to create and
maintain the database. To construct and administer the database, there are three major DDL
statements –
(i) CREATE
(ii) DROP
(iii) ALTER
Data Manipulation Language (DML)
DML stands for data manipulation language. It provides facility to manipulate data in a
table. To manipulate data in tables directly or through views we use the four standard DML
statements. They are :
(i) SELECT
(ii) DELETE
(iii) INSERT
(iv) UPDATE
Data manipulation capability allows one to retrieve and modify contents of the database/
table.
COMPUTER EDUCATION DIVISION 3
ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414
Transaction Control Language (TCL)
Transaction control commands manage changes made by DML commands.
(i) COMMIT
(ii) ROLLBACK
(iii) SAVEPOINT
Session Control Commands
Session Control command dynamically manage the properties of a user session.
(i) ALTER SESSION
(ii) SET ROLL
System Control Command
System Control Command dynamically manages the properties of an Oracle instance. This
command does not implicitly commit the current transaction.
(i) ALTER SYSTEM
Note :
TCL command, Session control command, and System control commands are discussed in
Oracle/ PL SQL Tutorial.
DDL COMMANDS
To Create a Table - CREATE statement is used to create a table.
Syntax :
CREATE TABLE < table name > ( < attribute list >) ;
Where,
< attribute list > : : = < attribute name > < data type > [NOT NULL] [, < attribute list >]
< data type > : : = < integer / smallint / char(n) / varchar(n) / float / decimal(p[, q]) >.
SQL Tutorial
amit@abroandsis.com, amit_abros@yahoo.com
e.g.,
CREATE TABLE Employee (Emp_no integer NOT NULL, Name char(25), Skill
char(20), Pay_rate decimal(10,2)) ;
CREATE statement can be used to create database, table, index or view.
To create index - CREATE INDEX statement is used to create index in an existing
relation. The columns to be used in the generation of the index are also specified. The
CLUSTER option could be specified to indicate that the records are to be placed in physical
proximity to each other.
Syntax :
CREATE [UNIQUE] INDEX <name of index > ON <existing table name>
(<column name [ ASC/ DESC ] [, column name [ ORDER] ….. ] ) [ CLUSTER] ;
e.g., CREATE INDEX Emp_index ON Employee (Name ASC, Pay_rate DESC);
To Create a View - CREATE statement is used to create a view. View is a virtual relation.
Syntax :
CREATE VIEW < view name > AS < query expression >
CREATE VIEW < view name > (At_name1, At_name2, …. ) AS (SELECT …. )
e.g., a view can be created for a subset of the tuples of a relation.
Command Purpose
CREATE DATABASE To create database.
CREATE TABLE To create table/ relation.
CREATE INDEX To create an index on a column.
CREATE VIEW To create a view.
DROP DATABASE To delete a database.
DROP TABLE To delete a table.
DROP INDEX To delete an index
DROP VIEW To delete a view.
COMPUTER EDUCATION DIVISION 5
ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414
CREATE VIEW FreeEmp AS (SELECT Emp_no FROM Employee) MINUS
(SELECT Emp_no FROM Duty_allocation ) ;
CREATE VIEW Employ ( E_no, Ename, E_skill) AS (SELECT Emp_no, Name,
Skill FROM Employee );
CREATE TABLE Emp_info (Emp_no integer NOT NULL, Name char(20), Skill char(20),
Phone_no decimal(10));
CREATE TABLE Emp_pay_rate (Emp integer NOT NULL, Hourly_rate decimal(10,2));
These two tables can be seems as a single in the form of view as :
CREATE VIEW Employ Emp_no, Name, Skill, Pay_rate AS (SELECT Emp_no, Name,
skill, hourly_rate FROM Emp_Info, Emp_pay_rate WHERE Emp_no = Emp);
To Delete a view - DROP statement is used to delete a view.
Syntax :
DROP VIEW < view _name >
e.g., DROP VIEW FreeEmp.
Note :
A tuple in a view can be theoretically updated, under the following constraints :
1. Any update operation through a view requires that the user has appropriate
authorization.
2. if the definition of the view involves a simple query on a single base relation and
includes the primary key, the following update operations are possible:
a) A new tuple could be inserted into the database via a view.
b) An existing tuple could be deleted via a view.
c) The value of a nonprime attribute could be modified.
3. The insertion of a new record using a view requires that the primary attributes are
included in the view, and the values for these are specified for the insertion i.e., they
are not null.
4. Updates are not allowed through views involving aggregation or grouping
operations.
SQL Tutorial
amit@abroandsis.com, amit_abros@yahoo.com
5. Updates are allowed through a view defined using a simple query involving a single
base relation and containing either the primary key or a candidate key of the base
relation.
6. Updates are not allowed through view involving multiple relations.
To Delete Existing Table or Index - DROP statement is used to delete existing database,
table, index or view.
Syntax :
DROP TABLE < existing table name >
DROP INDEX < existing index name >
e.g., DROP TABLE Employee;
DROP INDEX emp_index ;
In addition to CREATE and DROP statement ALTER TABLE or MODIFY DATABASE
are also available in DDL.
To alter an existing table – ALTER statement is used to alter an existing table.
ALTER statement can be used to alter the existing table. This statement allows
one or more new column to add to an existing relation. The added column
contains NULL value by default.
Syntax :
ALTER TABLE <existing table name> ADD <column name> <data type> [ … ]
Where,
<column name> : : = field name / new field name.
e.g.,
ALTER TABLE Employee ADD Phone_no decimal(10);
ALTER TABLE Employee ADD Ta Decimal(4), Hra Decimal(4).
COMPUTER EDUCATION DIVISION 7
ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414
DML COMMANDS
To Update existing Table - UPDATE statement is used to modify one or more records in
a specified relation. The record to be modified are specified by a predicate in WHERE
clause and the new value of the column to be modified is specified by a SET clause.
Syntax :
UPDATE <relation> SET <target value list> [WHERE <predicate>]
Where,
<target value list> : : = <attribute name> = <value expression> [, <target value list>]
e.g., UPDATE Employee SET Pay_rate = 7.85 WHERE Name = “Ram” ;
To Delete record – Delete statement is used to delete one or more records from a relation.
The records to be deleted are specified by the predicate in the WHERE clause. You are
required to specify WHERE clause otherwise all the records from the relation can be
deleted, but the relation is still remain in the database, although it is an empty relation.
Syntax :
DELETE FROM < relation > [ WHERE < predicate >]
e.g.,
DELETE FROM Employee WHERE Name = “Ram”
To Insert record - INSERT statement is used to insert a new tuple into a specified relation.
The value of each field of the record to be inserted is either specified by an expression or
could come form selected records of existing table.
Syntax :
(i) INSERT INTO < relation > VALUES (< value list > )
(ii) INSERT INTO < relation > (< target list >) VALUES (< value list >) ;
Where,
< value list > : : = < value expression > [, < value list > ] ;
< target list > : : = < attribute name > [, < target list > ] ;
e.g., INSERT INTO Employee VALUES (456, “Shyam”, “Cook”, 7.50)
SQL Tutorial
amit@abroandsis.com, amit_abros@yahoo.com
Note :
VALUES clause can be represented by a SELECT statement, which is evaluated and the
result is inserted into the relation specified in the INSERT statement.
In (ii) Syntax, a list of attribute names whose values are included in the < value list > are
specified.
To retrieve records – SELECT statement is the only data retrieval statement in SQL. It
specifies the methods of selecting/ showing the tuples of the relation.
Syntax :
SELECT <target list> FROM <relation list> [ WHERE <Predicate>] ;
Or,
SELECT [DISTINCT] <target list> FROM < relation list > [ WHERE < predicates > ]
[ ORDER BY < int / column_name [ASC / DESC ], … > ] ;
Where,
DISTINCT option is used in the select statement to eliminate duplicate tuples in the result.
< target list > : : = < attribute/ field name > [ , < target list> ]
FROM clause specifies the relations to be used in the evaluation of the statement. It
includes a relation list.
< relation list> : : = < relation name > [ < tuple variable >] [, < relation list > ]
< tuple variable > : : = a tuple variable is an identifier. The domain of the tuple variable is
the relation preceding it.
WHERE The where clause is used to specify the predicates involving the attributes of
the relation appearing in the FROM clause.
ORDER BY The order by clause is used to ordered the result of a query either in
Ascending (ASC) or in Descending (DESC) order.
Int – Ordinal position of the column in the result table.
If there is more than one specification, then the left – to – right specification corresponds to
major – to – minor ordering.
e.g., SELECT Name FROM Employee.
COMPUTER EDUCATION DIVISION 9
ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414
SELECT DISTINCT Name FROM Employee.
SELECT * FROM Employee WHERE Name = “Shyam”
Note:
To retrieve all the field/ column of the relation, we can write all the column name separated
by comma ( , ) or simply putting an asterisk ( * ) as shown in the example.
CONDITION SPECIFICATION
SQL supports the following Boolean and comparison operators :
Boolean Operator
NOT
AND
OR
Comparison Operator
= Equal to
< > Not equal to
> Greater then
< Less then
> = Greater then or equal to
< = Less then or equal to
These operators allows the formulation of more complex predicates, which are attached to
the SELECT statement by the WHERE clause. NOT has highest priority. OR has lowest
priority.
SQL Tutorial
amit@abroandsis.com, amit_abros@yahoo.com
ARITHMETIC & AGGREGATE OPERATORS
SQL provides a full component of arithmetic operators and functions. This includes
functions to find the Average, Sum, Maximum, Minimum, and To count the number of
occurrences. All these functions are used with Select statement.
COUNT
This function must be used either with the DISTINCT option of the SELECT statement or
as COUNT( * ). When used with the DISTINCT option, it COUNTS the number of distinct
values in the column. If the total number of rows in the relation is to be determined,
COUNT ( * ) must be used.
e.g., SELECT COUNT ( * ) FROM Menu ;
SELECT COUNT ( DISTINCT Pay_rate ) FROM Employee ;
AVG
The operand of this function must have a numeric value. It finds the average of these values.
If the DISTINCT option is specified, the duplicate values are not used for computing the
average.
e.g., SELECT AVG( Pay_rate) FROM Employee ;
SELECT AVG( Pay_rate ) FROM Employee WHERE Skill = “Chef” ;
SUM
The operand of this function must have a numeric value. It finds the sum of these values. If
the DISTINCT option is specified, the duplicate values are ignored in computing the result.
e.g., SELECT SUM( Price) FROM Menu ;
MIN
This function finds the minimum of the values in the column. The DISTINCT option has no
effect on this function.
e.g., SELECT MIN( Price) FROM Menu ;
COMPUTER EDUCATION DIVISION 11
ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414
MAX
This function finds the maximum of the values in the column. The DISTINCT option has no
effect on this function.
e.g., SELECT MAX( Price) FROM Menu ;
Note :
(i) If the function is followed by the word DISTINCT then unique values are used.
(ii) If ALL follows the function then all the values are used for evaluating the
function. ALL is the default.
(iii) COUNT ( * ) has a special meaning in that it counts the number of rows of a
relation.
Arithmetic Operator
+ For Addition
- for Subtraction
* for Multiplication
/ for Division.
SET MANIPULATION Operator
ANY
The operator ANY allows the testing of a value against a set of values. The comparisons
can be on of { <, >, < =, > = , = , < > } and are specified in SQL as the operators, < ANY,
> ANY, < = ANY, > = ANY, = ANY, < > ANY. We refer to any one of these operators
by the notation < operator > ANY.
In general, the condition
C < operator > ANY (SELECT X FROM …. )
evaluates to true if and only if the comparison “ C < operator > ANY {at least one or more
from the result of the select X FROM … }” is true.
SQL Tutorial
amit@abroandsis.com, amit_abros@yahoo.com
Syntax :
… … < operator > ANY ( SELECT …….. ).
e.g., Get employees who are working either on the date 19860419 or 19860420.
SELECT Emp_no FROM Duty_allocation WHERE Day = ANY ( SELECT Day
FROM Duty_allocation WHERE Day = 19860419 OR Day = 19860420) ;
IN
The operator IN is equivalent to “ = ANY ” operator. It tests for the membership of a value
within a set. i.e., a single value within a set of values.
e.g., Get employees who are working either on the date 19860419 or 19860420.
SELECT Emp_no FROM Duty_allocation WHERE Day IN (19860419, 19860420)
CONTAINS
The operator CONTAINS is used to test for the containment of one set in another.
e.g., Find the names of employees who are assigned to all positions that require a chef’s
skill.
SELECT e.Name FROM Employee e WHERE (SELECT Posting_no FROM
Duty_allocation d WHERE e.Emp_no = d.Emp_no) CONTAINS ( SELECT
p.Posting_no FROM Position p WHERE p.skill = “Chef”) ;
ALL
The set operator ALL is used in general, to show that the condition :
C < operator > ALL (SELECT X FROM …. )
Evaluates to true. This is so, if and only if the comparison C < operator > ALL the values
from the result of (SELECT X FROM …… )” is true.
e.g., Find the employees with the lowest pay rate.
COMPUTER EDUCATION DIVISION 13
ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414
SELECT Emp_no, Name, Pay_rate FROM Employee WHERE Pay_rate < =
ALL (SELECT Pay_rate FROM Employee WHERE Skill = “Chef”);
NOT IN
The set operator NOT IN is equivalent to < > ALL.
e.g., Find the names and rate of pay of all employees who are NOT allocated a duty.
SELECT Name, Pay_rate FROM Employee WHERE Emp_no NOT IN (SELECT
Emp_no FROM Duty_allocation ) ;
NOT CONTAINS
The set operator NOT CONTAINS, the complement of CONTAINS is true if one set of
values is not a superset of another set of values.
EXISTS
The set operator EXISTS is the SQL version of the existential quantifier. The expression :
EXISTS ( SELECT X FROM …. )
Evaluates to true if and only if the result of “SELECT X FROM …..” is not empty.
e.g., Find the names and rate of pay of all employees who are allocated a duty.
SELECT Name, Pay_rate FROM Employee WHERE EXISTS (SELECT *
FROM Duty_allocation WHERE Employee.Emp_no = Duty_allocation.Emp_no) ;
NOT EXISTS
The set operator NOT EXISTS is the complement form of EXISTS. The expression :
NOT EXISTS ( SELECT X FROM …. )
evaluates to true if and only if the result of “SELECT X FROM …..” is empty.
e.g., Find the names and rate of pay of all employees who are NOT allocated a duty.
SQL Tutorial
amit@abroandsis.com, amit_abros@yahoo.com
SELECT Name, Pay_rate FROM Employee WHERE NOT EXISTS (SELECT *
FROM Duty_allocation WHERE Employee.Emp_no = Duty_allocation.Emp_no) ;
UNION
UNION is similar to the traditional set theory Union operator. Duplicates are removed from
the result of a union.
e.g., Get employees who are waiters or worker at Posting_no = 321.
( SELECT Emp_no FROM Employee WHERE Skill = “Waiter” ) UNION
( SELECT Emp_no FROM Duty_allocation WHERE Posting_no = 321) ;
MINUS
The traditional set theory difference operator is MINUS.
e.g., Get a list of employees not assigned a duty.
( SELECT Emp_no FROM Employee ) MINUS ( SELECT Emp_no FROM
Duty_allocation);
INTERSECT
The traditional set theory set intersection operator is INTERSECT.
e.g., Get a list of names of employees with the skill of “chef” who are assigned a duty.
SELECT Name FROM Employee WHERE Emp_no IN (( SELECT Emp_no
FROM Employee WHERE Skill = “Chef”) INTERSECT (SELECT Emp_no
FROM Duty_allocation)) ;
BETWEEN Predicate
The use of BETWEEN gibes the range within the values must lie. If the value should lie
outside a range then BETWEEN is to be preceded by NOT.
e.g., SELECT * FROM Menu WHERE Price BETWEEN 5 AND 15 ;
SELECT * FROM Menu WHERE Price NOT BETWEEN 5 AND 15 ;
COMPUTER EDUCATION DIVISION 15
ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414
LIKE Predicate
LIKE predicate is used for pattern matching. A column of type char can be compared with a
string constant. The use of the word LIKE doesn’t look for exact match but a form of wild
string match. A % or - or * can appear in the string constant.
Where,
% stands for a sequence of n characters (n > = 0 ).
- stands for a single character.
* stands for a sequence of n characters (n > = 0 ).
TEST FOR NULL
To test an attribute for the presence or absence of null.
Syntax :
Col. Ref IS [ NOT ] NULL.
e.g., SELECT * FROM Order WHERE Qty IS NULL ;
SELECT * FROM Order WHERE Qty IS NOT NULL ;
GROUP BY Feature
This feature allows one to partition the result into a number of groups such that all rows of
the group have the same value in some specified column. i.e., it allow data to be classified
into categories.
Whenever, GROUP BY is used then the phrase WHERE is to be replaced by HAVING.
The meaning of HAVING is the same as WHERE except that the condition is now
applicable to each group.
e.g.,
(i) Get a count of different employees on each shift.
SELECT Shift, COUNT (DISTINCT Emp_no) from Duty_allocation GROUP BY Shift.
SQL Tutorial
amit@abroandsis.com, amit_abros@yahoo.com
(ii) Get employee numbers of all employees working on at least two dates.
SELECT Emp_no FROM Duty_allocation GROUP BY Emp_no HAVING
COUNT( * ) > 1.
MULTIPLE TABLES QUERY
Syntax :
SELECT T1.s11, …, T1.a1n, …, T2.a21, …, T2.a2m [, … ] FROM T1, T2, [, T3, …]
WHERE T1.a1j = T2.a2k …. ;
Where,
T1, T2, …. are different relations/ tables.
a11, a12, ….. a1n, a21, a22, … a2m, …. are fields / columns/ attributes of table T1,
T2 respectively.
e.g., SELECT e1.Name, e1.Pay_rate FROM Employee e1, employee e2 WHERE
e1.Pay_rate > e2.Pay_rate AND e2.Name = “Ram” ;
COMPUTER EDUCATION DIVISION 17
ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414
Practical – 1
Consider the relation/ table given below :
Item_List (Item_code numeric 4 , Item string 15, Rate numeric 6)
Orders (Bill numeric 3, Item_Code numeric 4, Piece numeric 3)
Cash_Memo (Bill numeric 3, Counter_No numeric 1, Emp_name string 20, Dates,
Amount numeric 6)
Now, Write the SQL statements for the following :
1. Display the item, rate for item code = 80.
2. List the item code, item, rate from item list where rate is greater than 20.
3. Display the details from item list where item code is less than 40 and rate is greater
than 20.
4. Display the Item code and Rate of “Burger”.
5. Find the item list whose cost is Rs 10.00.
6. Display the item code from orders for Bill = 804.
7. List the details of items for bill = 804.
8. Get the item list whose cost is BETWEEN 10 to 25.
9. Get the item list sorted on rate.
10. Get the item details whose name starts with “T”.
11. Get the item details whose rate is minimum.
12. Display the details of cash memo for “Rama Swami”.
13. List the detail of greatest bill amount.
14. Display the minimum bill amount.
15. Get the average bill amount.
16. Get the second greatest amount of the bill.
17. Get the lowest and highest bill amount.
SQL Tutorial
amit@abroandsis.com, amit_abros@yahoo.com
18. Get the second lowest and highest amount.
19. Get the item list whose rate is lowest or highest.
20. Display the total number of items sold.
21. Display the item wise pieces sold.
22. List the counter wise Sales amount.
23. List the detail of cash memo ordered by counter no.
24. Get the bill list in descending order by amount.
25. Get the detail of item list in descending order of their item.
26. Display the details of bill amount day wise.
27. Get the number of “Burger” sold.
28. Display the item code and number of pieces sold.
29. Select the counter wise sales amount.
30. Get the details of item sold on 28th
January 2006.
31. Get the details of item list sold on 20th
and 30th
January.
32. Get the item detail sold by “Rama swami”.
33. Get the details of item sold by “Hina” and number of pieces sold.
34. Count the number of staff working of the restaurant.
35. Get the item detail which is not sold till now.
36. Get the items detail sold in maximum quantity.
37. Get the name of the employee who sold “Ice Cone”.
38. Get the name of the employee who sold either “Samosa” or “Milk Cake”.
39. Get the name of the employee who sold “Tea” and “Milk Cake”.
40. Get the detail of item list which is sold either on 12th
or 20th
January.
41. Get the details of Billed amount which is greater than average Billed amount.
COMPUTER EDUCATION DIVISION 19
ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414
Solution :
To solve these queries, first you are required to create all the five tables. Then read all the
question carefully. Now enter data according to the question.
Item_List
Item_Code Item Rate
-------------------- ------------ ----------------
10 Samosa 5.00
20 Milk Cake 50.00
30 Chola Bhatora 10.00
40 Burger 20.00
50 Tikki 10.00
60 Tea 5.00
70 Cold Drink 15.00
80 Ice Cone 25.00
Cash_Memo
Bill Counter_No Emo_Name Dates Amount
--------------- ------------------ -------------------- -------------------- --------------
801 2 Ram Saran 20060112 150.00
802 3 Rama Swami 20060115 120.00
803 4 Mohan 20060118 240.00
804 1 Tina 20060119 40.00
805 3 Rama Swami 20060120 320.00
806 2 Ram Saran 20060120 120.00
807 1 Hina 20060120 40.00
808 1 Hina 20060128 10.00
809 2 Rama Swami 20060128 30.00
810 1 Tina 20060130 10.00
Now write the SQL Statement. You can get help from the solution given below.
Orders
Bill Item_Code Piece
-------------------- ---------- ----------------
801 30 5
802 10 12
803 40 6
804 20 2
805 80 4
806 40 3
807 40 2
808 50 1
809 30 3
810 60 2
SQL Tutorial
amit@abroandsis.com, amit_abros@yahoo.com
1. SELECT item, rate FROM item_list WHERE item_code = 80
2. SELECT * FROM item_list WHERE rate > 20
3. SELECT * FROM item_list WHERE item_code < 40
AND rate > 20
4. SELECT item_code, rate FROM item_list WHERE item
="Burger"
5. SELECT item FROM item_list WHERE rate = 10
6. SELECT item_code FROM orders WHERE bill = 804
7. SELECT * FROM item_list WHERE item_code IN
(SELECT item_code FROM orders WHERE bill = 804)
Or,
SELECT i.item_code, item, rate, piece, bill
FROM item_list i, orders o
WHERE i.item_code = o.item_code AND o.bill= 804
8. SELECT * FROM item_list WHERE rate BETWEEN 10 AND 20
Or,
SELECT * FROM item_list WHERE rate <= 20 AND rate >= 10
COMPUTER EDUCATION DIVISION 21
ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414
9. SELECT * FROM item_list ORDER BY rate
10. SELECT * FROM item_list WHERE item LIKE "t%"
11. SELECT * FROM item_list WHERE rate IN (SELECT
MIN(rate) FROM item_list )
Or,
SELECT * FROM item_list WHERE rate = (SELECT
MIN(rate) FROM item_list )
12. SELECT * FROM cash_memo WHERE emp_name = "Rama
Swami"
13. SELECT * FROM cash_memo WHERE amount IN (SELECT
MAX(amount) FROM cash_memo )
14. SELECT MIN(amount) "minimum bill amount" FROM cash_memo
15. SELECT AVG(amount) "average bill amount" FROM cash_memo
16. SELECT MAX(amount) FROM cash_memo WHERE amount
NOT IN (SELECT MAX(amount) FROM cash_memo)
SQL Tutorial
amit@abroandsis.com, amit_abros@yahoo.com
17. SELECT MIN(amount) "Minimum Bill Amount", MAX(amount)
"Maximum Bill Amount" FROM cash_memo
18. SELECT MAX(amount), MIN(amount) FROM cash_memo
WHERE amount NOT IN
((SELECT MAX(amount) FROM cash_memo)
UNION (SELECT MIN(amount) FROM cash_memo))
19. SELECT * FROM item_list WHERE rate IN
((SELECT MIN(rate) FROM item_list)
UNION (SELECT MAX(rate) FROM item_list))
20. SELECT SUM(piece) Total_no_of_item_sold FROM orders
21. SELECT item_code, SUM(piece) "Total piece sold"
FROM orders GROUP BY item_code
22. SELECT Counter_No , SUM(amount) sale_amount
FROM cash_memo GROUP BY Counter_No
23. SELECT * FROM cash_memo ORDER BY Counter_No
24. SELECT * FROM cash_memo ORDER BY amount DESC
COMPUTER EDUCATION DIVISION 23
ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414
25. SELECT * FROM item_list ORDER BY item DESC
26. SELECT * FROM cash_memo ORDER BY dates
27. SELECT SUM(piece) FROM orders WHERE item_code =
(SELECT item_code FROM item_list
WHERE item = "burger")
28. SELECT item_code, SUM(piece) FROM orders
GROUP BY item_code
29. SELECT Counter_No , SUM(amount) FROM cash_memo
GROUP BY Counter_No
30. SELECT * FROM item_list WHERE item_code =
(SELECT item_code FROM orders WHERE bill =
(SELECT bill FROM cash_memo
WHERE dates = 20060128))
31. SELECT * FROM item_list WHERE item_code IN
(SELECT item_code FROM orders WHERE bill IN
(SELECT bill FROM cash_memo
WHERE dates = 20060120 OR dates = 20060130))
SQL Tutorial
amit@abroandsis.com, amit_abros@yahoo.com
32. SELECT * FROM item_list WHERE item_code IN
(SELECT item_code FROM orders WHERE bill IN
(SELECT bill FROM cash_memo
WHERE emp_name = "rama swami"))
33. SELECT * FROM item_list WHERE item_code IN
(SELECT item_code FROM orders WHERE bill IN
(SELECT bill FROM cash_memo
WHERE emp_name = "hina"))
34. SELECT COUNT(emp_name) "No of employee" FROM
cash_memo
Or,
SELECT COUNT(*) "No of employee" FROM cash_memo
35. SELECT * FROM item_list WHERE item_code
NOT IN (SELECT item_code FROM orders)
36. SELECT * FROM item_list WHERE item_code IN
(SELECT item_code FROM orders WHERE piece IN
(SELECT MAX(piece) FROM orders))
COMPUTER EDUCATION DIVISION 25
ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414
37. SELECT emp_name FROM cash_memo WHERE bill IN
(SELECT bill FROM orders WHERE item_code IN
(SELECT item_code FROM item_list
WHERE item = "ice cone"))
38. SELECT emp_name FROM cash_memo WHERE bill IN
(SELECT bill FROM orders WHERE item_code IN
(SELECT item_code FROM item_list
WHERE item = "samosa" OR item = "milk cake"))
39. SELECT emp_name FROM cash_memo WHERE bill IN
(SELECT bill FROM orders WHERE item_code IN
(SELECT item_code FROM item_list
WHERE item = "tea" OR item = "milk cake"))
40. SELECT * FROM item_list WHERE item_code IN
(SELECT item_code FROM orders WHERE bill IN
(SELECT bill FROM cash_memo
WHERE dates = 20060112 OR dates = 20060120))
41. SELECT * FROM cash_memo WHERE amount >
(SELECT AVG(amount) FROM cash_memo)
SQL Tutorial
amit@abroandsis.com, amit_abros@yahoo.com
Practical – 2
Consider the relation/ table given below :
Sailors (Sailor_Id string 4, Sailor_Name string 20, Rating numeric 1, Age numeric 2)
Boats (Boat_Id string 4, Boat_Name string 20, Colour string 15)
Reserves (Sailor_Id string 4, Boat_Id string 4, Days string 8)
Now, Write the SQL statements for the following :
1. Display the list of details of sailors whose rating 1.
2. Display the list of details of sailors whose rating is 5 or 2.
3. Display the detail of sailor whose age is less than 30 and greater than 25.
4. List the details of sailors whose age is less than 25 or greater than 30.
5. List the sailors detail whose name starts with “R”.
6. Select the list of sailor who is engaged in 1st
January.
7. Get the detail of sailors who is engaged on 2nd
January.
8. List the sailor id who has no any reserve date.
9. List the details of boat which is not reserved for a single time (till now).
10. Get the list of reserved date for sailor id S001.
11. Get the boat name for all the yellow and white colored boat.
12. Select the list of all different boat name.
13. Display all the distinct colour of boat.
14. Get the total number of boat available.
15. Get the name of boat and number of boat with same name.
Or, Get the distinct boat name and their number.
16. Display the list of sailor and number of days they works.
17. Get the distinct boat detail which is in use.
18. What are the different rating available.
19. Display the distinct boat name available.
COMPUTER EDUCATION DIVISION 27
ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414
20. List the dates at which more than one boat is booked.
21. Get the detail of sailors whose age is greater than 32.
22. List the name of boat whose colour is Red.
23. Get the sailors name whose name starts with “N”.
24. Select the detail of sailors whose name ends with “m”.
25. Get the detail of boat and sailors who worked on 1st
January 2006.
26. Get the detail of sailor whose rating is 1 and age is maximum.
27. Get the details of sailor who has worked at 20060126.
28. Get the number of records in sailors table.
29. Get the detail of boat which is reserved between 10-15 January 2006.
30. Get the details of boat which reserved between 10 -15 January 2006 excluding 10
and 15 .
31. Select the sailor who is working on any of the date BETWEEN 20 to 24.
32. Select the sailor who has worked on 22 and 25 January 2006.
33. Get the boat which is used more than 2 times (having count > 2).
34. Get the detail of sailors who had operated boat id “B009”.
35. Get the detail of sailors who had operated “Kala Ghora”.
36. Get the number of distinct boat in use.
37. Get the details of boat which is not in use.
38. Get the dates on which more than two boats are reserved and their number.
39. Get the average age of the sailor.
40. Get the sailor list who worked on either 20 or 25 January 2006 (but not on the both
the date).
41. Get the sailors id who has operated same boat two times (more than once).
42. Get the sailors detail who has operated same boat two times.
Solution :
To solve these queries, first you are required to create all the five tables. Then read all the
question carefully. Now enter data according to the question.
SQL Tutorial
amit@abroandsis.com, amit_abros@yahoo.com
Boats
Boat_Id Boat_Name Colour
-------------------- ---------- ---------------------------
B001 Pawan Hansh White
B002 Kala Ghora Black
B003 Kala Ghora Black
B004 Pushpak Bluess Green
B005 Pushpak Dark Green
B006 Tytanic Pink
B007 Aatmrath Yellow
B008 Aatmrath Brown
B009 Kala Ghora Dark Blue
B010 Pushpak Green
B011 Kohinoor Red
B012 Pawan Hansh White
B013 Pawan Hansh White
Reserves
Sailor_Id Boat_Id Days
-------------------- ----------- ---------------
S001 B002 20060101
S002 B001 20060101
S001 B003 20060102
S003 B004 20060103
S005 B005 20060103
S006 B008 20060104
S007 B006 20060102
S008 B007 20060102
S009 B010 20060102
S010 B011 20060102
S010 B012 20060106
S002 B013 20060107
S003 B005 20060107
S005 B004 20060108
S007 B005 20060109
S009 B007 20060110
S008 B001 20060112
S002 B005 20060115
S005 B002 20060120
S006 B003 20060120
S001 B002 20060122
S001 B008 20060125
S005 B008 20060126
S010 B010 20060127
Sailors
Sailor_Id Sailor_Name Rating Age
-------------------- --------------------------------- ---
S001 Ram Kumar 1 30
S002 Radhe Shyam 2 20
S003 Parimal 3 28
S004 Pyare Mohan 2 28
S005 Shyam Sundar 1 26
S006 Suresh 1 25
S007 Ajit Singh 3 23
S008 Narayan 1 32
S009 Sita Ram 2 35
S010 Shiv 5 30
COMPUTER EDUCATION DIVISION 29
ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414
1. SELECT * FROM sailors WHERE rating = 1
2. SELECT * FROM sailors WHERE rating = 2 OR rating = 5
3. SELECT * FROM sailors WHERE age < 30 AND age > 25
4. SELECT * FROM sailors WHERE age < 25 OR age > 30
5. SELECT * FROM sailors WHERE Sailor_Name like "r%"
6. SELECT * FROM sailors WHERE sailor_id = ANY (SELECT
sailor_id FROM reserves WHERE days = 20060101)
7. SELECT * FROM sailors WHERE sailor_id NOT IN (SELECT
sailor_id FROM reserves WHERE days = 20060102)
8. SELECT sailor_id FROM sailors WHERE sailor_id NOT IN
(SELECT sailor_id FROM reserves WHERE days
BETWEEN 20060101 AND 20060130)
9. SELECT * FROM boats WHERE boat_id not IN ( SELECT
DISTINCT boat_id FROM reserves )
SQL Tutorial
amit@abroandsis.com, amit_abros@yahoo.com
10. SELECT * FROM reserves WHERE sailor_id = "S001"
11. SELECT boat_name FROM boats WHERE colour = "white"
OR colour = "yellow"
12. SELECT DISTINCT boat_name FROM boats
13. SELECT DISTINCT colour FROM boats
14. SELECT COUNT(boat_name) FROM boats
15. SELECT boat_name, COUNT(*) FROM boats GROUP BY
boat_name
16. SELECT sailor_id, COUNT(*) FROM reserves GROUP BY
sailor_id
17. SELECT * FROM boats WHERE boat_id = ANY (SELECT
DISTINCT boat_id FROM reserves)
18. SELECT DISTINCT rating FROM sailors
19. SELECT DISTINCT boat_name FROM boats
COMPUTER EDUCATION DIVISION 31
ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414
20. SELECT days FROM reserves GROUP BY days
HAVING COUNT (*) > 1
21. SELECT * FROM sailors WHERE age > 32
22. SELECT boat_name FROM boats WHERE colour = "red"
23. SELECT sailor_name FROM sailors WHERE sailor_name
LIKE "n%"
24. SELECT * FROM sailors WHERE sailor_name LIKE "%m"
25. SELECT s.sailor_name, s.sailor_id, s.rating, s.age,
b.boat_name, b.boat_id, b.colour
FROM sailors s, boats b, reserves r
WHERE s.sailor_id = r.sailor_id
AND b.boat_id = r.boat_id
AND days = 20060101
SQL Tutorial
amit@abroandsis.com, amit_abros@yahoo.com
26. SELECT * FROM sailors WHERE age IN
(SELECT MAX(age) FROM sailors WHERE rating = 1)
27. SELECT * FROM sailors WHERE sailor_id IN
( SELECT sailor_id FROM reserves WHERE
days = 20060126)
28. SELECT count(*) "No. of records" FROM sailors
29. SELECT * FROM boats WHERE boat_id IN
(SELECT boat_id FROM reserves WHERE days
BETWEEN 20060110 AND 20060115)
Or,
SELECT * FROM boats WHERE boat_id IN
(SELECT boat_id FROM reserves
WHERE days >= 20060110 AND days <= 20060115)
30. SELECT * FROM boats WHERE boat_id IN
(SELECT boat_id FROM reserves
WHERE days > 20060110 AND days < 20060115)
31. SELECT * FROM sailors WHERE sailor_id IN
(SELECT sailor_id FROM reserves
WHERE days >= 20060120 AND days <= 20060124)
COMPUTER EDUCATION DIVISION 33
ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414
32. SELECT * FROM sailors WHERE sailor_id IN
(SELECT sailor_id FROM reserves
WHERE days = 20060122 OR days = 20060125
AND sailor_id = sailor_id)
33. SELECT boat_id, COUNT(*) FROM reserves
GROUP BY boat_id HAVING COUNT(*) > 2
34. SELECT * FROM sailors WHERE sailor_id = ANY (SELECT
sailor_id FROM reserves WHERE boat_id = "B009")
35. SELECT * FROM sailors WHERE sailor_id IN
(SELECT sailor_id FROM reserves WHERE boat_id IN
(SELECT boat_id FROM boats WHERE boat_name =
"kala ghora"))
36. SELECT COUNT(DISTINCT(boat_id)) FROM reserves
37. SELECT * FROM boats WHERE boat_id NOT IN
(SELECT DISTINCT boat_id FROM reserves)
SQL Tutorial
amit@abroandsis.com, amit_abros@yahoo.com
38. SELECT days, COUNT(*) FROM reserves GROUP BY days
HAVING COUNT (*) > 2
39. SELECT AVG(age) "Average age" FROM sailors
40. SELECT * FROM sailors WHERE sailor_id IN
(SELECT sailor_id FROM reserves
WHERE days = 20060120 OR days = 20060125
AND sailor_id < > sailor_id)
41. SELECT DISTINCT r1.sailor_id FROM reserves r1,
reserves r2 WHERE r1.boat_id = r2.boat_id
AND r1.sailor_id = r2.sailor_id
AND r1.days < > r2.days
42. SELECT * FROM sailors WHERE sailor_id IN
(SELECT DISTINCT r1.sailor_id FROM reserves r1,
reserves r2 WHERE r1.boat_id = r2.boat_id
AND r1.sailor_id = r2.sailor_id
AND r1.days <> r2.days)
COMPUTER EDUCATION DIVISION 35
ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414
Practical – 3
Consider the schema/ table given below :
Branch_scheme (Branch_name, asset, Branch_city)
Customer_scheme (Customer_name, street, customer_city)
Deposit_scheme (Branch_name, account_number, customer_name, balance)
Borrow_scheme (Branch_name, loan_number, customer_name, amount)
Client_scheme (Customer_name, banker_name)
Now, Write the SQL statements for the following :
1. Find the name and balance of customer living at “Gomti Street”.
2. Find the name of banker whose customer is living at “Mumbai”.
3. Find the complete detail of account holder 123.
4. Find the branch, which is situated at the same city.
5. Find the customer name who is borrower and depositor.
6. Get the customer detail who is not a borrower.
7. Get the branch detail of all the customer who is either borrower or depositor.
8. Get the total amount borrowed by the customer.
9. Get the average amount borrowed by the customer.
10. Find the branch detail who borrow largest amount.
11. Display the customer address who has least balance.
12. List the detail of depositor according to account number.
13. Find the customer detail who has second greatest balance.
14. Find the customer detail who is borrower but not the depositor.
15. Find the total amount owned by “Asraf ali”.
16. Find the total amount borrowed by the customer.
17. Display the customer and branch whose city is same.
18. Find the banker whose customer is living at “Kolkata”.
19. Find the customer detail whose street or city begins with “J”.
20. Find the branch detail whose city end with “r”.
21. Find the assets which contain “ut” in their name.
SQL Tutorial
amit@abroandsis.com, amit_abros@yahoo.com
22. Find the number of records in customer table.
23. Find the customer detail whose loan number is 13.
24. Find the customer detail whose account number is less than 122 with balance greater
than 1100 along with account number and balance amount.
25. Find the depositors details whose Assets is “auto”.
26. Find the depositors detail who has highest deposit.
27. Find the banker whose customer borrow 1200.
28. Find the banker who has only depositor.
29. Find the branch which is in the same city where “Bhagat singh” liver.
30. Find the customer who living in the same city.
31. Find the branch details where assets is “Camera” and branch name = “Dwaraka”.
32. Find the customer name who lives in same city.
33. Display the detail of account number 121.
34. Find the customer detail as well as branch detail of loan number 13.
35. Find the branch where borrow is greater than deposit.
36. Find the Banker city from where banker works.
37. Find the amount owned by “Shaktiman”.
38. Find the detail of Depositor of minimum amount.
39. Find the name of minimum and maximum amount borrower.
40. Find the depositors detail who deposit amount greater than the average amount.
41. Find the depositors detail who deposits less than the average borrowed amount.
42. Find the customer detail whose loan number is less than 20 and greater than 13.
43. List the bankers in descending order.
44. Find the different branch city where more than one branch.
45. Find all customers who have a balance of over Rs. 1000.
46. Write the query to find the clients of banker Patel, and the city they live in.
47. Write a statement to find all the customers who have a loan amount of more than Rs.
1200.
48. Write a statement to find all the customers whose name starts with “R” and who have a
balance of more than Rs. 10,000.
COMPUTER EDUCATION DIVISION 37
ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414
Solution :
To solve these queries, first you are required to create all the five tables. Then read all the
question carefully. Now enter data according to the question.
Branch_sechme
Branch_Name Asset Branch_City
-------------------- -------------------------- -----------
Indraprasth Computer Delhi
Maharastra Refrigerator Pune
Dwaraka Camera Delhi
Pink City Auto Jaipur
Golden Temple Truck Amritsar
Ganga Books Allahabad
Patliputra Furnitures Patna
Customer_Scheme
Customer_Name Street Customer_City
-------------------- ---------- -------------------------------
Parimal Tripathi Monarch Mumbai
Pyare Mohan Tulsi Chennai
Kumar Ranjan Konark Kolkata
Shaktiman Frejar Patna
Asraf Ali Rajpath Delhi
Bhagat Singh Swarna Amritsar
Vishawas Joker Banglore
Akbar Gomti Allahabad
Sher Singh Mansarovar Jaipur
Parimal Puskar Jaipur
SQL Tutorial
amit@abroandsis.com, amit_abros@yahoo.com
Deposit_scheme
Branch_Name Account_No Customer_Name Balance
-------------------- ----------- -------------------- --------------------
Pink City 123 Parimal 1000
Dwaraka 120 Asraf Ali 1200
Patliputra 122 Shaktiman 2000
Ganga 121 Akbar 1100
Borrow_scheme
Branch_Name Loan_Number Customer_Name Amount
-------------------- ----------- ------------- --------------------------
Indraprasth 12 Asraf Ali 1200
Pink City 14 Sher Singh 2000
Patliputra 13 Shaktiman 1300
Client_scheme
Customer_Name Banker_Name
-------------------- -------------------------
Parimal Tripathi Rama
Pyare Mohan Sita
Kumar Ranjan Radhe
Vishawas Narayana
Asraf Ali Sangam
Akbar Patel
Sher Singh Ram
Shaktiman Ram
Parimal Rama
Now write the SQL Statement. You can get help from the solution given below.
COMPUTER EDUCATION DIVISION 39
ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414
1. SELECT customer_name, balance FROM deposit_scheme WHERE
customer_name IN (SELECT customer_name FROM
customer_scheme WHERE street = "gomti");
2. SELECT banker_name FROM client_scheme WHERE
customer_name IN (SELECT customer_name FROM
customer_scheme WHERE customer_city = "mumbai");
3. SELECT * FROM customer_scheme WHERE customer_name IN
(SELECT customer_name FROM deposit_scheme WHERE
account_no = 123 );
4. SELECT b1.branch_name FROM branch_scheme b1,
branch_scheme b2 WHERE b1.branch_city = b2.branch_city
AND b1.branch_name < > b2.branch_name ;
5. SELECT customer_name FROM borrow_scheme WHERE
customer_name IN (SELECT customer_name FROM
deposit_scheme);
6. SELECT * FROM customer_scheme WHERE customer_name
NOT IN (SELECT customer_name FROM borrow_scheme);
7. SELECT * FROM branch_scheme WHERE branch_name
IN ((SELECT branch_name FROM borrow_scheme )
UNION (SELECT branch_name FROM deposit_scheme));
SQL Tutorial
amit@abroandsis.com, amit_abros@yahoo.com
8. SELECT SUM(amount) total_borrowed_amount FROM
borrow_scheme;
9. SELECT AVG(amount) average_borrowed_amount FROM
borrow_scheme;
10. SELECT * FROM branch_scheme WHERE branch_name IN
(SELECT branch_name FROM borrow_scheme WHERE amount =
(SELECT MAX(amount) FROM borrow_scheme));
11. SELECT * FROM customer_scheme WHERE customer_name IN
(SELECT customer_name FROM deposit_scheme WHERE balance
= (SELECT MIN(balance) FROM deposit_scheme));
12. SELECT * FROM deposit_scheme ORDER BY account_no;
13. SELECT * FROM customer_scheme WHERE customer_name IN
(SELECT customer_name FROM deposit_scheme WHERE balance
IN (SELECT MAX(balance) FROM deposit_scheme WHERE
balance NOT IN
(SELECT MAX(balance) FROM deposit_scheme)));
14. SELECT * FROM customer_scheme WHERE customer_name IN
(SELECT customer_name FROM borrow_scheme WHERE
customer_name NOT IN (SELECT customer_name FROM
deposit_scheme));
COMPUTER EDUCATION DIVISION 41
ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414
15. SELECT (d.balance - b.amount) total_amount FROM
borrow_scheme b, deposit_scheme d WHERE d.customer_name
= "asraf ali" AND b.customer_name = d.customer_name ;
16. SELECT SUM(amount) FROM borrow_scheme ;
17. SELECT c.customer_name, b.branch_name, c.customer_city
FROM customer_scheme c, branch_scheme b WHERE
b.branch_city = c.customer_city ;
18. SELECT banker_name FROM client_scheme WHERE
customer_name IN (SELECT customer_name FROM
customer_scheme WHERE customer_city = "kolkata");
19. SELECT * FROM customer_scheme WHERE street like "j%" OR
customer_city like "j%" ;
20. SELECT * FROM branch_scheme WHERE branch_city like "%r" ;
21. SELECT asset FROM branch_scheme WHERE asset like "%ut%" ;
22. SELECT COUNT(*) FROM customer_scheme ;
Or,
SELECT COUNT(*) total_no_of_records FROM customer_scheme;
SQL Tutorial
amit@abroandsis.com, amit_abros@yahoo.com
23. SELECT * FROM customer_scheme WHERE customer_name IN
(SELECT customer_name FROM borrow_scheme WHERE
loan_number = 13) ;
24. SELECT c.customer_name, c.street, c.customer_city,
d.balance, d.account_no FROM customer_scheme c,
deposit_scheme d WHERE d.balance > 1100 AND
d.account_no < 122 AND
c.customer_name = d.customer_name ;
Or,
SELECT * FROM customer_scheme WHERE customer_name IN
(SELECT customer_name FROM deposit_scheme WHERE
account_no < 122 AND balance > 1100) ;
25. SELECT * FROM deposit_scheme WHERE branch_name IN
(SELECT branch_name FROM branch_scheme WHERE
asset = "auto");
26. SELECT * FROM deposit_scheme WHERE balance IN
(SELECT MAX(balance) FROM deposit_scheme ) ;
27. SELECT banker_name FROM client_scheme WHERE
customer_name IN (SELECT customer_name FROM
borrow_scheme WHERE amount = 1200);
COMPUTER EDUCATION DIVISION 43
ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414
28. SELECT DISTINCT c.customer_name, c.banker_name FROM
borrow_scheme b, deposit_scheme d, client_scheme c
WHERE b.customer_name < > d.customer_name AND
d.customer_name = c.customer_name ;
Or,
SELECT distinct c.customer_name, c.banker_name FROM
borrow_scheme b, deposit_scheme d, client_scheme c
WHERE b.customer_name < > d.customer_name AND
d.customer_name = c.customer_name ;
29. SELECT branch_name FROM branch_scheme WHERE branch_city =
(SELECT customer_city FROM customer_scheme WHERE
customer_name = "bhagat singh") ;
30. SELECT c1.customer_name FROM customer_scheme c1,
customer_scheme c2 WHERE c1.customer_city =
c2.customer_city AND c1.customer_name < >
c2.customer_name;
31. SELECT Branch_name, Asset, Branch_City FROM
Branch_scheme WHERE assets = “Camera” AND
Branch_name = “Dwaraka”.
32. SELECT c1.customer_name FROM customer_scheme c1,
customer_scheme c2 WHERE c1.customer_city =
c2.customer_city AND c1.customer_name < >
c2.customer_name ;
SQL Tutorial
amit@abroandsis.com, amit_abros@yahoo.com
33. SELECT * FROM deposit_scheme WHERE account_no = 121 ;
34. SELECT c.customer_name, c.street, c.customer_city,
b.branch_name, b.asset FROM customer_scheme c,
branch_scheme b, borrow_scheme bo WHERE
bo.loan_number = 13 AND c.customer_name =
bo.customer_name AND b.branch_name = bo.branch_name ;
35. SELECT b.branch_name FROM deposit_scheme d,
borrow_scheme b WHERE b.branch_name = d.branch_name
AND b.amount > d.balance ;
36. SELECT c.customer_name, cl.banker_name, c.customer_city
FROM customer_scheme c, client_scheme cl
WHERE cl.customer_name = c.customer_name ;
37. SELECT (d.balance - b.amount) total_amount FROM
deposit_scheme d, borrow_scheme b WHERE
d.customer_name = "shaktiman" AND
d.customer_name = b.customer_name ;
38. SELECT * FROM customer_scheme WHERE customer_name IN
(SELECT customer_name FROM deposit_scheme WHERE
balance IN (SELECT MIN(balance) FROM deposit_scheme));
COMPUTER EDUCATION DIVISION 45
ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414
39. (SELECT customer_name, amount FROM borrow_scheme WHERE
amount IN (SELECT MIN(amount) FROM borrow_scheme))
UNION
(SELECT customer_name, amount FROM borrow_scheme WHERE
amount IN (SELECT MAX(amount) FROM borrow_scheme));
40. SELECT * FROM deposit_scheme WHERE balance > ANY
(SELECT AVG(balance) FROM deposit_scheme) ;
41. SELECT * FROM deposit_scheme WHERE balance < ANY
(SELECT AVG(amount) FROM borrow_scheme) ;
42. SELECT * FROM customer_scheme WHERE customer_name IN
(SELECT customer_name FROM borrow_scheme WHERE
loan_number < 20 AND loan_number > 13) ;
43. SELECT banker_name FROM client_scheme ORDER BY
banker_name DESC ;
44. SELECT DISTINCT b1.branch_city FROM branch_scheme b1,
branch_scheme b2 WHERE
b1.branch_city = b2.branch_city AND
b1.branch_name < > b2.branch_name ;
45. SELECT * FROM deposit_scheme WHERE balance >1000;
SQL Tutorial
amit@abroandsis.com, amit_abros@yahoo.com
46. SELECT customer_city FROM customer_scheme WHERE
customer_name IN (SELECT customer_name FROM
client_scheme WHERE banker_name = "patel");
OR
SELECT cu.customer_name, cu.customer_city FROM
customer_scheme cu, client_scheme cl WHERE
cl.banker_name = "patel" AND
cu.customer_name = cl.customer_name;
47. SELECT * FROM borrow_scheme WHERE amount > 1200
48. SELECT * FROM customer_scheme WHERE customer_name IN
(SELECT customer_name FROM deposit_scheme
WHERE balance >= 1000 AND customer_name like "p%");
***

More Related Content

PPT
Db1 lecture4
PDF
Database Systems - SQL - DDL Statements (Chapter 3/3)
PDF
Database Systems - SQL - DDL Statements (Chapter 3/2)
PPTX
Advanced SQL Webinar
PPT
Chapter08
DOC
A must Sql notes for beginners
PPT
Advanced Sql Training
PPTX
Db1 lecture4
Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/2)
Advanced SQL Webinar
Chapter08
A must Sql notes for beginners
Advanced Sql Training

What's hot (20)

PPT
Introduction to-sql
ODP
BIS05 Introduction to SQL
PPTX
PPTX
Creating database using sql commands
PPTX
Avinash database
PPT
Les02 (restricting and sorting data)
PPT
Chapter 07 ddl_sql
PPT
Les09 (using ddl statements to create and manage tables)
PPT
MY SQL
DOCX
Exploring collections with example
DOCX
DOC
Oracle sql material
DOC
DOC
Best sql plsql material
PDF
Assignment#07
PPTX
Database Management - Lecture 2 - SQL select, insert, update and delete
PDF
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
PPT
Introduction to structured query language (sql)
Introduction to-sql
BIS05 Introduction to SQL
Creating database using sql commands
Avinash database
Les02 (restricting and sorting data)
Chapter 07 ddl_sql
Les09 (using ddl statements to create and manage tables)
MY SQL
Exploring collections with example
Oracle sql material
Best sql plsql material
Assignment#07
Database Management - Lecture 2 - SQL select, insert, update and delete
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
Introduction to structured query language (sql)
Ad

Similar to Sql tutorial (20)

PPT
Sqlbysandeep
PPTX
lovely
PPTX
SQL Query
PPT
Sql basics and DDL statements
PPTX
SQL - DML and DDL Commands
PPTX
Data Manipulation Language.pptx
PPTX
Database models and DBMS languages
PPTX
SQL DATABASE MANAGAEMENT SYSTEM FOR CLASS 12 CBSE
PPT
Sql 2006
PPT
Sql – Structured Query Language
PDF
Data manipulation language
DOCX
COMPUTERS SQL
ODP
Mysqlppt
PPTX
PPTX
Its about a sql topic for basic structured query language
PPT
Mysql Ppt
PPTX
SQL PPT.pptx
PPT
Interactive SQL: SQL, Features of SQL, DDL & DML
DOC
Module 3
PPTX
SQl data base management and design
Sqlbysandeep
lovely
SQL Query
Sql basics and DDL statements
SQL - DML and DDL Commands
Data Manipulation Language.pptx
Database models and DBMS languages
SQL DATABASE MANAGAEMENT SYSTEM FOR CLASS 12 CBSE
Sql 2006
Sql – Structured Query Language
Data manipulation language
COMPUTERS SQL
Mysqlppt
Its about a sql topic for basic structured query language
Mysql Ppt
SQL PPT.pptx
Interactive SQL: SQL, Features of SQL, DDL & DML
Module 3
SQl data base management and design
Ad

Recently uploaded (20)

PPTX
Pharma ospi slides which help in ospi learning
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Insiders guide to clinical Medicine.pdf
PDF
Computing-Curriculum for Schools in Ghana
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Pre independence Education in Inndia.pdf
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
Pharma ospi slides which help in ospi learning
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
TR - Agricultural Crops Production NC III.pdf
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Insiders guide to clinical Medicine.pdf
Computing-Curriculum for Schools in Ghana
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Microbial disease of the cardiovascular and lymphatic systems
Final Presentation General Medicine 03-08-2024.pptx
Microbial diseases, their pathogenesis and prophylaxis
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Anesthesia in Laparoscopic Surgery in India
Pre independence Education in Inndia.pdf
Abdominal Access Techniques with Prof. Dr. R K Mishra
human mycosis Human fungal infections are called human mycosis..pptx
STATICS OF THE RIGID BODIES Hibbelers.pdf

Sql tutorial

  • 1. SQL Tutorial Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414 COMPUTER EDUCATION DIVISION ABRO&SIS A Group of Artist and Computer S/W & H/W Professional
  • 2. SQL Tutorial 2 amit@abroandsis.com, amit_abros@yahoo.com SQL SQL stands for Structured Query Language. It is a Fourth Generation Language (4 GL). SQL commands can be divided into Five major categories with regard to their functionality. They are : (i) Data Definition Language (DDL). (ii) Data Manipulation Language (DML). (iii) Transaction Control Commands (iv) Session Control Commands (v) System Control Command. Data Definition Language (DDL) DDL stands for Data definition language. It provides facility/ commands to create and maintain the database. To construct and administer the database, there are three major DDL statements – (i) CREATE (ii) DROP (iii) ALTER Data Manipulation Language (DML) DML stands for data manipulation language. It provides facility to manipulate data in a table. To manipulate data in tables directly or through views we use the four standard DML statements. They are : (i) SELECT (ii) DELETE (iii) INSERT (iv) UPDATE Data manipulation capability allows one to retrieve and modify contents of the database/ table.
  • 3. COMPUTER EDUCATION DIVISION 3 ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414 Transaction Control Language (TCL) Transaction control commands manage changes made by DML commands. (i) COMMIT (ii) ROLLBACK (iii) SAVEPOINT Session Control Commands Session Control command dynamically manage the properties of a user session. (i) ALTER SESSION (ii) SET ROLL System Control Command System Control Command dynamically manages the properties of an Oracle instance. This command does not implicitly commit the current transaction. (i) ALTER SYSTEM Note : TCL command, Session control command, and System control commands are discussed in Oracle/ PL SQL Tutorial. DDL COMMANDS To Create a Table - CREATE statement is used to create a table. Syntax : CREATE TABLE < table name > ( < attribute list >) ; Where, < attribute list > : : = < attribute name > < data type > [NOT NULL] [, < attribute list >] < data type > : : = < integer / smallint / char(n) / varchar(n) / float / decimal(p[, q]) >.
  • 4. SQL Tutorial amit@abroandsis.com, amit_abros@yahoo.com e.g., CREATE TABLE Employee (Emp_no integer NOT NULL, Name char(25), Skill char(20), Pay_rate decimal(10,2)) ; CREATE statement can be used to create database, table, index or view. To create index - CREATE INDEX statement is used to create index in an existing relation. The columns to be used in the generation of the index are also specified. The CLUSTER option could be specified to indicate that the records are to be placed in physical proximity to each other. Syntax : CREATE [UNIQUE] INDEX <name of index > ON <existing table name> (<column name [ ASC/ DESC ] [, column name [ ORDER] ….. ] ) [ CLUSTER] ; e.g., CREATE INDEX Emp_index ON Employee (Name ASC, Pay_rate DESC); To Create a View - CREATE statement is used to create a view. View is a virtual relation. Syntax : CREATE VIEW < view name > AS < query expression > CREATE VIEW < view name > (At_name1, At_name2, …. ) AS (SELECT …. ) e.g., a view can be created for a subset of the tuples of a relation. Command Purpose CREATE DATABASE To create database. CREATE TABLE To create table/ relation. CREATE INDEX To create an index on a column. CREATE VIEW To create a view. DROP DATABASE To delete a database. DROP TABLE To delete a table. DROP INDEX To delete an index DROP VIEW To delete a view.
  • 5. COMPUTER EDUCATION DIVISION 5 ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414 CREATE VIEW FreeEmp AS (SELECT Emp_no FROM Employee) MINUS (SELECT Emp_no FROM Duty_allocation ) ; CREATE VIEW Employ ( E_no, Ename, E_skill) AS (SELECT Emp_no, Name, Skill FROM Employee ); CREATE TABLE Emp_info (Emp_no integer NOT NULL, Name char(20), Skill char(20), Phone_no decimal(10)); CREATE TABLE Emp_pay_rate (Emp integer NOT NULL, Hourly_rate decimal(10,2)); These two tables can be seems as a single in the form of view as : CREATE VIEW Employ Emp_no, Name, Skill, Pay_rate AS (SELECT Emp_no, Name, skill, hourly_rate FROM Emp_Info, Emp_pay_rate WHERE Emp_no = Emp); To Delete a view - DROP statement is used to delete a view. Syntax : DROP VIEW < view _name > e.g., DROP VIEW FreeEmp. Note : A tuple in a view can be theoretically updated, under the following constraints : 1. Any update operation through a view requires that the user has appropriate authorization. 2. if the definition of the view involves a simple query on a single base relation and includes the primary key, the following update operations are possible: a) A new tuple could be inserted into the database via a view. b) An existing tuple could be deleted via a view. c) The value of a nonprime attribute could be modified. 3. The insertion of a new record using a view requires that the primary attributes are included in the view, and the values for these are specified for the insertion i.e., they are not null. 4. Updates are not allowed through views involving aggregation or grouping operations.
  • 6. SQL Tutorial amit@abroandsis.com, amit_abros@yahoo.com 5. Updates are allowed through a view defined using a simple query involving a single base relation and containing either the primary key or a candidate key of the base relation. 6. Updates are not allowed through view involving multiple relations. To Delete Existing Table or Index - DROP statement is used to delete existing database, table, index or view. Syntax : DROP TABLE < existing table name > DROP INDEX < existing index name > e.g., DROP TABLE Employee; DROP INDEX emp_index ; In addition to CREATE and DROP statement ALTER TABLE or MODIFY DATABASE are also available in DDL. To alter an existing table – ALTER statement is used to alter an existing table. ALTER statement can be used to alter the existing table. This statement allows one or more new column to add to an existing relation. The added column contains NULL value by default. Syntax : ALTER TABLE <existing table name> ADD <column name> <data type> [ … ] Where, <column name> : : = field name / new field name. e.g., ALTER TABLE Employee ADD Phone_no decimal(10); ALTER TABLE Employee ADD Ta Decimal(4), Hra Decimal(4).
  • 7. COMPUTER EDUCATION DIVISION 7 ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414 DML COMMANDS To Update existing Table - UPDATE statement is used to modify one or more records in a specified relation. The record to be modified are specified by a predicate in WHERE clause and the new value of the column to be modified is specified by a SET clause. Syntax : UPDATE <relation> SET <target value list> [WHERE <predicate>] Where, <target value list> : : = <attribute name> = <value expression> [, <target value list>] e.g., UPDATE Employee SET Pay_rate = 7.85 WHERE Name = “Ram” ; To Delete record – Delete statement is used to delete one or more records from a relation. The records to be deleted are specified by the predicate in the WHERE clause. You are required to specify WHERE clause otherwise all the records from the relation can be deleted, but the relation is still remain in the database, although it is an empty relation. Syntax : DELETE FROM < relation > [ WHERE < predicate >] e.g., DELETE FROM Employee WHERE Name = “Ram” To Insert record - INSERT statement is used to insert a new tuple into a specified relation. The value of each field of the record to be inserted is either specified by an expression or could come form selected records of existing table. Syntax : (i) INSERT INTO < relation > VALUES (< value list > ) (ii) INSERT INTO < relation > (< target list >) VALUES (< value list >) ; Where, < value list > : : = < value expression > [, < value list > ] ; < target list > : : = < attribute name > [, < target list > ] ; e.g., INSERT INTO Employee VALUES (456, “Shyam”, “Cook”, 7.50)
  • 8. SQL Tutorial amit@abroandsis.com, amit_abros@yahoo.com Note : VALUES clause can be represented by a SELECT statement, which is evaluated and the result is inserted into the relation specified in the INSERT statement. In (ii) Syntax, a list of attribute names whose values are included in the < value list > are specified. To retrieve records – SELECT statement is the only data retrieval statement in SQL. It specifies the methods of selecting/ showing the tuples of the relation. Syntax : SELECT <target list> FROM <relation list> [ WHERE <Predicate>] ; Or, SELECT [DISTINCT] <target list> FROM < relation list > [ WHERE < predicates > ] [ ORDER BY < int / column_name [ASC / DESC ], … > ] ; Where, DISTINCT option is used in the select statement to eliminate duplicate tuples in the result. < target list > : : = < attribute/ field name > [ , < target list> ] FROM clause specifies the relations to be used in the evaluation of the statement. It includes a relation list. < relation list> : : = < relation name > [ < tuple variable >] [, < relation list > ] < tuple variable > : : = a tuple variable is an identifier. The domain of the tuple variable is the relation preceding it. WHERE The where clause is used to specify the predicates involving the attributes of the relation appearing in the FROM clause. ORDER BY The order by clause is used to ordered the result of a query either in Ascending (ASC) or in Descending (DESC) order. Int – Ordinal position of the column in the result table. If there is more than one specification, then the left – to – right specification corresponds to major – to – minor ordering. e.g., SELECT Name FROM Employee.
  • 9. COMPUTER EDUCATION DIVISION 9 ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414 SELECT DISTINCT Name FROM Employee. SELECT * FROM Employee WHERE Name = “Shyam” Note: To retrieve all the field/ column of the relation, we can write all the column name separated by comma ( , ) or simply putting an asterisk ( * ) as shown in the example. CONDITION SPECIFICATION SQL supports the following Boolean and comparison operators : Boolean Operator NOT AND OR Comparison Operator = Equal to < > Not equal to > Greater then < Less then > = Greater then or equal to < = Less then or equal to These operators allows the formulation of more complex predicates, which are attached to the SELECT statement by the WHERE clause. NOT has highest priority. OR has lowest priority.
  • 10. SQL Tutorial amit@abroandsis.com, amit_abros@yahoo.com ARITHMETIC & AGGREGATE OPERATORS SQL provides a full component of arithmetic operators and functions. This includes functions to find the Average, Sum, Maximum, Minimum, and To count the number of occurrences. All these functions are used with Select statement. COUNT This function must be used either with the DISTINCT option of the SELECT statement or as COUNT( * ). When used with the DISTINCT option, it COUNTS the number of distinct values in the column. If the total number of rows in the relation is to be determined, COUNT ( * ) must be used. e.g., SELECT COUNT ( * ) FROM Menu ; SELECT COUNT ( DISTINCT Pay_rate ) FROM Employee ; AVG The operand of this function must have a numeric value. It finds the average of these values. If the DISTINCT option is specified, the duplicate values are not used for computing the average. e.g., SELECT AVG( Pay_rate) FROM Employee ; SELECT AVG( Pay_rate ) FROM Employee WHERE Skill = “Chef” ; SUM The operand of this function must have a numeric value. It finds the sum of these values. If the DISTINCT option is specified, the duplicate values are ignored in computing the result. e.g., SELECT SUM( Price) FROM Menu ; MIN This function finds the minimum of the values in the column. The DISTINCT option has no effect on this function. e.g., SELECT MIN( Price) FROM Menu ;
  • 11. COMPUTER EDUCATION DIVISION 11 ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414 MAX This function finds the maximum of the values in the column. The DISTINCT option has no effect on this function. e.g., SELECT MAX( Price) FROM Menu ; Note : (i) If the function is followed by the word DISTINCT then unique values are used. (ii) If ALL follows the function then all the values are used for evaluating the function. ALL is the default. (iii) COUNT ( * ) has a special meaning in that it counts the number of rows of a relation. Arithmetic Operator + For Addition - for Subtraction * for Multiplication / for Division. SET MANIPULATION Operator ANY The operator ANY allows the testing of a value against a set of values. The comparisons can be on of { <, >, < =, > = , = , < > } and are specified in SQL as the operators, < ANY, > ANY, < = ANY, > = ANY, = ANY, < > ANY. We refer to any one of these operators by the notation < operator > ANY. In general, the condition C < operator > ANY (SELECT X FROM …. ) evaluates to true if and only if the comparison “ C < operator > ANY {at least one or more from the result of the select X FROM … }” is true.
  • 12. SQL Tutorial amit@abroandsis.com, amit_abros@yahoo.com Syntax : … … < operator > ANY ( SELECT …….. ). e.g., Get employees who are working either on the date 19860419 or 19860420. SELECT Emp_no FROM Duty_allocation WHERE Day = ANY ( SELECT Day FROM Duty_allocation WHERE Day = 19860419 OR Day = 19860420) ; IN The operator IN is equivalent to “ = ANY ” operator. It tests for the membership of a value within a set. i.e., a single value within a set of values. e.g., Get employees who are working either on the date 19860419 or 19860420. SELECT Emp_no FROM Duty_allocation WHERE Day IN (19860419, 19860420) CONTAINS The operator CONTAINS is used to test for the containment of one set in another. e.g., Find the names of employees who are assigned to all positions that require a chef’s skill. SELECT e.Name FROM Employee e WHERE (SELECT Posting_no FROM Duty_allocation d WHERE e.Emp_no = d.Emp_no) CONTAINS ( SELECT p.Posting_no FROM Position p WHERE p.skill = “Chef”) ; ALL The set operator ALL is used in general, to show that the condition : C < operator > ALL (SELECT X FROM …. ) Evaluates to true. This is so, if and only if the comparison C < operator > ALL the values from the result of (SELECT X FROM …… )” is true. e.g., Find the employees with the lowest pay rate.
  • 13. COMPUTER EDUCATION DIVISION 13 ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414 SELECT Emp_no, Name, Pay_rate FROM Employee WHERE Pay_rate < = ALL (SELECT Pay_rate FROM Employee WHERE Skill = “Chef”); NOT IN The set operator NOT IN is equivalent to < > ALL. e.g., Find the names and rate of pay of all employees who are NOT allocated a duty. SELECT Name, Pay_rate FROM Employee WHERE Emp_no NOT IN (SELECT Emp_no FROM Duty_allocation ) ; NOT CONTAINS The set operator NOT CONTAINS, the complement of CONTAINS is true if one set of values is not a superset of another set of values. EXISTS The set operator EXISTS is the SQL version of the existential quantifier. The expression : EXISTS ( SELECT X FROM …. ) Evaluates to true if and only if the result of “SELECT X FROM …..” is not empty. e.g., Find the names and rate of pay of all employees who are allocated a duty. SELECT Name, Pay_rate FROM Employee WHERE EXISTS (SELECT * FROM Duty_allocation WHERE Employee.Emp_no = Duty_allocation.Emp_no) ; NOT EXISTS The set operator NOT EXISTS is the complement form of EXISTS. The expression : NOT EXISTS ( SELECT X FROM …. ) evaluates to true if and only if the result of “SELECT X FROM …..” is empty. e.g., Find the names and rate of pay of all employees who are NOT allocated a duty.
  • 14. SQL Tutorial amit@abroandsis.com, amit_abros@yahoo.com SELECT Name, Pay_rate FROM Employee WHERE NOT EXISTS (SELECT * FROM Duty_allocation WHERE Employee.Emp_no = Duty_allocation.Emp_no) ; UNION UNION is similar to the traditional set theory Union operator. Duplicates are removed from the result of a union. e.g., Get employees who are waiters or worker at Posting_no = 321. ( SELECT Emp_no FROM Employee WHERE Skill = “Waiter” ) UNION ( SELECT Emp_no FROM Duty_allocation WHERE Posting_no = 321) ; MINUS The traditional set theory difference operator is MINUS. e.g., Get a list of employees not assigned a duty. ( SELECT Emp_no FROM Employee ) MINUS ( SELECT Emp_no FROM Duty_allocation); INTERSECT The traditional set theory set intersection operator is INTERSECT. e.g., Get a list of names of employees with the skill of “chef” who are assigned a duty. SELECT Name FROM Employee WHERE Emp_no IN (( SELECT Emp_no FROM Employee WHERE Skill = “Chef”) INTERSECT (SELECT Emp_no FROM Duty_allocation)) ; BETWEEN Predicate The use of BETWEEN gibes the range within the values must lie. If the value should lie outside a range then BETWEEN is to be preceded by NOT. e.g., SELECT * FROM Menu WHERE Price BETWEEN 5 AND 15 ; SELECT * FROM Menu WHERE Price NOT BETWEEN 5 AND 15 ;
  • 15. COMPUTER EDUCATION DIVISION 15 ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414 LIKE Predicate LIKE predicate is used for pattern matching. A column of type char can be compared with a string constant. The use of the word LIKE doesn’t look for exact match but a form of wild string match. A % or - or * can appear in the string constant. Where, % stands for a sequence of n characters (n > = 0 ). - stands for a single character. * stands for a sequence of n characters (n > = 0 ). TEST FOR NULL To test an attribute for the presence or absence of null. Syntax : Col. Ref IS [ NOT ] NULL. e.g., SELECT * FROM Order WHERE Qty IS NULL ; SELECT * FROM Order WHERE Qty IS NOT NULL ; GROUP BY Feature This feature allows one to partition the result into a number of groups such that all rows of the group have the same value in some specified column. i.e., it allow data to be classified into categories. Whenever, GROUP BY is used then the phrase WHERE is to be replaced by HAVING. The meaning of HAVING is the same as WHERE except that the condition is now applicable to each group. e.g., (i) Get a count of different employees on each shift. SELECT Shift, COUNT (DISTINCT Emp_no) from Duty_allocation GROUP BY Shift.
  • 16. SQL Tutorial amit@abroandsis.com, amit_abros@yahoo.com (ii) Get employee numbers of all employees working on at least two dates. SELECT Emp_no FROM Duty_allocation GROUP BY Emp_no HAVING COUNT( * ) > 1. MULTIPLE TABLES QUERY Syntax : SELECT T1.s11, …, T1.a1n, …, T2.a21, …, T2.a2m [, … ] FROM T1, T2, [, T3, …] WHERE T1.a1j = T2.a2k …. ; Where, T1, T2, …. are different relations/ tables. a11, a12, ….. a1n, a21, a22, … a2m, …. are fields / columns/ attributes of table T1, T2 respectively. e.g., SELECT e1.Name, e1.Pay_rate FROM Employee e1, employee e2 WHERE e1.Pay_rate > e2.Pay_rate AND e2.Name = “Ram” ;
  • 17. COMPUTER EDUCATION DIVISION 17 ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414 Practical – 1 Consider the relation/ table given below : Item_List (Item_code numeric 4 , Item string 15, Rate numeric 6) Orders (Bill numeric 3, Item_Code numeric 4, Piece numeric 3) Cash_Memo (Bill numeric 3, Counter_No numeric 1, Emp_name string 20, Dates, Amount numeric 6) Now, Write the SQL statements for the following : 1. Display the item, rate for item code = 80. 2. List the item code, item, rate from item list where rate is greater than 20. 3. Display the details from item list where item code is less than 40 and rate is greater than 20. 4. Display the Item code and Rate of “Burger”. 5. Find the item list whose cost is Rs 10.00. 6. Display the item code from orders for Bill = 804. 7. List the details of items for bill = 804. 8. Get the item list whose cost is BETWEEN 10 to 25. 9. Get the item list sorted on rate. 10. Get the item details whose name starts with “T”. 11. Get the item details whose rate is minimum. 12. Display the details of cash memo for “Rama Swami”. 13. List the detail of greatest bill amount. 14. Display the minimum bill amount. 15. Get the average bill amount. 16. Get the second greatest amount of the bill. 17. Get the lowest and highest bill amount.
  • 18. SQL Tutorial amit@abroandsis.com, amit_abros@yahoo.com 18. Get the second lowest and highest amount. 19. Get the item list whose rate is lowest or highest. 20. Display the total number of items sold. 21. Display the item wise pieces sold. 22. List the counter wise Sales amount. 23. List the detail of cash memo ordered by counter no. 24. Get the bill list in descending order by amount. 25. Get the detail of item list in descending order of their item. 26. Display the details of bill amount day wise. 27. Get the number of “Burger” sold. 28. Display the item code and number of pieces sold. 29. Select the counter wise sales amount. 30. Get the details of item sold on 28th January 2006. 31. Get the details of item list sold on 20th and 30th January. 32. Get the item detail sold by “Rama swami”. 33. Get the details of item sold by “Hina” and number of pieces sold. 34. Count the number of staff working of the restaurant. 35. Get the item detail which is not sold till now. 36. Get the items detail sold in maximum quantity. 37. Get the name of the employee who sold “Ice Cone”. 38. Get the name of the employee who sold either “Samosa” or “Milk Cake”. 39. Get the name of the employee who sold “Tea” and “Milk Cake”. 40. Get the detail of item list which is sold either on 12th or 20th January. 41. Get the details of Billed amount which is greater than average Billed amount.
  • 19. COMPUTER EDUCATION DIVISION 19 ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414 Solution : To solve these queries, first you are required to create all the five tables. Then read all the question carefully. Now enter data according to the question. Item_List Item_Code Item Rate -------------------- ------------ ---------------- 10 Samosa 5.00 20 Milk Cake 50.00 30 Chola Bhatora 10.00 40 Burger 20.00 50 Tikki 10.00 60 Tea 5.00 70 Cold Drink 15.00 80 Ice Cone 25.00 Cash_Memo Bill Counter_No Emo_Name Dates Amount --------------- ------------------ -------------------- -------------------- -------------- 801 2 Ram Saran 20060112 150.00 802 3 Rama Swami 20060115 120.00 803 4 Mohan 20060118 240.00 804 1 Tina 20060119 40.00 805 3 Rama Swami 20060120 320.00 806 2 Ram Saran 20060120 120.00 807 1 Hina 20060120 40.00 808 1 Hina 20060128 10.00 809 2 Rama Swami 20060128 30.00 810 1 Tina 20060130 10.00 Now write the SQL Statement. You can get help from the solution given below. Orders Bill Item_Code Piece -------------------- ---------- ---------------- 801 30 5 802 10 12 803 40 6 804 20 2 805 80 4 806 40 3 807 40 2 808 50 1 809 30 3 810 60 2
  • 20. SQL Tutorial amit@abroandsis.com, amit_abros@yahoo.com 1. SELECT item, rate FROM item_list WHERE item_code = 80 2. SELECT * FROM item_list WHERE rate > 20 3. SELECT * FROM item_list WHERE item_code < 40 AND rate > 20 4. SELECT item_code, rate FROM item_list WHERE item ="Burger" 5. SELECT item FROM item_list WHERE rate = 10 6. SELECT item_code FROM orders WHERE bill = 804 7. SELECT * FROM item_list WHERE item_code IN (SELECT item_code FROM orders WHERE bill = 804) Or, SELECT i.item_code, item, rate, piece, bill FROM item_list i, orders o WHERE i.item_code = o.item_code AND o.bill= 804 8. SELECT * FROM item_list WHERE rate BETWEEN 10 AND 20 Or, SELECT * FROM item_list WHERE rate <= 20 AND rate >= 10
  • 21. COMPUTER EDUCATION DIVISION 21 ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414 9. SELECT * FROM item_list ORDER BY rate 10. SELECT * FROM item_list WHERE item LIKE "t%" 11. SELECT * FROM item_list WHERE rate IN (SELECT MIN(rate) FROM item_list ) Or, SELECT * FROM item_list WHERE rate = (SELECT MIN(rate) FROM item_list ) 12. SELECT * FROM cash_memo WHERE emp_name = "Rama Swami" 13. SELECT * FROM cash_memo WHERE amount IN (SELECT MAX(amount) FROM cash_memo ) 14. SELECT MIN(amount) "minimum bill amount" FROM cash_memo 15. SELECT AVG(amount) "average bill amount" FROM cash_memo 16. SELECT MAX(amount) FROM cash_memo WHERE amount NOT IN (SELECT MAX(amount) FROM cash_memo)
  • 22. SQL Tutorial amit@abroandsis.com, amit_abros@yahoo.com 17. SELECT MIN(amount) "Minimum Bill Amount", MAX(amount) "Maximum Bill Amount" FROM cash_memo 18. SELECT MAX(amount), MIN(amount) FROM cash_memo WHERE amount NOT IN ((SELECT MAX(amount) FROM cash_memo) UNION (SELECT MIN(amount) FROM cash_memo)) 19. SELECT * FROM item_list WHERE rate IN ((SELECT MIN(rate) FROM item_list) UNION (SELECT MAX(rate) FROM item_list)) 20. SELECT SUM(piece) Total_no_of_item_sold FROM orders 21. SELECT item_code, SUM(piece) "Total piece sold" FROM orders GROUP BY item_code 22. SELECT Counter_No , SUM(amount) sale_amount FROM cash_memo GROUP BY Counter_No 23. SELECT * FROM cash_memo ORDER BY Counter_No 24. SELECT * FROM cash_memo ORDER BY amount DESC
  • 23. COMPUTER EDUCATION DIVISION 23 ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414 25. SELECT * FROM item_list ORDER BY item DESC 26. SELECT * FROM cash_memo ORDER BY dates 27. SELECT SUM(piece) FROM orders WHERE item_code = (SELECT item_code FROM item_list WHERE item = "burger") 28. SELECT item_code, SUM(piece) FROM orders GROUP BY item_code 29. SELECT Counter_No , SUM(amount) FROM cash_memo GROUP BY Counter_No 30. SELECT * FROM item_list WHERE item_code = (SELECT item_code FROM orders WHERE bill = (SELECT bill FROM cash_memo WHERE dates = 20060128)) 31. SELECT * FROM item_list WHERE item_code IN (SELECT item_code FROM orders WHERE bill IN (SELECT bill FROM cash_memo WHERE dates = 20060120 OR dates = 20060130))
  • 24. SQL Tutorial amit@abroandsis.com, amit_abros@yahoo.com 32. SELECT * FROM item_list WHERE item_code IN (SELECT item_code FROM orders WHERE bill IN (SELECT bill FROM cash_memo WHERE emp_name = "rama swami")) 33. SELECT * FROM item_list WHERE item_code IN (SELECT item_code FROM orders WHERE bill IN (SELECT bill FROM cash_memo WHERE emp_name = "hina")) 34. SELECT COUNT(emp_name) "No of employee" FROM cash_memo Or, SELECT COUNT(*) "No of employee" FROM cash_memo 35. SELECT * FROM item_list WHERE item_code NOT IN (SELECT item_code FROM orders) 36. SELECT * FROM item_list WHERE item_code IN (SELECT item_code FROM orders WHERE piece IN (SELECT MAX(piece) FROM orders))
  • 25. COMPUTER EDUCATION DIVISION 25 ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414 37. SELECT emp_name FROM cash_memo WHERE bill IN (SELECT bill FROM orders WHERE item_code IN (SELECT item_code FROM item_list WHERE item = "ice cone")) 38. SELECT emp_name FROM cash_memo WHERE bill IN (SELECT bill FROM orders WHERE item_code IN (SELECT item_code FROM item_list WHERE item = "samosa" OR item = "milk cake")) 39. SELECT emp_name FROM cash_memo WHERE bill IN (SELECT bill FROM orders WHERE item_code IN (SELECT item_code FROM item_list WHERE item = "tea" OR item = "milk cake")) 40. SELECT * FROM item_list WHERE item_code IN (SELECT item_code FROM orders WHERE bill IN (SELECT bill FROM cash_memo WHERE dates = 20060112 OR dates = 20060120)) 41. SELECT * FROM cash_memo WHERE amount > (SELECT AVG(amount) FROM cash_memo)
  • 26. SQL Tutorial amit@abroandsis.com, amit_abros@yahoo.com Practical – 2 Consider the relation/ table given below : Sailors (Sailor_Id string 4, Sailor_Name string 20, Rating numeric 1, Age numeric 2) Boats (Boat_Id string 4, Boat_Name string 20, Colour string 15) Reserves (Sailor_Id string 4, Boat_Id string 4, Days string 8) Now, Write the SQL statements for the following : 1. Display the list of details of sailors whose rating 1. 2. Display the list of details of sailors whose rating is 5 or 2. 3. Display the detail of sailor whose age is less than 30 and greater than 25. 4. List the details of sailors whose age is less than 25 or greater than 30. 5. List the sailors detail whose name starts with “R”. 6. Select the list of sailor who is engaged in 1st January. 7. Get the detail of sailors who is engaged on 2nd January. 8. List the sailor id who has no any reserve date. 9. List the details of boat which is not reserved for a single time (till now). 10. Get the list of reserved date for sailor id S001. 11. Get the boat name for all the yellow and white colored boat. 12. Select the list of all different boat name. 13. Display all the distinct colour of boat. 14. Get the total number of boat available. 15. Get the name of boat and number of boat with same name. Or, Get the distinct boat name and their number. 16. Display the list of sailor and number of days they works. 17. Get the distinct boat detail which is in use. 18. What are the different rating available. 19. Display the distinct boat name available.
  • 27. COMPUTER EDUCATION DIVISION 27 ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414 20. List the dates at which more than one boat is booked. 21. Get the detail of sailors whose age is greater than 32. 22. List the name of boat whose colour is Red. 23. Get the sailors name whose name starts with “N”. 24. Select the detail of sailors whose name ends with “m”. 25. Get the detail of boat and sailors who worked on 1st January 2006. 26. Get the detail of sailor whose rating is 1 and age is maximum. 27. Get the details of sailor who has worked at 20060126. 28. Get the number of records in sailors table. 29. Get the detail of boat which is reserved between 10-15 January 2006. 30. Get the details of boat which reserved between 10 -15 January 2006 excluding 10 and 15 . 31. Select the sailor who is working on any of the date BETWEEN 20 to 24. 32. Select the sailor who has worked on 22 and 25 January 2006. 33. Get the boat which is used more than 2 times (having count > 2). 34. Get the detail of sailors who had operated boat id “B009”. 35. Get the detail of sailors who had operated “Kala Ghora”. 36. Get the number of distinct boat in use. 37. Get the details of boat which is not in use. 38. Get the dates on which more than two boats are reserved and their number. 39. Get the average age of the sailor. 40. Get the sailor list who worked on either 20 or 25 January 2006 (but not on the both the date). 41. Get the sailors id who has operated same boat two times (more than once). 42. Get the sailors detail who has operated same boat two times. Solution : To solve these queries, first you are required to create all the five tables. Then read all the question carefully. Now enter data according to the question.
  • 28. SQL Tutorial amit@abroandsis.com, amit_abros@yahoo.com Boats Boat_Id Boat_Name Colour -------------------- ---------- --------------------------- B001 Pawan Hansh White B002 Kala Ghora Black B003 Kala Ghora Black B004 Pushpak Bluess Green B005 Pushpak Dark Green B006 Tytanic Pink B007 Aatmrath Yellow B008 Aatmrath Brown B009 Kala Ghora Dark Blue B010 Pushpak Green B011 Kohinoor Red B012 Pawan Hansh White B013 Pawan Hansh White Reserves Sailor_Id Boat_Id Days -------------------- ----------- --------------- S001 B002 20060101 S002 B001 20060101 S001 B003 20060102 S003 B004 20060103 S005 B005 20060103 S006 B008 20060104 S007 B006 20060102 S008 B007 20060102 S009 B010 20060102 S010 B011 20060102 S010 B012 20060106 S002 B013 20060107 S003 B005 20060107 S005 B004 20060108 S007 B005 20060109 S009 B007 20060110 S008 B001 20060112 S002 B005 20060115 S005 B002 20060120 S006 B003 20060120 S001 B002 20060122 S001 B008 20060125 S005 B008 20060126 S010 B010 20060127 Sailors Sailor_Id Sailor_Name Rating Age -------------------- --------------------------------- --- S001 Ram Kumar 1 30 S002 Radhe Shyam 2 20 S003 Parimal 3 28 S004 Pyare Mohan 2 28 S005 Shyam Sundar 1 26 S006 Suresh 1 25 S007 Ajit Singh 3 23 S008 Narayan 1 32 S009 Sita Ram 2 35 S010 Shiv 5 30
  • 29. COMPUTER EDUCATION DIVISION 29 ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414 1. SELECT * FROM sailors WHERE rating = 1 2. SELECT * FROM sailors WHERE rating = 2 OR rating = 5 3. SELECT * FROM sailors WHERE age < 30 AND age > 25 4. SELECT * FROM sailors WHERE age < 25 OR age > 30 5. SELECT * FROM sailors WHERE Sailor_Name like "r%" 6. SELECT * FROM sailors WHERE sailor_id = ANY (SELECT sailor_id FROM reserves WHERE days = 20060101) 7. SELECT * FROM sailors WHERE sailor_id NOT IN (SELECT sailor_id FROM reserves WHERE days = 20060102) 8. SELECT sailor_id FROM sailors WHERE sailor_id NOT IN (SELECT sailor_id FROM reserves WHERE days BETWEEN 20060101 AND 20060130) 9. SELECT * FROM boats WHERE boat_id not IN ( SELECT DISTINCT boat_id FROM reserves )
  • 30. SQL Tutorial amit@abroandsis.com, amit_abros@yahoo.com 10. SELECT * FROM reserves WHERE sailor_id = "S001" 11. SELECT boat_name FROM boats WHERE colour = "white" OR colour = "yellow" 12. SELECT DISTINCT boat_name FROM boats 13. SELECT DISTINCT colour FROM boats 14. SELECT COUNT(boat_name) FROM boats 15. SELECT boat_name, COUNT(*) FROM boats GROUP BY boat_name 16. SELECT sailor_id, COUNT(*) FROM reserves GROUP BY sailor_id 17. SELECT * FROM boats WHERE boat_id = ANY (SELECT DISTINCT boat_id FROM reserves) 18. SELECT DISTINCT rating FROM sailors 19. SELECT DISTINCT boat_name FROM boats
  • 31. COMPUTER EDUCATION DIVISION 31 ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414 20. SELECT days FROM reserves GROUP BY days HAVING COUNT (*) > 1 21. SELECT * FROM sailors WHERE age > 32 22. SELECT boat_name FROM boats WHERE colour = "red" 23. SELECT sailor_name FROM sailors WHERE sailor_name LIKE "n%" 24. SELECT * FROM sailors WHERE sailor_name LIKE "%m" 25. SELECT s.sailor_name, s.sailor_id, s.rating, s.age, b.boat_name, b.boat_id, b.colour FROM sailors s, boats b, reserves r WHERE s.sailor_id = r.sailor_id AND b.boat_id = r.boat_id AND days = 20060101
  • 32. SQL Tutorial amit@abroandsis.com, amit_abros@yahoo.com 26. SELECT * FROM sailors WHERE age IN (SELECT MAX(age) FROM sailors WHERE rating = 1) 27. SELECT * FROM sailors WHERE sailor_id IN ( SELECT sailor_id FROM reserves WHERE days = 20060126) 28. SELECT count(*) "No. of records" FROM sailors 29. SELECT * FROM boats WHERE boat_id IN (SELECT boat_id FROM reserves WHERE days BETWEEN 20060110 AND 20060115) Or, SELECT * FROM boats WHERE boat_id IN (SELECT boat_id FROM reserves WHERE days >= 20060110 AND days <= 20060115) 30. SELECT * FROM boats WHERE boat_id IN (SELECT boat_id FROM reserves WHERE days > 20060110 AND days < 20060115) 31. SELECT * FROM sailors WHERE sailor_id IN (SELECT sailor_id FROM reserves WHERE days >= 20060120 AND days <= 20060124)
  • 33. COMPUTER EDUCATION DIVISION 33 ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414 32. SELECT * FROM sailors WHERE sailor_id IN (SELECT sailor_id FROM reserves WHERE days = 20060122 OR days = 20060125 AND sailor_id = sailor_id) 33. SELECT boat_id, COUNT(*) FROM reserves GROUP BY boat_id HAVING COUNT(*) > 2 34. SELECT * FROM sailors WHERE sailor_id = ANY (SELECT sailor_id FROM reserves WHERE boat_id = "B009") 35. SELECT * FROM sailors WHERE sailor_id IN (SELECT sailor_id FROM reserves WHERE boat_id IN (SELECT boat_id FROM boats WHERE boat_name = "kala ghora")) 36. SELECT COUNT(DISTINCT(boat_id)) FROM reserves 37. SELECT * FROM boats WHERE boat_id NOT IN (SELECT DISTINCT boat_id FROM reserves)
  • 34. SQL Tutorial amit@abroandsis.com, amit_abros@yahoo.com 38. SELECT days, COUNT(*) FROM reserves GROUP BY days HAVING COUNT (*) > 2 39. SELECT AVG(age) "Average age" FROM sailors 40. SELECT * FROM sailors WHERE sailor_id IN (SELECT sailor_id FROM reserves WHERE days = 20060120 OR days = 20060125 AND sailor_id < > sailor_id) 41. SELECT DISTINCT r1.sailor_id FROM reserves r1, reserves r2 WHERE r1.boat_id = r2.boat_id AND r1.sailor_id = r2.sailor_id AND r1.days < > r2.days 42. SELECT * FROM sailors WHERE sailor_id IN (SELECT DISTINCT r1.sailor_id FROM reserves r1, reserves r2 WHERE r1.boat_id = r2.boat_id AND r1.sailor_id = r2.sailor_id AND r1.days <> r2.days)
  • 35. COMPUTER EDUCATION DIVISION 35 ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414 Practical – 3 Consider the schema/ table given below : Branch_scheme (Branch_name, asset, Branch_city) Customer_scheme (Customer_name, street, customer_city) Deposit_scheme (Branch_name, account_number, customer_name, balance) Borrow_scheme (Branch_name, loan_number, customer_name, amount) Client_scheme (Customer_name, banker_name) Now, Write the SQL statements for the following : 1. Find the name and balance of customer living at “Gomti Street”. 2. Find the name of banker whose customer is living at “Mumbai”. 3. Find the complete detail of account holder 123. 4. Find the branch, which is situated at the same city. 5. Find the customer name who is borrower and depositor. 6. Get the customer detail who is not a borrower. 7. Get the branch detail of all the customer who is either borrower or depositor. 8. Get the total amount borrowed by the customer. 9. Get the average amount borrowed by the customer. 10. Find the branch detail who borrow largest amount. 11. Display the customer address who has least balance. 12. List the detail of depositor according to account number. 13. Find the customer detail who has second greatest balance. 14. Find the customer detail who is borrower but not the depositor. 15. Find the total amount owned by “Asraf ali”. 16. Find the total amount borrowed by the customer. 17. Display the customer and branch whose city is same. 18. Find the banker whose customer is living at “Kolkata”. 19. Find the customer detail whose street or city begins with “J”. 20. Find the branch detail whose city end with “r”. 21. Find the assets which contain “ut” in their name.
  • 36. SQL Tutorial amit@abroandsis.com, amit_abros@yahoo.com 22. Find the number of records in customer table. 23. Find the customer detail whose loan number is 13. 24. Find the customer detail whose account number is less than 122 with balance greater than 1100 along with account number and balance amount. 25. Find the depositors details whose Assets is “auto”. 26. Find the depositors detail who has highest deposit. 27. Find the banker whose customer borrow 1200. 28. Find the banker who has only depositor. 29. Find the branch which is in the same city where “Bhagat singh” liver. 30. Find the customer who living in the same city. 31. Find the branch details where assets is “Camera” and branch name = “Dwaraka”. 32. Find the customer name who lives in same city. 33. Display the detail of account number 121. 34. Find the customer detail as well as branch detail of loan number 13. 35. Find the branch where borrow is greater than deposit. 36. Find the Banker city from where banker works. 37. Find the amount owned by “Shaktiman”. 38. Find the detail of Depositor of minimum amount. 39. Find the name of minimum and maximum amount borrower. 40. Find the depositors detail who deposit amount greater than the average amount. 41. Find the depositors detail who deposits less than the average borrowed amount. 42. Find the customer detail whose loan number is less than 20 and greater than 13. 43. List the bankers in descending order. 44. Find the different branch city where more than one branch. 45. Find all customers who have a balance of over Rs. 1000. 46. Write the query to find the clients of banker Patel, and the city they live in. 47. Write a statement to find all the customers who have a loan amount of more than Rs. 1200. 48. Write a statement to find all the customers whose name starts with “R” and who have a balance of more than Rs. 10,000.
  • 37. COMPUTER EDUCATION DIVISION 37 ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414 Solution : To solve these queries, first you are required to create all the five tables. Then read all the question carefully. Now enter data according to the question. Branch_sechme Branch_Name Asset Branch_City -------------------- -------------------------- ----------- Indraprasth Computer Delhi Maharastra Refrigerator Pune Dwaraka Camera Delhi Pink City Auto Jaipur Golden Temple Truck Amritsar Ganga Books Allahabad Patliputra Furnitures Patna Customer_Scheme Customer_Name Street Customer_City -------------------- ---------- ------------------------------- Parimal Tripathi Monarch Mumbai Pyare Mohan Tulsi Chennai Kumar Ranjan Konark Kolkata Shaktiman Frejar Patna Asraf Ali Rajpath Delhi Bhagat Singh Swarna Amritsar Vishawas Joker Banglore Akbar Gomti Allahabad Sher Singh Mansarovar Jaipur Parimal Puskar Jaipur
  • 38. SQL Tutorial amit@abroandsis.com, amit_abros@yahoo.com Deposit_scheme Branch_Name Account_No Customer_Name Balance -------------------- ----------- -------------------- -------------------- Pink City 123 Parimal 1000 Dwaraka 120 Asraf Ali 1200 Patliputra 122 Shaktiman 2000 Ganga 121 Akbar 1100 Borrow_scheme Branch_Name Loan_Number Customer_Name Amount -------------------- ----------- ------------- -------------------------- Indraprasth 12 Asraf Ali 1200 Pink City 14 Sher Singh 2000 Patliputra 13 Shaktiman 1300 Client_scheme Customer_Name Banker_Name -------------------- ------------------------- Parimal Tripathi Rama Pyare Mohan Sita Kumar Ranjan Radhe Vishawas Narayana Asraf Ali Sangam Akbar Patel Sher Singh Ram Shaktiman Ram Parimal Rama Now write the SQL Statement. You can get help from the solution given below.
  • 39. COMPUTER EDUCATION DIVISION 39 ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414 1. SELECT customer_name, balance FROM deposit_scheme WHERE customer_name IN (SELECT customer_name FROM customer_scheme WHERE street = "gomti"); 2. SELECT banker_name FROM client_scheme WHERE customer_name IN (SELECT customer_name FROM customer_scheme WHERE customer_city = "mumbai"); 3. SELECT * FROM customer_scheme WHERE customer_name IN (SELECT customer_name FROM deposit_scheme WHERE account_no = 123 ); 4. SELECT b1.branch_name FROM branch_scheme b1, branch_scheme b2 WHERE b1.branch_city = b2.branch_city AND b1.branch_name < > b2.branch_name ; 5. SELECT customer_name FROM borrow_scheme WHERE customer_name IN (SELECT customer_name FROM deposit_scheme); 6. SELECT * FROM customer_scheme WHERE customer_name NOT IN (SELECT customer_name FROM borrow_scheme); 7. SELECT * FROM branch_scheme WHERE branch_name IN ((SELECT branch_name FROM borrow_scheme ) UNION (SELECT branch_name FROM deposit_scheme));
  • 40. SQL Tutorial amit@abroandsis.com, amit_abros@yahoo.com 8. SELECT SUM(amount) total_borrowed_amount FROM borrow_scheme; 9. SELECT AVG(amount) average_borrowed_amount FROM borrow_scheme; 10. SELECT * FROM branch_scheme WHERE branch_name IN (SELECT branch_name FROM borrow_scheme WHERE amount = (SELECT MAX(amount) FROM borrow_scheme)); 11. SELECT * FROM customer_scheme WHERE customer_name IN (SELECT customer_name FROM deposit_scheme WHERE balance = (SELECT MIN(balance) FROM deposit_scheme)); 12. SELECT * FROM deposit_scheme ORDER BY account_no; 13. SELECT * FROM customer_scheme WHERE customer_name IN (SELECT customer_name FROM deposit_scheme WHERE balance IN (SELECT MAX(balance) FROM deposit_scheme WHERE balance NOT IN (SELECT MAX(balance) FROM deposit_scheme))); 14. SELECT * FROM customer_scheme WHERE customer_name IN (SELECT customer_name FROM borrow_scheme WHERE customer_name NOT IN (SELECT customer_name FROM deposit_scheme));
  • 41. COMPUTER EDUCATION DIVISION 41 ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414 15. SELECT (d.balance - b.amount) total_amount FROM borrow_scheme b, deposit_scheme d WHERE d.customer_name = "asraf ali" AND b.customer_name = d.customer_name ; 16. SELECT SUM(amount) FROM borrow_scheme ; 17. SELECT c.customer_name, b.branch_name, c.customer_city FROM customer_scheme c, branch_scheme b WHERE b.branch_city = c.customer_city ; 18. SELECT banker_name FROM client_scheme WHERE customer_name IN (SELECT customer_name FROM customer_scheme WHERE customer_city = "kolkata"); 19. SELECT * FROM customer_scheme WHERE street like "j%" OR customer_city like "j%" ; 20. SELECT * FROM branch_scheme WHERE branch_city like "%r" ; 21. SELECT asset FROM branch_scheme WHERE asset like "%ut%" ; 22. SELECT COUNT(*) FROM customer_scheme ; Or, SELECT COUNT(*) total_no_of_records FROM customer_scheme;
  • 42. SQL Tutorial amit@abroandsis.com, amit_abros@yahoo.com 23. SELECT * FROM customer_scheme WHERE customer_name IN (SELECT customer_name FROM borrow_scheme WHERE loan_number = 13) ; 24. SELECT c.customer_name, c.street, c.customer_city, d.balance, d.account_no FROM customer_scheme c, deposit_scheme d WHERE d.balance > 1100 AND d.account_no < 122 AND c.customer_name = d.customer_name ; Or, SELECT * FROM customer_scheme WHERE customer_name IN (SELECT customer_name FROM deposit_scheme WHERE account_no < 122 AND balance > 1100) ; 25. SELECT * FROM deposit_scheme WHERE branch_name IN (SELECT branch_name FROM branch_scheme WHERE asset = "auto"); 26. SELECT * FROM deposit_scheme WHERE balance IN (SELECT MAX(balance) FROM deposit_scheme ) ; 27. SELECT banker_name FROM client_scheme WHERE customer_name IN (SELECT customer_name FROM borrow_scheme WHERE amount = 1200);
  • 43. COMPUTER EDUCATION DIVISION 43 ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414 28. SELECT DISTINCT c.customer_name, c.banker_name FROM borrow_scheme b, deposit_scheme d, client_scheme c WHERE b.customer_name < > d.customer_name AND d.customer_name = c.customer_name ; Or, SELECT distinct c.customer_name, c.banker_name FROM borrow_scheme b, deposit_scheme d, client_scheme c WHERE b.customer_name < > d.customer_name AND d.customer_name = c.customer_name ; 29. SELECT branch_name FROM branch_scheme WHERE branch_city = (SELECT customer_city FROM customer_scheme WHERE customer_name = "bhagat singh") ; 30. SELECT c1.customer_name FROM customer_scheme c1, customer_scheme c2 WHERE c1.customer_city = c2.customer_city AND c1.customer_name < > c2.customer_name; 31. SELECT Branch_name, Asset, Branch_City FROM Branch_scheme WHERE assets = “Camera” AND Branch_name = “Dwaraka”. 32. SELECT c1.customer_name FROM customer_scheme c1, customer_scheme c2 WHERE c1.customer_city = c2.customer_city AND c1.customer_name < > c2.customer_name ;
  • 44. SQL Tutorial amit@abroandsis.com, amit_abros@yahoo.com 33. SELECT * FROM deposit_scheme WHERE account_no = 121 ; 34. SELECT c.customer_name, c.street, c.customer_city, b.branch_name, b.asset FROM customer_scheme c, branch_scheme b, borrow_scheme bo WHERE bo.loan_number = 13 AND c.customer_name = bo.customer_name AND b.branch_name = bo.branch_name ; 35. SELECT b.branch_name FROM deposit_scheme d, borrow_scheme b WHERE b.branch_name = d.branch_name AND b.amount > d.balance ; 36. SELECT c.customer_name, cl.banker_name, c.customer_city FROM customer_scheme c, client_scheme cl WHERE cl.customer_name = c.customer_name ; 37. SELECT (d.balance - b.amount) total_amount FROM deposit_scheme d, borrow_scheme b WHERE d.customer_name = "shaktiman" AND d.customer_name = b.customer_name ; 38. SELECT * FROM customer_scheme WHERE customer_name IN (SELECT customer_name FROM deposit_scheme WHERE balance IN (SELECT MIN(balance) FROM deposit_scheme));
  • 45. COMPUTER EDUCATION DIVISION 45 ABRO&SIS, Rz. 47/271, Hans Park, West Sagarpur, New Delhi – 110046. Ph. 011 – 65070414 39. (SELECT customer_name, amount FROM borrow_scheme WHERE amount IN (SELECT MIN(amount) FROM borrow_scheme)) UNION (SELECT customer_name, amount FROM borrow_scheme WHERE amount IN (SELECT MAX(amount) FROM borrow_scheme)); 40. SELECT * FROM deposit_scheme WHERE balance > ANY (SELECT AVG(balance) FROM deposit_scheme) ; 41. SELECT * FROM deposit_scheme WHERE balance < ANY (SELECT AVG(amount) FROM borrow_scheme) ; 42. SELECT * FROM customer_scheme WHERE customer_name IN (SELECT customer_name FROM borrow_scheme WHERE loan_number < 20 AND loan_number > 13) ; 43. SELECT banker_name FROM client_scheme ORDER BY banker_name DESC ; 44. SELECT DISTINCT b1.branch_city FROM branch_scheme b1, branch_scheme b2 WHERE b1.branch_city = b2.branch_city AND b1.branch_name < > b2.branch_name ; 45. SELECT * FROM deposit_scheme WHERE balance >1000;
  • 46. SQL Tutorial amit@abroandsis.com, amit_abros@yahoo.com 46. SELECT customer_city FROM customer_scheme WHERE customer_name IN (SELECT customer_name FROM client_scheme WHERE banker_name = "patel"); OR SELECT cu.customer_name, cu.customer_city FROM customer_scheme cu, client_scheme cl WHERE cl.banker_name = "patel" AND cu.customer_name = cl.customer_name; 47. SELECT * FROM borrow_scheme WHERE amount > 1200 48. SELECT * FROM customer_scheme WHERE customer_name IN (SELECT customer_name FROM deposit_scheme WHERE balance >= 1000 AND customer_name like "p%"); ***