The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.
Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by Naveen Gupta, 2020-09-07 07:25:14

SQL_Modifed

SQL_Modifed

8 data management – sql

Learning Outcomes

After going through this chapter students will be able to:
• understand RDBMS and its advantages.
• explain SQL and other related terminologies.
• compare and apply various keys in their relations.
• recognise the categories of SQL command.
• deploy the constraints in the table.
• identify the operator, clauses and functions.
• practice SQL commands.

IMPORTANT TERMS & DEFINITIONS

1. Data. It can be described as the raw of facts and figures. 11. Domain. A set of unique pool of values allowed for a
column is known as its domain.
2. Information. Processing of data into meaningful
statements enhances our knowledge. 12. Tuple. A row/record in a relation or a horizontal subset
is known as table.
3. Database. Organised collection of logically related data.
13. Attribute. A column/ Field in a relation or vertical subset.
4. DBMS. Data Base Management System. A computer
system that allows us to manage Databases. 14. Cardinality. Number of rows in a relation denotes
cardinality of the table.
5. Need for DBMS. Database provides centralised control
on its operational data. Thus, with the help of a database 15. Degree. Number of columns in a relation.

• redundancy can be reduced. 16. SQL. Stands for Structured Query Language. It is a
standard programming language used to store, retrieve
• inconsistence can be avoided. and manage data in relational databases.

• data integrity is maintained. 17. Candidate Key. A column or a set of columns which
uniquely identify a row in a relation. A table/relation
• data can be shared. can have multiple candidate keys.

• security restrictions can be imposed. 18. Primary Key. A column or a set of columns which can
uniquely identify a row in a relation.
6. Data Redundancy. Duplication (Replication) of data is
known as Data Redundancy. 19. Alternate key. A candidate key which is not a primary
key but can serve as a primary key.
7. Data Inconsistency. It is a situation/problem where the
same data is stored in two different files in a different 20. Foreign Key. It is a column that references the primary
format. key of another table.

8. Data Security. Protection of data from unauthorised 21. DDL. Stands for Data Definition Language. It is a
persons against accidental/intentional addition or category of SQL command which is used to manipulate
modification or deletion. database objects like table structure. Examples of DDL
commands are: Create Table, Alter Table, Drop Table.
9. Data Privacy. Create database, Drop database.

10. Relation. It is a two dimensional format which contains
rows and columns. A relation is also known as Table.

136 Together with®  Computer Science (Python)—12

22. DML. Stands for Data Manipulation Language. It is a category of SQL command which is used to manipulate the data.
Examples of DML commands are Insert, Delete, Update and Select.

23. Arithmetic Operator are the operator used for mathematical calculation e.g. +, –, *, /, %
24. Relational Operators. These operators are used to compare two values or a column with value in SQL. Different relational

operators are >(less than), >=(less than or equal to), <(greater than), <=(greater than or equal to), =(equal to), ! < > (not
equal to).
25. Logical Operators. These operators are used to combine two or more conditions. Different logical operators are AND(&&),
OR( ), NOT(!)
26. Data Type. Data type is required to specify that what sort of value will be shared in particular column. It is important
for the overall optimization of our database.
MySQL Data Types:
•  Numeric Types
•   String Types
•   Date & Time Types

Data Type Description Storage

INT(size) Allows signed integers from -2147483638 to 2147483637 and 0 4 bytes
FLOAT(size,d) to 4294967925 unsigned integers. 4 bytes
DOUBLE(size,d) 8 bytes
Allows small numbers with floating decimal point. The size
parameter is used to specify the maximum number of digits, and
the d parameter is used to specify the maximum number of digits
to the right of the decimal.

Allows large numbers with floating decimal point. The size
parameter is used to specify the maximum number of digits, and
the d parameter is used to specify the maximum number of digits
to the right of the decimal.

DECIMAL(size,d) Allows storing DOUBLE as a string, so that there is a fixed Varies
String Data Types decimal point. The size parameter is used to specify the maximum
number of digits, and the d parameter is used to specify the
maximum number of digits to the right of the decimal.

Data Type Description Storage
CHAR(size)
Holds up to 255 characters and allows a fixed (Declared column length of characters *
length string. Number of bytes) <= 255

Holds up to 255 characters and allows a • String value(Len) + 1 WHERE column

variable length string. If you store characters values require 0 − 255 bytes

VARCHAR(size) greater than 55, then the data type will be • String value(Len) + 2 bytes WHERE
TEXT
converted to TEXT type. column values may require more than

255 bytes

Allows a string with a maximum length of Actual length in bytes of String value(Len)

65,535 characters + 2 bytes, where Len < 216

Data Management – Sql 137

Date and Time Data Type

Data Type Description Storage Required Storage Required as
YEAR() Before MySQL 5.6.4 of MySQL 5.6.4
DATE() Holds the value of year either in a two digit or
in a four-digit format. Year values in the range 1 byte 1 byte
(70-99) are converted to (1970-1999), and year
values in the range (00-69) are converted to 3 bytes 3 bytes
(2000-2069)
Holds the date values in the format: YYYY-
MM-DD, where the supported range is (1000-
01-01) to (9999-12-31)

TIME() Holds the time values in the format: HH:MI:SS, 3 bytes 3 bytes + fractional
where the supported range is (-838:59:59) to seconds storage
(838:59:59)

DATETIME() A combination of date and time values in the 8 bytes 5 bytes + fractional
format: YYYY-MM-DD HH:MI:SS, where the seconds storage
supported range is from ‘1000-01-01 00:00:00’
to ‘9999-12-31 23:59:59’

27. Create Table. This is a DDL Command used to create a or
new table. We can specify the table name, column name
with its data-type. describe <table name>

Syntax For example

Create table <table name> ( Desc student;

Column_name1 data-type(data size/limit) 29. Insert. This is a DML command used to insert/add a
new record at the end of the table.
constraints,
Syntax
Column_name2 data-type(data size/limit),
Insert into <table name> (<column name1>,
Column_name3 data-type(data size/limit) <column name2>, <column name3>) VALUES
(<expression1>,<expression2>,expression3>);
);

For example For example

Create table student Insert into student(admno,first_name,last_
name,D_O_B,fees,state) values
(

Admno int(5) primary key, (1101,‘Tejas’,’Gupta’,’2008-06-15’,4500,’Delhi’);

First_Name varchar(15) not null, Or

Last_Name varchar(15), Insert into student values (1101, ‘Tejas’, ’Gupta’,
’2008-06-15’,4500,’Delhi’);
D_O_B date,
30. Select. This is used to display the data either in selection
Fees decimal(9,2), or projection way.

State varchar(10) Selection: Way show(s) all attributes from the table(s).

); Syntax

28. Describe. This command is used to view the structure Select * from <table name>;
of the table (that is a column name, data-type and
constraints). For example

Syntax Select * from the student where admno=1101;

Desc <table name> Projection: T his way is used to show specific attributes
from the table(s).

138 Together with®  Computer Science (Python)—12

Syntax For example

Select <column name1>, <column name2>, Drop table student;
<column name3> from <table name>;
36. Clause. The condition through which record(s) can be
For example filtered.

Select admno, first_name, state from student where (a) Where: This clause is used to search a rows/
admno1101; record(s).

31. NULL. Null is something undefined or unavailable Syntax
or Missing value/ No value but it’s not 0. If the value
of the record is not known, then we can write NULL. Select <column name1>, <column name2>
Arithmetic or relational operators cannot work with from <table name> where <condition>;
NULL.
For example
(a) Is Null: returns true, when column contain null
value. Select admno, name, fees from student where
state=’Delhi’;
Select * from student where Fees is null;
(b) Distinct: This clause is used to fetch(retrieve) unique
(b) Is not Null: returns true, when column does not values(non-duplicate) from the column of the table.
contain null value.
Syntax
Select * from student where Fees is not null;
Select distinct <column name> from <table
32. Update. This DML command is used to modify/edit name>;
data/record(s) of the table.
For example
Syntax
Select distinct state from student;
Update <table name> Set <column name (whose
value to be <changed)> = <expression (new value)> (c) Order by: This clause is used to arrange the records of
where <condition>; the relation either in ascending or descending order.

For example Syntax

Update student Set state = ‘Haryana’ where admno Select * from <table name> order by <column
= 1101; name>;

33. Alter. This DDL command is used to add/modify/remove For example
structure(column) of the table.
• Select * from student order by admno;
Syntax # by default ascending order (ASC)

Alter table <table name> add <column name> <data • Select * from student order by admno desc;
type> <data width> ; # Descending Order

For example (d) Group by: This clause is used to group the column(s)
with aggregate function.
Alter table student add gender char(1);
Syntax
34. Delete. This DML command is used to remove rows or
record(s) from the table. S e l e c t < c o l u m n n a m e > , a g g r e g a t e _
function(column name> from <table name>
Syntax
group by <column name>;
Delete from <table name> where <condition>;
For example
For example
Select state, sum(fees) from student group by
Delete from student; state; # Display state wise total fees

# removes all records from the table. (e) Having: This clause is used to specify a condition
on grouped column.
Delete from student where state=’Delhi’
Syntax
# remove only delhi records.
Select <column name>, sum<column name>
35. Drop. This DDL command is used to remove the records from <table name> group by
along with its structure of the table from the database.
<column name> having count(column name)
Syntax > <expression>;

Drop table <table name>;

Data Management – Sql 139

For example 41. Aggregate Functions.

Select state, sum(fees) from student group by • Sum(): This function is used to get total value of
state having count(state)>5; specified column.

# To display state wise total fees having more For example
than 5 records.
Select sum(fees) from the student;
37. Between operator. This operator is used to display the
data between a specified range of Text, Numbers or • Max(): This function is used to find the maximum
Date. value of the specified column.

Syntax For example

Select * from <table name> where <column name> Select max(fees) from the student;
between <min value> and <max value>;
• Min(): This function is used to find the minimum
Both <min value> and <max value> are inclusive. value of the specified column.

For example For example

• select * from student where admno between 1100 Select min(fees) from the student;
and 1199;
• Avg(): This function is used to display the average
• Select * from student where admno not between of the specified column.
1100 and 1199;
For example
38. In operator. This clause is used to fetch the information
from the table by providing one or more values from Select Avg(fees) from the student;
the specified column.
• Count(): This function is used to count a number
Syntax of values in the specified column. It will not count
NULL values.
Select <column name1>, <column name2> , …..
from <table name> where <column name> in For example
(<value1,value2,value3>);
Select count(fees) from student;
For example
42. Join Clause. It is used to combine records from two or
• Select admno, name from student where state more tables in a database.
in(‘Delhi’,’Haryana’);
• Equi Join. It returns data from the tables with
• Select admno, name from student where state not matching values.
in(‘Delhi’,’Haryana’);
Syntax
39. Like operator. This clause is used to search the data
according to the given pattern and for this we need to Select column(s)(from any of the tables) from
use the two wild card characters. Table1, Table2

• Percent symbol (%).Matches any string. where table1.common_column=table2.
commom_column;
• Underscore (_). Matching single character.
• Cross Join/ Cartesian Product. A product of two
Syntax or more sets that consists of all combinations of
elements drawn one from each set. It is a set of
Select <column name1>, <column name2> from records from two or more tables are joined(inner
<table name> where <column name> like <matching join) or join condition is missing. Cartesian product
pattern>; of two relations A and B is written as A X B. Rows
of both tables will be multiplied, and columns will
For example be added. For Example, Table A contains four rows
and three columns, and Table B contain 5 rows and
Select * from student where name like ‘A%’; 3 cols then Cartesian product result to 20 rows(4X5)
#name starts with ‘A’. and 6 columns(3+3).

40. Constraints. Constraints are rules to restrict the type Syntax
of data to be entered in a table. It will be helpful in
maintaining the accuracy, Integrity and reliability of Select column(s)(from any of the tables) from
the data. Most commonly used constraints are Primary Table1, Table2
Key, Foreign Key, Not Null, Check, default etc.

140 Together with®  Computer Science (Python)—12

43. REVIEW of the commands.

-- Database-Level Commands

DROP DATABASE databaseName -- Delete the database

DROP DATABASE IF EXISTS databaseName -- Delete if it exists

CREATE DATABASE databaseName -- Create a new database

CREATE DATABASE IF NOT EXISTS databaseName -- Create only if it does not exists

SHOW DATABASES -- Show all the databases in this server

USE databaseName -- Set the default (current) database

SELECT DATABASE() -- Show the default database

SHOW CREATE DATABASE databaseName -- Show the CREATE DATABASE statement

-- Table-Level

DROP TABLE [IF EXISTS] tableName, ...

CREATE TABLE [IF NOT EXISTS] tableName (

columnNamecolumnTypecolumnAttribute, ...

PRIMARY KEY(columnName),

FOREIGN KEY (columnNmae) REFERENCES tableName (columnNmae)

)

SHOW TABLES -- Show all the tables in the default database

DESCRIBE / DESC tableName-- Describe the detailed structured for a table

ALTER TABLE tableName ... -- Modify a table, e.g., ADD COLUMN and DROP COLUMN

ALTER TABLE tableName ADD columnDefinition

ALTER TABLE tableName DROP columnName

ALTER TABLE TABLE NAME ADD PRIMARY KEY (columnNmae)

ALTER TABLE TABLE NAME DROP PRIMARY KEY

ALTER TABLE tableName ADD FOREIGN KEY (columnNmae) REFERENCES tableName (columnNmae)
ALTER TABLE tableName DROP FOREIGN KEY constraintName
SHOW CREATE TABLE tableName -- Show the CREATE TABLE statement for this tableName

-- Row-Level

INSERT INTO tableName

VALUES (column1Value, column2Value,...) -- Insert on all Columns

INSERT INTO tableName

VALUES (column1Value, column2Value,...), ... -- Insert multiple rows

INSERT INTO tableName (column1Name, ...,columnNName)

VALUES (column1Value, ...,columnNValue) -- Insert on selected Columns

DELETE FROM tableName WHERE criteria

UPDATE tableName SET columnName = expr, ... WHERE criteria

SELECT * | column1Name AS alias1, ...,columnNName AS aliasN

FROM tableName

WHERE criteria

GROUP BY columnName

ORDER BY columnName ASC|DESC, ...

HAVING groupConstraints

Data Management – Sql 141

Solved Question bank

Very Short Answer/Objective Type Questions [1 Mark] (c) Degree 5, Cardinality 7.
(d) Cardinality 7, Degree 7.
1. Which command is used to add a new row?
Ans. (a)
(a) Insert (b) create
11. Fill in the Blanks.
(c) update (d) add (a) _________________ clause is used to remove

Ans. (a) duplicate rows from the result of SQL select
statement.
2. Which command is used to change the database? Ans. Distinct
(b) ________________ key is used to uniquely
(a) Open (b) Change identify row in a table and also does not accept
NULL values.
(c) Use (d) Select Ans. Primary
(c) ________________ clause is used to arrange the
Ans. (c) rows of a table.
Ans. Order by
3. Command to remove the row(s) from table student is (d) ________________ clause is used to filter the
(a) drop table student; row from the table.
(b) drop from student;
(c) remove from student; Ans. Where
(d) delete from student; (e) ________________ command is used to display

Ans. (d) information from the table.
Ans. Select
4. Which is not a MySQL function? (f) Alter is _______________ command.
Ans. DDL
(a) Mult() (b) Min() (g) Select * from student where admno between

(c) Count() (d) Sum() 1101 _______ 1199;.
Ans. AND/&&
Ans. (a) (h) Select * from student where state

5. Which is not a category of SQL command? (‘Delhi’,’MP’,’Tamil Nadu’);.
Ans. IN
(a) DDL (b) XML (i) ____________ command is used to view the

(c) DML (d) TCL structure of the table.
Ans. Desc
Ans. (b) (j) ____________ is undefined/ unavailable/ missing

6. Which command is used to close the MySQLSoftware/ value/ No value.
Ans. NULL
application?
12. State TRUE or FALSE.
(a) exit(); (b) Close(); (a) DELETE is DDL command.

(c) Close; (d) exit; Ans. FALSE
(b) COUNT() will count NULL values.
Ans. (a)
Ans. FALSE
7. Which command is used to modify rows in a table. (c) SQL stands for Structured Query Language.

(a) Delete (b) Update Ans. TRUE
(d) Number of columns in a table is known as Degree.
(c) Alter (d) Modify
Ans. TRUE
Ans. (b) (e) Delete command is used to remove table.

8. Number of rows in a relation is known as Ans. FALSE

(a) Degree (b) Cardinality

(c) Cartesian Product (d) Attribute

Ans. (b)

9. Which clause is used to group the column(s) with

aggregate function?

(a) Order by (b) Like

(c) Where (d) Group by

Ans. (d)

10. A Table customer contains 5 rows and 7 columns.
What will be its cardinality and degree?

(a) Degree 7, Cardinality 5.

(b) Degree 5, Cardinality 7.

142 Together with®  Computer Science (Python)—12

13. Name the command used to change the database. 20. Name the SQL command used for the following:
Ans. USE <database-name>
(a) To add new record
14. Define Primary Key. (b) To remove a record
(c) To change the name of a column
Ans. A column or a set of columns which can uniquely (d) To change the database
identify a row in a relation. Primary key cannot have (e) To display records
Null values. (f) To edit record

For example AdmNo(Admission No) in table Student. Ans. (a) Insert (b) Delete (c) Alter

15. Define Foreign Key. (d) Use (f) Select (f) Update

Ans. It is a column that references the primary key of another 21. A Table customer contains 5 rows and 7 columns.
table. What will be its cardinality and degree?

16. Write the Difference between DDL and DML Ans. Degree – 7, Cardinality -5

Ans. DDL DML 22. A table Item and Store have one common column
Item-Id. Item table consists of 5 rows and 3 columns
• Stands for Data • Stands for Data while the store table consists of 7 rows and 5 columns.
Definition Language Manipulation Language What will be the degree and cardinality of these tables
in the cartesian product?
• I t is used to create/ • I t is used to insert/
modify/ remove the modify/ remove the Ans. Degree – 8 (5+3)
database schemas. records (rows) of the
table. Cardinality – 35 (7 X5)
• For example Create,
Alter, Drop • F or example Insert, 23. A table student consists of 5 rows and 7 columns.
Update, Delete Later on 3 columns added and 2 rows deleted. After
some time 5 new students added. What will be the
17. Write the difference between CHAR and VARCHAR. degree and cardinality?

Ans. CHAR VARCHAR Ans. Degree – 10
Cardinality - 8
• I t is fixed length • It is variable length Initial table: 5 rows and 7 columns
Later 3 columns added: 10 columns
string. string. 2 rows deleted : 3 rows and 10 columns
5 new students: 5 rows
• They are right-padded • T hey are not right-padded Degree = 10 (i.e. 7 + 3 = 10 columns)
cardinality = 8 (i.e. 5 – 2 + 5 = 8)
wi t h s p a c e s t o t h e with space. The length is
Short Answer Type Questions [2/3 Marks]
specified length. actual data it contains.
24. Write the difference between WHERE and HAVING
18. What do you mean by NULL? clause.

Ans. NULL means no value/ missing value. Ans. W here clause is used for selecting the rows based on
the condition applied on rows. While HAVING clauses
19. What is the purpose of BETWEEN Clause? used to select the rows from the data given by group by
group by clause in SQL.
Ans. This clause is used to filter the record by providing the
range in a column which contains only a numeric value
Text, Data can also be used with BETWEEN clause.

For example Select * from student where age between
15 and 18;

25. Observe the following tables VIDEO and MEMBER carefully and write the name of the RDBMS operation out of
(i) SELECTION (ii) PROJECTION (iii) UNION (iv) CARTESIAN PRODUCT, which has been used to produce

the output FINAL RESULT as shown below, Also, find the Degree and Cardinality of the final result.

TABLE: VIDEO TABLE: MEMBER

VNO VNAME type MNO NAME
M101 Namish Gupta
F101 The Last Battle Fiction M102 Sana Sheikh
M103 Lara James
C101 Angels and Devils Comedy

A102 Daredevils Adventure

Data Management – Sql 143

TABLE: FINAL Result

VNO VNAME type MNO MNAME
F101 The Last Battle Fiction M101 MNamish Gupta
F101 The Last Battle Fiction M102 Sana Sheikh
F101 The Last Battle Fiction M103 Lara James
C101 Angels and Devils Comedy M101 Namish Gupta
C101 Angels and Devils Comedy M103 Sana Sheikh
C101 Angels and Devils Comedy M103 Lara Sheikh
A102 Daredevils Adventure M101 Namish Gupta
A102 Daredevils Adventure M102 Sana Sheikh
A102 Daredevils Adventure M103 Lara James

Ans. (iv) CARTESIAN PRODUCT
DEGREE = 5
CARDINALITY = 9

26. Observe the following STUDENTS and EVENTS tables carefully and write the name of the RDBMS operation

which will be used to produce the output as shown in LIST ? Also, find the Degree and Cardinality of the LIST.

STUDENTS EVENTS

NO NAME EVENTSCODE EVENTNAME
1 Tara Mani 1001 Programming
2 Jaya Sarkar 1002 IT Quiz
3 Tarini Trikha

list

NO NAME eventcode eventname
1 Tara Mani 1001 Programming
1 Tara Mani 1002 IT Quiz
2 Jaya Sarkar 1001 Programming
2 jaya Sarkar 1002 ITQ Quiz
3 Tarini Trikha 1001 Programming
3 Tarini Trikha 1002 IT Quiz

Ans. Cartesian Product
Degree of LIST = 4
Cardinality of LIST = 6

27. Observe the following table CANDIDATE carefully and write the name of the RDBMS operation out of

(i) SELECTION  (ii) PROJECTION  (iii) UNION  (iv) CARTESIAN PRODUCT,
which has been used to produce the output as shown in RESULT ? Also, find the Degree and Cardinality of the

RESULT.

T ABLE: CANDIDATE

NO NAME Stream
C1 AJAY LAW
C2 ADITI MEDICAL
C3 ROHAN EDUCATION

C4 RISHAB ENGINEERING

144 Together with®  Computer Science (Python)—12

r ESULT

NO NAME
C3 ROHAN

Ans. (i) Selection and (ii) Projection
Degree = 2
Cardinality = 1

28. Observe the table ‘Club’ given below:

Table: Club

Member_id Member_Name Address Age Fee
M001 Sumit New Delhi 20 2000
M002 Nisha Gurgaon 19 3500
M003 Niharika New Delhi 21 2100
M004 Sachin Faridabad 18 3500

(i) What is the cardinality and degree of the above given table?
(ii) If a new column contact_no has been added and three more members have joined the club then how these

changes will affect the degree and cardinality of the above given table.
Ans. (i) Cardinality: 4

Degree: 5

(ii) Cardinality: 7

Degree: 6

29. Observe the following table and answer the parts  (i) and  (ii) accordingly [Sample Paper 2018]

Table: Product

Pno Name Qty PurchaseDate
101 Pen 102 12-12-2011
102 Pencil 201 21-02-2013

103 Eraser 90 09-08-2010

109 Sharpener 90 31-08-2012
113 Clips 900 12-12-2011

(a) Write the names of most appropriate columns, that can be considered as candidate keys.
(b) What is the degree and cardinality of the above table?
Ans. (a) Pno.

(b) The degree is 4 and Cardinality is 5.

30. Consider the table: CLUB as given below:

Table: CLUB

MEMBER_ID MEMBER_NAME ADDRESS AGE FEE

M002 NISHA GURGAON 19 3500

M003 NIHARIKA NEW DELHI 21 2100

M004 SACHIN FARIDABAD 18 3500

(a) What is the cardinality and degree of the above given table?
(b) If a new column contact_no has been added and three more members have joined the club then how these

changes will affect the degree and cardinality of the above given table.

Data Management – Sql 145

Ans. (a) Degree = 5    Cardinality = 3
(b) After adding one more column Contact_no, then Degree is 6
After adding 3 more members Cardinality is 6.

31. Write SQL commands for the following:

Table: TEACHER

TID NAME AGE DEPT DATEOFJOIN SAL SEX
12000 M
T118 Navin 40 Computer 2010-01-10 20000 F
30000 M
T107 Chetna 37 History 2008-03-24 25000 F
40000 M
T105 Sandeep 46 Maths 2006-12-12 28000 M

T110 Sangeeta 35 History 2010-07-01

T101 Rudransh 42 Maths 2004-09-05

T121 Neeraj 38 Physics 2011-04-01

(i) To show information about the teachers of the history department.
(ii) To list the names of teachers earning a salary between 20000 and 30000.
(iii) To count the number of male teachers.
(iv) Display gender wise total number of teachers.
(v) To list the name and age of teachers of female teachers in descending order of date of join.
(vi) Increase the salary by 10% for Maths departments.
(v ii) To delete the record of teacher Neeraj.
Ans. (i) Select * from teacher where DEPT= ’History.’
(ii) Select name from teacher where SAL between 20000 and 30000.
(iii) Select count(sex) from teacher where SEX=’M’.
(iv) Select sex, count(sex) from teacher group by sex;
(v) Select NAME, AGE from the teacher where sex=’F’ order by DATEOFJOIN DESC;
(vi) Update teacher set SAL = SAL+(10*SAL)/100 where DEPT=’Maths’;
(vii) Delete from teacher where NAME=’Neeraj’;
(Q-32 to Q-33) C onsider the following table HOSPITAL.

Table: HOSPITAL

PNo Name Age Department DateofAdm Charges Sex
1 Mayank 65 Surgery 23/02/2018 600 M
2 Babita 24 ENT 01/01/2019 400 F
3 Kashish 45 Orthopaedic 19/12/2018 400 M
4 Tarun 12 Surgery 01/10/2018 600 M
5 Manisha 36 ENT 12/01/2018 400 F
6 Imran 16 ENT 24/02/2018 400 M
7 Ankita NULL Cardiology 20/08/2018 800 F
8 Zoya 45 Gynecology 22/02/2018 500 F
9 Kush 19 Cardiology 13/01/2019 800 M
10 Shalini 31 Medicine 19/02/2018 300 F

Note: PNo is the primary key in the above table.

146 Together with®  Computer Science (Python)—12

32. Write SQL commands for the statements (a) to (g) Ans. (a) select* from hospital where name like ‘Z%’,
on the table HOSPITAL. (b) update hospital set Age=20 where Name=’Kush’;
(c) update hospital set Charges = Charges + (Charges
(a) To show all the information about the patients
of the cardiology department. *5)/100;
(d) delete from hospital where Name = ‘Tarun’;
(b) To list the names of female patients who are (e) Alter table hospital add DocName varchar(20);
either in the orthopaedic or surgery department. (f) select* from hospital where Age is NULL;
(g) update hospital set Charges = Charges-
(c) To list the name of all the patients with their
date of admission in ascending order. (Charges*5)/100 where Department = 'ENT'

(d) To display the patient’s name, charges, the age 34. Write SQL commands for the statements (a) to (h)
for female patients only. on the table HOSPITAL

(e) To count the number of patients with age > 30. (a) To insert a new row in the HOSPITAL table with
(f) To display various departments. the following data: 11,’ Kasif’, 37,’ENT’,’2018-
(g) To display the number of patients in each de- 02-25’, 300, ’M’.

partment. (b) To set charges to NULL for all the patients in
Ans. (a) select * from hospital where Department=’ the Surgery department.

Cardiology’; (c) To display patient details who are giving charges
in the range 300 and 400 (both inclusive).
(b) select name from hospital where Sex=’F’ and
(Department=’Cardiology’ or Department=’ (d) To display the details of that patient whose name
Surgery’); second character contains ‘a’.

or (e) To display total charges of ENT Department.
(f) To display details of the patients who admitted
select name from hospital where Sex=’F’ and
Department in (‘Cardiology’,‘Surgery’); in the year 2019.
(g) To display the structure of the table hospital.
(c) select name, DateofAdm from hospital order by (h) Write the command to create the above table.
DateofAdm; Ans. (a) Insert into hospital values(11,Kasif’,37,’ENT’,

(d) select name, Charges, Age from hospital where ’2018-02-25’, ‘M’);
Sex=‘F’;
(b) update hospital set Charges = NULL where
(e) select count(Age) from hospital where Age > 30; Department=’Surgery’;

(f) select distinct(Department) from hospital; (c) select* from hospital where charges between 300
and 400;
(g) select department, count(department) from hospital
group by department, (d) select* from hospital where name like ‘_a%’;

33. Write SQL commands for the statements (a) to (g) (e) selectsum(Charges) from hospital where Department
on the table HOSPITAL. =’ ENT’;

(a) To display the details of all the patients whose (f) select* from hospital where year(DateofAdm)=2019;
name starts with the alphabet ‘Z’.
(g) desc hospital;
(b) To change the age of the patient Kush to 20.
(c) To increase the charges of all the patients by (h) Create table Hospital (

5%. Pno int(3) Primary Key,
(d) To remove the record of the patient whose Name
Name Varchar(20),
is Tarun.
(e) To add another column DocName(Doctor Name) Age int(2),

of the type varchar in the above table. Department Varchar(15),
(f) To display patient detail whose age is miss-
DateofAdm date,
ing(null).
(g) To decrease the charges by 5% of all the patients Charges int(4),

admitted to the ENT department. Sex char(1) );

Data Management – Sql 147

(Q-35 to Q-37) Consider the following table Bank.
Table: Bank

AccNo Cust_name FD_Amount Months Int_Rate FD_Date
1001 Arti Gupta 30000 36 6.00 2018-07-01
1002 Dilip Lal 50000 48 6.75 2018-03-22
1003 Navin Gupta 30000 36 NULL 2018-03-01
1004 D.P. Yadav 80000 60 8.25 2017-06-12
1005 Jyoti Sharma 20000 36 6.50 2017-01-31
1006 Rakesh Kumar 70000 60 8.25 2018-06-15
1007 K.D. Singh 50000 48 NULL 2018-07-05
1008 Anjali Sharma 60000 48 6.75 2017-04-02
1009 Swati Garg 40000 42 6.50 2018-06-15
1010 Rupinder Kaur 25000 36 6.50 2018-09-27

35. Write SQL commands for the statements (a) to (g) (b) Display amounts of various FD from the table
on the table BANK Bank. An FD Amount should appear only once.

(a) To create the table Bank (Primary Key: AccNo) (c) Display the number of months of various loans
(b) Display the structure of the table Bank. from the table Bank. A month should appear
(c) Display the details of all the bank. only once.
(d) Display theAccNo, Cust_Name, and FD_Amount.
(e) Display the details of all the FD’s having maturity (d) Display the Customer Name and FD Amount
for all the Bank which do not have a number
time is less than 40 months. of months is 36.
(f) Display the AccNo and FD amount which started
(e) Display the Customer Name and FD Amount
before 01-04-2018. for which the FD amount is less than 500000
(g) Display details of all FD whose rate of interest or int_rate is more than 7.

are NULL. (f) Display the details of all FD which started in
Ans. (a) Crate table Bank ( the year 2018.

AccNo Int(4) Primary Key, (g) Display the details of all FD whose FD_Amount
is in the range 40000 to 50000.
Cust_Name Varchar(15),
Ans. (a) Select * from Bank where Int_rate is not NULL;
FD_Amount int, (b) Select distinct(FD_Amount) from Bank;
(c) Select distinct(Months) from Bank;
Months int(3), (d) Select cust name FD Amount from Bank where

Int_Rate decimal(5,2), Months < > 36
(e) Select cust_name, Fd_Amount from Bank where
FD_Date date );
Fd_Amount<500000 and Int_rate >7.00;
(b) Desc Bank; (f) Select * from Bank where year(FD_Date)=2018;
(g) Select * from Bank where FD_Amount IN
(c) Select * from Bank;
(40000,50000);
(d) SelectAccNo,Cust_Name, FD_Amount from Bank;
37. Write SQL commands for the statements (a) to (h)
(e) Select * from Bank where Months < 40 on the table Bank

(f) Select Acc_No, FD_Amount from Bank where (a) D isplay the details of all FD whose rate of interest
FD_Date<’2018-04-01’; is in the range 6% to 7%.

(g) Select * from Bank where Int_rate is NULL; (b) Display the Customer Name and FD Amount for
all the loans for which the number of Months is
36. Write SQL commands for the statements (a) to (g) 24, 36, or 48(using IN operator).
on the table BANK

(a) Display details of all the FD whose rate of interest
is NOT NULL.

148 Together with®  Computer Science (Python)—12

(c) D isplay the Account Number, Customer Name and FD Amount for all the FD for which the Customer Name
ends with “Sharma”.

(d) Delete the records of “Rupinder Kaur”.
(e) Add another column Maturity_Amt of type Integer in the Bank table.
(f) T o find the average FD amount. Label the column as “Average FD Amount”.
(g) To find the total FD amount which started in the year 2018?
(h) Update Maturity Amount of all bank customers.
a. Maturity Amount = (FD_Amount*Months* Int_rate)/(12*100)

Ans. (a) Select * from bank where Int_rate>=6.00 and FD_Amount<=7.00;

(b) Select cust_name,FD_Amount from Bank where Months in(36,42,48);

(c) Select AccNo, cust_name, Fd_Amount from bank where cust_name like ‘%Sharma’;

(d) Delete from Bank where cust_name=’Rupinder Kaur’;

(e) Alter table bank add Maturity_Amt int:

(f) Select avg(FD_Amount)”Average FD Amount” from bank;

(g) Select sum(FD_Int) from bank where year(FD_Date)=2018;

(h) Update Bank set Maturity_amt = ((FD_Amount)*Months*Int_rate)/(12*100);

(Q-38 to Q-39) Consider the following table Student & Stream.

Table: Student

Admno Sname Class Sec Fee Mobile Area S_ID

1001 RAMESH XII A 2500 987654321 Madipur 10

1078 KRISHNA XII B 2400 999911111 Jawala Heri 30

1006 FARDEEN XII C 2600 987654321 Paschim Puri 40

1004 SUBHAM XII A 2500 963025874 Madipur 20

1029 KRITIKA XI C 2700 987456210 Madipur 30

1008 SAMEEKSHA XII A 2450 987123456 Mangol Puri 20

1025 SALMA XII B 2580 998877445 Madipur 30

1036 AMANDEEP XII B 2600 999333555 Khyala 40

1037 TEJAS XI C 2650 987951357 Paschim Puri 40

1029 HIMANSHU XII A 2750 951369874 Jawala Heri 10

S_ID Table : Stream
10 Stream_name
20 MEDILCAL
30 NON MEDICAL
40 COMMERCE WITH MATH
50 COMMERCE WITH IP
HUMANITIES

Data Management – Sql 149

38. Write SQL commands for the statements (a) to (h) (c) Display all the student details who have taken
on the above table: Student and Stream Commerce Stream.

(a) Identify Primary Keys and Foreign Key in the (d) Count number of students who have opted for
table student and primary key in Stream table HUMANITIES stream.
given above.
(e) Display information of commerce with ip stu-
(b) Display stream id and stream-wise total fee dents whose name start with ‘S’. Arrange the
collected. record by admission number.

(c) Count no of students from each area. (f) Display details of all students who are in the
(d) Display all the student details those who belongs MEDICAL stream.

to Madipur Area. (g) Display total fee of ‘Non-Medical’ Student.
(e) Increase the fees of all students by10%. (h) Change the name of the Column Sname to Stu-
(f) Display unique area from the student table.
(g) Display details of those students whose area dent_Name.
Ans. (a) Select Class, Sum(Class) from Student group by
contains ‘Puri’.
(h) Display the information of those students who Class;
(b) Select admno, sname, stream_name from student,
are in class XII and section is either B or C.
Ans. (a) STUDENT Table : ADMNO Primary Key, stream where student.s_id=steam.s_id;
Foreign Key S_ID OR
STREAM Table : S_ID Primary Key
(b) Select s_id, sum(Fee) from student group by s_id; Select admno, sname, stream_name from student
(c) Select area, count(area) from student group by area; s1, steam s2 where s1.s_id = s2.s_id;
(d) Select * from student where area='Madipur';
(e) Update student set fee = fee+(fee*10)/100; (c) Select * from student, stream where student.s_id =
(f) Select distinct(Area) from student; stream.S_id and stream_name like ‘COMMERCE%’;
(g) Select * from student where Area like '%puri';
(h) Select * from student where Class = ‘XII and Sec (d) Select count(Stream_Name) from student, stream
where student.s_id=stream.s_id and stream_name
in('B','C'); = ‘HUMANITIES’;

39. Write SQL commands for the statements (a) to (h) (e) Select admno, sname, Class, Sec, Fee, Mobile,
on the table: Student and Stream Area, Student.S_ID, Stream_Name from student,
Stream where Student.S_ID = Stream.S_ID and
(a) Display class and total fee collected from each Sname like ‘S%’ order by admno asc,;
class.
(f) Select * from student, stream where student.s_id
(b) Display admission no, students name and stream and stream_name=‘Medical’;
name.
(g) Select sum(Fee) from Student, Stream where
40. Given the following relation: STUDENT Student.S_ID=Stream.S_id and Stream_name =
‘NON MEDICAL’.

(h) Alter table student change Student_Name
varchar(20);

Table: STUDENT

No. Name Age Department Dateofadm Fee Sex
10/01/97 120 M
1 Pankaj 24 Computer 24/03/98 200 F
12/12/96 300 M
2 Shalini 21 History 01/07/99 400 F
05/09/97 250 M
3 Sanjay 22 Hindi 27/06/98 300 M
25/02/97 210 M
4 Sudha 25 History 31/07/97 200 F

5 Rakesh 22 Hindi

6 Shakeel 30 History

7 Surya 34 Computer

8 Shikha 23 Hindi

150 Together with®  Computer Science (Python)—12

Write SQL commands for the following queries (d) To display all CNO,CNAME and DOT (date of
(a) To show all information about the students of transaction) of those CUSTOMERS from tables
CUSTOMERS and TRANSACTION who have
History department. done transactions more than or equal to 2000.
(b) To list the names of female students who are in
(e) S e l e c t c o u n t ( * ) , a v g ( a m o u n t ) f r o m
Hindi department. transaction where dot>= ‘2017-06-01’;
(c) To list the names of all students with their date
(f) Select cno, count(*), max (amount) from
of admission in ascending order. transaction group by cno having count(*)> 1;
(d) To display student’s name, fee, age for male
(g) Select cno, cname from customer where address
students only. not in (‘Delhi, ‘Bangalore’);
(e) To count the number of students with Age>23.
Ans. (a) Select * from student where department = “history”; (h) Select distinct cno from transaction;
Ans. (a) select * from TRANSACTION where type=’Credit’;
(b) Select * from student where department = “hindi”
and sex=’f’; (b) selectC NO,Amount from Transaction where
month(DOT)=09 and year(DOT)=2017;
(c) Select * from student order by dateofadm;
(c) select Max(DOT) from Transaction where
(d) Select name, fee, age from student where sex=“m”; CNO=103;

(e) Select count(*) from student age>23; (d) selectc ustomer.cno, cname, dot from c u s t o m e r,
transaction where customer.cno = transaction.cno
41. Write SOL queries for (i) to (iv) and find outputs and amount>=2000;

for SQL queries (v) to (viii) which are based on the (e) +----------+-------------+
| COUNT(*) | AVG(AMOUNT) |
tables. [Delhi Compt 2018-19] +----------+-------------+
|4 | 4375.0000 |
TABLE : CUSTOMERS +----------+-------------+

NO CNAME ADDRESS (f) +------+----------+-------------+
| CNO | COUNT(*) | MAX(AMOUNT) |
101 Richa jain Delhi +------+----------+-------------+
| 101 | 2 | 1500 |
101 Surbhi Sinha Chennai | 103 | 2 | 12000 |
+------+----------+-------------+
103 Lisa Thomas Bangalore (g) +------+--------------+
| CNO | CNAME |
104 Imran Ali Delhi +------+--------------+
105 Roshan Singh Chennai | 102 | Surbhi Sinha |
| 103 | Lisa Thomas |
TABLE : TRANSACTION | 105 | Roshan Singh |
+------+--------------+
TRNO CNO AMOUNT TYPE DOT (h) +------+
T001 101 1500 Credit 2017-11-23 | CNO |
T002 103 2000 Debit 2017-05-12 +------+
T003 102 3000 Credit 2017-06-10 | 101 |
T004 103 12000 Credit 2017-09-12 | 103 |
T004 101 1000 Debit 2017-09-05 | 102 |
+------+
(a) To display details of all transactions of TYPE
Credit from Table TRANSACTION.

(b) To display the CNO and AMOUNT of all
transactions done in the month September 2017
from the table TRANSACTION.

(c) To display the last date of transaction (DOT)
from the table TRANSACTION for the customer
having CNO as 103.

Data Management – Sql 151

42. Write SQL queries for (i) to (iv) and find outputs (g) +------+----------+-------------+---------------------+
| CODE | NAME | ITCODE |
for SQL queries (v) to (viii), which are based on the --------+------+----------+--------------+----------------+
| 1001 | SANDEEP JHA | I2|
tables: [CBSE Comptt. 2018] +------+----------+-------------+------------------------+

TABLE: SALESPERSON

CODE NAME SALARY ITCODE (h) (i) +----------- +
1001 TANDEEP JHA 60000 I2 | SALARY|
1002 YOGRAJ SINHA 70000 I5 +----------- +
1003 TENZIN JACK 45000 I2 | 60000 |
1005 ANOKHI RAJ 50000 I7 +-----------+
1004 TARANA SEN 55000 I7
43. Write SQL queries for (i) to (iv) and find outputs

TABLE: ITEM for SQL queries (v) to (vii), which are based on the

tables. [Sample Paper 2018]

ITCODE ITEMTYPE TURNOVER Table: Trainer
I5 STATIONARY 3400000
I7 HOISTERY 6500000 TID Tname City HireDate Salary
I2 BAKERY 10090000
101 Sunaina Mumbai 1998-10-15 90000

(a) To display the CODE and NAME of all sales- 102 Anamika Delhi 1994-12-24 80000
person having “I7” item Type Code from the
table SALESPERSON. 103 Deepti Chandigarh 2001-12-21 82000

(b) To display all details from table SALES- 104 Meenakshi Delhi 2002-12-25 78000
PERSON in descending order of SALARY.
105 Richa Mumbai 1996-01-12 95000
(c) To display the numberof SALESPERSON dealing
in each TYPE of ITEM.(Use ITCODE for the same) 106 Maniprabha Chennai 2001-12-12 69000

(d) To display NAME of all the salesperson table Table: Course
along with their corresponding ITEMTYPE
from the ITEM table. CID CNAME FEES STARTDATE TID

(e) Select max(salary) from salesperson; C201 AGDCA 12000 2018-07-02 101
(f) Select distinct itcode from salesperson;
(g) select code,name,i.itcode from sales person C202 ADCA 15000 2018-07-15 103

s, item i where s.itcode=i.itcode and turn- C203 DCA 10000 2018-10-01 102
over>=7000000;
(h) Select sum (salary)from salesperson where it- C203 DDTP 9000 2018-09-15 104
code=”i2”;
Ans. (a) Select CODE, NAME from Salesperson where C205 DHN 20000 2018-08-01 101
ITCODE=”I7”;
C206 O LEVEL 18000 2018-07-25 105

(b) Select * from Salesperson order by salary desc; (a) Display the Trainer Name, City and Salary in
descending order of their hire date.
(c) Select Type, count(*) from Salesperson group by
type; (b) To display the TNAME and CITY of Trainer of
joined the institute in the month of December2001.
(d) Select NAME from Salesperson, Item where
SALESPERSON.ITOCDE=ITEM.ITCODE; (c) To display TNAME, HIREDATE,CNAME,
STARTDATE from tables TRAINER and
(e) 70000 COURSE whose FEES is less than or equal to
10000
(f) +----------- +
(d) To display number of trainer from each city
| ITCODE | (e) select tid, tname,from trainer where city not

+----------- + in(‘delhi’,’mumbai’);
(f) select distinct tid from course;
| I2 | (g) select tid , count (*), min(fees) from course

| I5 | group by tid having count(*)>1;
(h) Select count(*),sum(fees) from course where
| I7 |
startdate <’2018-09-15’;
Ans. (a) select t name, city, salary from trainer order

by hiredate;

+-----------+

152 Together with®  Computer Science (Python)—12

(b) Select tname, city from trainer where hiredate (a) To display all the details of those watches whose
between ‘2001-12-01’ and ‘2001-12-31’; name ends with ‘time’

OR (b) To display watch’s name andprice of those
watches which have price range between 5000-
Select tname, city from trainer where hiredate >= 15000
‘2001-12-01’ and hiredate<=‘2001-12-31’;
(c) To display total quantity in store of unisex type
OR watches

Select tname, city from trainer where hiredate like (d) To display watch name and their quantity sold
‘2001-12%’; in first quarter

(c) Select t name, hiredate, cname, startdate (e) Select max(price),min(qty_store) from watches;
from trainer, course where trainer.tid=course.tid (f) Select quarter, sum(qty_sold) from sale group
and fees<=10000;
by quarter;
(d) Select city, count(*) from trainer group by city; (g) Select watch_name,price,type from watches w,

(e) Select tid, tname, from trainer where city not sale s where w.watchid=s.watchid;
in(‘delhi’, ‘mumbai’); (h) Select watch_name, qty_store, sum(qty_

(f) Distinct tid sold),qty_store
(i) W.watch=s.watchid group by s.watchid;
101 Ans. (a) select * from watches where watch_name like
103
102 ‘%TIME’;
104
105 (b) select Watch_name, Price from Watches where
price between 5000 and 15000;
(g) tid count(*) min(fees)
OR
101 2 12000

(h) count(*) sum(fees) Select Watch_name, Price from Watches where
Price>=5000 and Price<=15000;
4 65000

44. Write SQL queries for (a) to (d) and find outputs (c) S e l e c t s u m ( P r i c e ) f r o m Wa t c h e s w h e r e
Type=’UNISEX’;
for SQL queries (e) to (i), which are based on the
(d) Select Watch_name, Qty_sold from Watches, Sale
tables. [Sample Paper 2016-17] where Watches. Watchid = Sale. Watchid and
Quarter = 1;
TABLE: WATCHES

Watchid Watch_name Price Type Qty_store (e) Max(Price) Min(Qty_store)

W001 High time 10000 Unisex 100 25000 100
W002 Life time 15000 Ladies 150
W003 Wave 20000 Gents 200 (f  ) quarter sum(qty_sold)
W004 High fashion 7000 Unisex 250 1 15
2 30
W005 Golden time 25000 Gents 100 3 45
4 15
TABLE: SALE

Watchid Qty_Sold Quarter (g ) watch_name price type
W001 10 1 HighFashion 7000 Unisex
W003 5 1
W002 20 2 (h ) watch_name qty_store qty_sold Stock
W003 10 2
W001 15 3 HighTime 100 25 75
W002 20 3
W005 10 3 LifeTime 150 40 110
W003 15 4
Wave 200 30 170

GoldenTime 100 10 900

Data Management – Sql 153

Practice Questions

Very Short Answer Type Questions [1 Mark] Table: Employees
1. Write the full form of SQL.
2. A table course has its degree as 7 and cardinality as 18. EMPID FIRST LAST ADDRESS city
010 NAME NAME
Write the number rows and columns in the table. 105 George Smith 83 First Howard
3. Name the two wild card characters. 152 Losantiville
Mary Jones Street
842 Vine
Short Answer Type Questions [2/3 Marks]
Ave.

4. What is an Alternate Key? Sam Tones 33 Elm St. Paris

5. Write the full form of DDL and DML? 215 Sarah Ackerman 440 U.S. 110 Upton

6. Differentiate between the terms primary key and alternate 244 Manila Sengupta 24 Friends New Delhi
key. Street

7. What is the importance of a Primary Key in a table? 300 Robert Samuel 9 Fifth Cross Washington
Explain with a suitable example.
335 Henry Williams 12 Moore Boston
8. Differentiate between Candidate Key and Primary Key Street
in context of RDBMS.
400 Rachel Lee 121 Harrison New York
St.
9. Differentiate between Candidate Key and Alternate Key
in context of RDBMS. 441 Peter Thompson 11 Red Road Paris

10. Differentiate between DDL & DMLcommands. Identify Table: EMPSalary
DDL & DML commands from the following:
EMPID SALARY BENEFITS DESIGNATION

(UPDATE, SELECT, ALTER, DROP) 010 75000 15000 Manager

11. What are candidate keys in a table? Give a suitable 105 65000 15000 Manager
example of candidate keys in a table.
152 80000 25000 Director

12. Observe the following table and answer the parts 215 75000 12500 Manager
(i) and (ii) accordingly
244 50000 12000 Clerk

Table: Product 300 45000 10000 Clerk

Pno Name Qty PurchaseDate 355 40000 10000 Clerk

101 Pen 102 12-12-2011 4000 32000 7500 Salesman

102 Pencil 201 21-02-2013 441 28000 7500 Salesman

103 Eraser 90 09-08-2010 Write the SQL commands for the following :
(i) To show firstname, lastname, address and city of
109 Sharpener 90 31-08-2012
all employees living in paris.
113 Clips 900 12-12-2011 (ii) To display the content of Employees table in

(a) Write the names of most appropriate columns, ascending order of Firstname.
which can be considered as candidate keys. (iii) To display the firstname,lastname and total salary

(b) What is the degree and cardinality of the above of all managers from the tables employee and
table? empsalary, where total salary is calculated as
salary+benefits.
13. Differentiate between cardinality and degree of a table (iv) To display the maximum salary among managers
with the help of an example. and clerks from the table Empsalary.
Give the Output of following SQL commands:
Long Answer Type Questions [4 Marks] (v) Select firstname, salary from employees, empsalary
where designation = ‘Salesman’ and Employees.
14. Write the SQL query questions from (i) to (iv) and write empid=Empsalary.empid;
the output of SQL command for questions from (v) to (vi) Select count(distinct designation) from empsalary;
(vii) given below: (vii) Select designation, sum(salary) from empsalary
group by designation having count(*) >2;

154 Together with®  Computer Science (Python)—12

15. Consider the following tables Product and Client. Write SQL commands for the statements (i) to (iv) and give outputs
for SQL queries (v) to (viii)

TABLE: PRODUCT TABLE: CLIENT

P_ID Product Name Manufacturer Price C_ID ClientName City P_ID

TP01 Talcom Powder LAK 40 01 Cosmetic Shop Delhi FW05
ABC 45 06 Total Health Mumbai BS01
FW05 FaceWash ABC 55 12 Live Life SH06
BS01 Bath Soap XYZ 120 15 Pretty Woman Delhi FW12
16 Dreams Delhi TP01
SH06 Shampoo XYZ 95 Bangalore

FW12 Face Wash

(i) To display the details of those Clients whose City is Delhi
(ii) To display the details of Products whose Price is in the range of 50 to 100 (Both values included)
(iii) To display the ClientName, City from Table Client, and ProductName and Price from table Product, with their

corresponding matching P_ID
(iv) To increase the Price of all Products by 10
(v) SELECT DISTINCT CITY FROM Client;
(vi) SELECT Manufacturer, MAX(Price), Min(Price), Count(*) FROM Product GROUP BY Manufacturer;
(vii) SELECT ClientName, ManufacturerName FROM Product, Client WHERE Client.Prod_Id = Product.P_Id;
16. Write SQL commands for the following queries based on the relation Teacher given below:

Table: Teacher

No Name Age Department Date_of_join Salary Sex

1 Jugal 34 Computer 10/01/97 12000 M

2 Sharmila 31 History 24/03/98 20000 F

3 Sandeep 32 Maths 12/12/96 30000 M

4 Sangeeta 35 History 01/07/99 40000 F

5 Rakesh 42 Maths 05/09/97 25000 M

6 Shyam 50 History 27/06/98 30000 M

7 Shiv Om 44 Computer 25/02/97 21000 M

8 Shalakha 33 Maths 31/07/97 20000 F

(a) To show all information about the teacher of Computer department.
(b) To list the names of female teachers who are in Maths department.
(c) To list the names of all teachers with their date of joining in ascending order.
(d) To display teacher’s name, salary, age for male teachers only.
(e) To count the number of teachers with Age>23.

Data Management – Sql 155

17. Write SQL commands for the following queries on the basis of Club relation given below:
Relation: Club

Coach-ID CoachName Age Sports date_of_app Pay Sex

1 Kukreja 35 Karate 27/03/1996 1000 M

2 Ravina 34 Karate 20/01/1998 1200 F

3 Karan 34 Squash 19/02/1998 2000 M

4 Tarun 33 Basketball 01/01/1998 1500 M

5 Zubin 36 Swimming 12/01/1998 750 M

6 Ketaki 36 Swimming 24/02/1998 800 F

7 Ankita 39 Squash 20/02/1998 2200 F

8 Zareen 37 Karate 22/02/1998 1100 F

9 Kush 41 Swimming 13/01/1998 900 M

10 Shailya 37 Basketball 19/02/1998 1700 M

(a) To show all information about the swimming coaches in the club.
(b) To list the names of all coaches with their date of appointment (date_of_app) in descending order.
(c) To display a report showing coach name, pay, age, and bonus (15% of pay) for all coaches.
(d) To insert a new row in the Club table with ANY relevant data:
(e) Give the output of the following SQL statements:
(i) Select COUNT(Distinct Sports) from Club;
(ii) Select Min(Age) from Club where SEX = “F”;
18. Write SQL commands for (a) to (f) and write the outputs for (g) on the basis of tables FURNITURE and ARRIVALS

Table: FURNITURE

NO ITEMNAME TYPE DATEOFSTOCK PRICE DISCOUNT
1 White lotus Double Bed 23/02/2002 30000 25
2 Pink feather Baby cot 20/01/2002 7000 20
3 Dolphin Baby cot 19/02/2002 9500 20
4 Decent Office Table 01/01/2002 25000 30
5 Comfort zone Double Bed 12/01/2002 25000 25
6 Donald Baby cot 24/02/2002 6500 15
7 Royal Finish Office Table 20/02/2002 18000 30
8 Royal tiger Sofa 22/02/2002 31000 30
9 Econo sitting Sofa 13/12/2001 9500 25
10 Eating Paradise Dining Table 19/02/2002 11500 25

Table: ARRIVALS

NO ITEMNAME TYPE DATEOFSTOCK PRICE DISCOUNT

1 Wood Double 23/03/2003 25000 25
Comfort Bed 20/02/2003 17000 20
Sofa 21/02/2003 7500 15
2 Old Fox
Baby cot
3 Micky

156 Together with®  Computer Science (Python)—12

(a) To show all information about the Baby cots from Relation: PLAYER
the FURNITURE table.
PCode Name Gcode
(b) To list the ITEMNAME which are priced at more
than 15000 from the FURNITURE table. 1 Nabi Ahmad 101

(c) To list ITEMNAME and TYPE of those items, 2 Ravi Sahai 108
in which date of stock is before 22/01/2002 from
the FURNITURE table in descending order of 3 Jatin 101
ITEMNAME.
4 Nazneen 103
(d) To display ITEMNAME and DATEOFSTOCK of
those items, in which the discount t percentage is (a) To display the name of all Games with their Gcodes
more than 25 from FURNITURE table.
(b) To display details of those games which are having
(e) To count the number of items, whose TYPE is PrizeMoney more than 7000.
“Sofa” from FURNITURE table.
(c) To display the content of the GAMES table in
(f) To insert a new row in the ARRIVALS table with ascending order of ScheduleDate.
the following data:
(d) To display sum of PrizeMoney for each of the
14,“Valvet touch”, “Double bed”, {25/03/03}, Number of participation groupings (as shown in
25000,30 column Number)

(g) Give the output of following SQL statement (e1) Select COUNT(DISTINCT Number) FROM
GAMES;
Note: Outputs of the above mentioned queries should
be based on original data given in both the tables i.e., (e2) Select MAX(ScheduleDate),MIN(ScheduleDate)
without considering the insertion done in (f) part of this FROM GAMES;
question.
(e3) Select SUM(PrizeMoney) FROM GAMES;
(i) Select COUNT(distinct TYPE) from FURNITURE;
(e4) Select DISTINCT Gcode FROM PLAYER;
(ii) Select MAX(DISCOUNT) from FURNITURE,
ARRIVALS; 20. Consider the following tables WORKER and PAYLEVEL
and answer (a) and (b) parts of this question:
(iii) Select AVG(DISCOUNT) from FURNITURE
where TYPE=”Baby cot”; [Delhi 2011]

(iv) Select SUM(Price) from FURNITURE where Relation: WORKER
DATEOFSTOCK<12/02/02;
ECODE NAME DESIG PAYLEVEL DOJ DOB
19. Consider the following tables GAMES and PLAYER.
Write SQL commands for the statements (a) to (d) and 11 Radhey Supervisor P001 13-Sep- 23-Aug-
give outputs for SQL queries (e1) to (e4) Shyam 2004 1981

Relation: GAMES 12 Chander Operator P003 22-Feb- 12-Jul-
Nath 2010 1987

Game Prize Schedule 13 Fizza Operator P003 14-June- 14-Oct-
Name Money Date 2009 1983
GCode Number
Ameen 21-Aug- 13-Mar-
Carom 15 Ahmed Mechanic P002 2006 1984
Board
101 2 5000 23-Jan-2004

18 Sanya Clerk P002 19-Dec- 09-June-
2005 1983
102 Badminton 2 12000 12-Dec-2003

Table Relation: PAYLEVEL
Tennis
103 4 8000 14-Feb-2004 PAYLEVEL PAY ALLOWANCE
P001 26000 12000
105 Chess 2 9000 01-Jan-2004 P002 22000 10000
P003 12000 6000
108 Lawn 4 25000 19-Mar-2004
Tennis

Data Management – Sql 157

(a) Write SQL commands for the following statements: (a) Write SQL commands for the following statements:

(i) To display the details of all WORKERs in (i) To display the names of all white colored
descending order of DOB. vehicles

(ii) To display NAME and DESIG of those (ii) To display name of vehicle, make and
WORKERs whose PLEVEL is either P001 capacity of vehicles in ascending order of
or P002. their sitting capacity

(iii) To display the content of all the WORKERs (iii) To display the highest charges at which a
table, whose DOB is in between ’19-JAN- vehicle can be hired from CARHUB.
1984’ and ’18-JAN-1987’.
(iv) To display the customer name and the
(iv) To add a new row with the following: corresponding name of the vehicle hired by
them.
19, ‘Daya kishore’, ‘Operator’, ‘P003’, ’19-
Jun-2008’, ’11-Jul-1984’ (b) Give the output of the following SQL queries:

(b) Give the output of the following SQL queries: (i) Select count(distinct make) from cabhub;

(i) Select count(plevel), plevel from worker (Ii) Select max(charges), min(charges) from
group by plevel; carhub;

(ii) Select max(dob), min(doj) from worker; (Iii) Select count(*), make from carhub;

(iii) Select name, pay from worker w, paylevel (Iv) Select vehiclename from carhub where
p where w.plevel=p.plevel and w.ecode<13; capacity = 4;

(iv) Select plevel, pay+allowance from paylevel 22. Write SQL queries for (a) to (f) and write the outputs
where plevel=’ p003’; for the SQL queries mentioned shown in (g1) to (g4)
parts on the basis of tables ITEMS and TRADERS:
21. Consider the following tables CARHUB and CUSTOMER [Delhi 2013]
and answer (a) and (b) parts of this question: Table: ITEMS

CODE INAME QTY PRICE COMPANY TCODE
T01
[Delhi 2012] DIGITAL T02
1001
Table: CARHUB 120 11000 XENITA
PAD 12i

Vcode Vehicle Make Color Capacity Charges 1006 LED 70 38000 SANTORA
Name
SCREEN 40

100 Innova Toyota WHITE 7 15 1004 CAR GPS 50 21500 GEOKNOW T01
4 14 SYSTEM T02
4 35 T03
102 SX4 Suzuki BLUE 3 14 DIGITAL
3 12 1003 CAMERA
104 C Class Mercedes RED 160 8000 DIGICLICK
VCode 12X
101
105 A-Star Suzuki WHITE 108 1005 PEN DRIVE 600 1200 STOREHOME
105 32GB
108 Indigo Tata SILVER 104

CCode Table: CUSTOMER TCode Table: TRADERS CITY
1 CName T01 MUMBAI
2 T03 TName
3 Hemant Sahu T02 DELHI
4 Raj Lal ELECTRONIC CHENNAI
SALES
Feroza Shah BUSY STORE
Ketan Dhal CORP
DISP HOUSE
INC

158 Together with®  Computer Science (Python)—12

(a) To display the details of all the items in the ascending T04 Mouse 300 S01
order of item names (i.e. INAME).

(b) To display item name and price of all those items, T05 Mother Board 13000 S02
whose price is in range of 10000 and 22000 (both
values inclusive). T06 Key Board 400 S03

(c) To display the number of items, which are traded T07 LCD 6000 S04
by each trader. The expected output of this query
should be: T08 LCD 5500 S05

T01 2 T09 Mouse 350 S05

T02 2 T10 Hard disk 4500 S03

T03 1 (a) Write the SQL queries (1 to 4):

(d) To display the price, item name and quantity (i.e. (i) To display IName and Price of all the items
qty) of those items which have quantity more than in the ascending order of their Price.
150.

(e) To display the names of those traders, who are (ii) To display the SNo and SName or all stores
either from DELHI or from MUMBAI. located in CP.

(f) To display the names of the companies and the names (iii) To display the minimum and maximum price
of the items in descending order of company names. of each IName from the table Item.

(g1) Select max(price), min(price) from items; (iv) To display the IName, price of all items
and their respective SName where they are
(g2) Select price*qty amount from items where available.
code=1004;

(g3) Select distinct tcode from items; (b) Write the output of the following SQL commands
(i) to (iv):
(g4) Select iname, tname from items i, traders t where
i.tcode=t.tcode and qty<100; (i) Select distinct iname from item where price
>= 5000;
23. Answer the (a) and (b) on the basis of the following

tables STORE and ITEM: [Delhi 2014] (ii) Select area, count(*) from store group by
area;
Table: STORE

SNo SName AREA (iii) Select count(distinct area) from store;

S01 ABC Computronics GK II (iv) Select iname, price*0.05 discount from item
where sno in (‘s02’, ‘s03’);

S02 All Infotech Media CP 24. Consider the following DEPT and WORKER tables.

Write SQL queries for ( i) to (iv) and find outputs for

S03 Tech Shoppe Nehru Place SQL queries (v) to (viii): [Delhi 2015]

S05 Hitech Tech Store CP Table: DEPT

DCODE DEPARTMENT CITY

Table: ITEM D01 MEDIA DELHI
INo IName Price SNo
D02 MARKETING DELHI
T01 Mother Board 12000 S01 D03 INFRASTRUCTURE MUMBAI

T02 Hard Disk 5000 S01 D05 FINANCE KOLKATA

T03 Keyboard 500 S02 D04 HUMAN RESOURCE MUMBAI

Data Management – Sql 159

Table: WORKER

WNO NAME DOJ DOB GENDER DCODE

1001 George K 2013-09-02 1991-09-01 MALE D01

1002 Ryma Sen 2012-12-11 1990-12-15 FEMALE D03
1003 Mohitesh 2013-02-03 1987-09-04 MALE D05
1007 Anil Jha 2014-01-17 1984-10-19 MALE D04

1004 Manila Sahai 2012-12-09 1986-11-14 FEMALE D01
1005 R SAHAY 2013-11-18 1987-03-31 MALE D02
1006 Jaya Priya 2014-06-09 1985-06-23 D05
FEMALE

Note: DOJ refers to date of joining and DOB refers to date of Birth of workers.

(i) To display Wno, Name, Gender from the table WORKER in descending order of Wno.

(ii) To display the Name of all the FEMALE workers from the table WORKER.

(iii) To display the Wno and Name of those workers from the table WORKER who are born between ‘1987-01-01’
and ‘1991-12-01’.

(iv) To count and display MALE workers who have joined after ‘1986-01-01’.

(v) SELECT COUNT(*), DCODE FROM WORKER GROUP BY DCODE HAVING COUNT(*)>1;

(vi) SELECT DISTINCT DEPARTMENT FROM DEPT;

(vii) SELECT NAME, DEPARTMENT, CITY FROM WORKER W,DEPT D WHERE W.DCODE=D.DCODE AND
WNO<1003;

(viii) SELECT MAX(DOJ), MIN(DOB) FROM WORKER;

25. Consider the following DEPT and EMPLOYEE tables. Write SQL queries for (i) to (iv) and find outputs for SQL queries

(v) to (viii). [AI 2015]

Table: DEPT

DCODE DEPARTMENT LOCATION

D01 INFRASTRUCTURE DELHI

D02 MARKETING DELHI

D03 MEDIA MUMBAI

D05 FINANCE KOLKATA

D04 HUMAN RESOURCE MUMBAI

Table: EMPLOYEE

ENO NAME DOJ DOB GENDER DCODE
D01
1001 George K 2013-09-02 1991-09-01 MALE D03
D05
1002 Ryma Sen 2012-12-11 1990-12-15 FEMALE D04
D01
1003 Mohitesh 2013-02-03 1987-09-04 MALE D02
D05
1007 Anil Jha 2014-01-17 1984-10-19 MALE

1004 Manila Sahai 2012-12-09 1986-11-14 FEMALE

1005 R SAHAY 2013-11-18 1987-03-31 MALE

1006 Jaya Priya 2014-06-09 1985-06-23 FEMALE

Note: DOJ refers to date of joining and DOB refers to date of Birth of employees.

160 Together with®  Computer Science (Python)—12

(i) To display Eno, Name, Gender from the table Table: TRAVEL
EMPLOYEE in ascending order of Eno.
NO NAME TDATE KM CODE NOP
(ii) To display the Name of all the MALE employees 101 Janish Kin 2015-11-13 200 101 32
from the table EMPLOYEE. 103 Vedika sahai 2016-04-21 100 103 45
105 Tarun Ram 2016-03-23 350 102 42
(iii) To display the Eno and Name of those employees 102 John Fen 2016-02-13 90 102 40
from the table EMPLOYEE who a born between
‘1987‐01‐01’ and ‘1991‐12‐01’. 107 AhmedKhan 2015-01-10 75 104 2

(iv) To count and display FEMALE employees who 104 Raveena 2015-05-28 80 105 4
have joined after ‘1986‐01‐01’.
106 Kripal Anya 2016-02-06 200 101 25
(v) Select count(*),dcode from employee group by
dcode having count(*)>1; Note:

(vi) Select distinct department from dept; • NO is Traveller Number

(vii) Select name, department from employee e, dept • KM is Kilometer travelled
d where e.dcode=d.dcode and en0<1003;
• NOP is number of travellers travelled in vehicle
(viii) select max(doj), min(dob) from employee;
• TDATE is Travel Date
26. Write SQL queries for (i) to (iv) and find outputs for
SQL queries (v) to (viii), which are based on the tables. (i) To display NO, NAME, TDATE from the table
[Delhi 2016] TRAVEL in descending order of NO.

Table: VEHICLE (ii) To display the NAME of all the travellers from
the table TRAVEL who are travelling by vehicle
Code VTYPE PERKM with code 101 or 102.

101 VOLVO BUS 160 (iii) To display the NO and NAME of those travellers
from the table TRAVEL who travelled between
102 AC DELUXE BUS 150 ‘2015-12-31’ and ‘2015-04-01’.

103 ORDINARY BUS 90 (iv) To display all the details from table TRAVEL
for the travellers, who have travelled distance
105 SUV 40 more than 100 KM in ascending order of NOP.

104 CAR 20 (v) SELECT COUNT (*), CODE FROM TRAVEL
GROUP BY CODE HAVING COUNT(*)>1;
Note:
• PERKM is Freight Charges per kilometer (vi) SELECT DISTINCT CODE FROM TRAVEL;
• VTYPE is Vehicle Type
(vii) SELECT A.CODE,NAME,VTYPE FROM
TRAVEL A,VEHICLE B WHERE A.CODE=B.
CODE AND KM<90;

(viii) SELECT NAME,KM*PERKM FROM TRAVEL
A, VEHICLE B WHERE A.CODE=B.CODE
AND A.CODE=‘105’;

ANSWERs TO Practice Questions

1. Structured Query Language. 5. DDL – Data Definition Language

2. Rows=18 DML – Data Manipulation Language

Columns=7 6. Primary Key: An attribute/ column used to identify each
record in a table
3. Two wild Card Characters are % (Percentage)
and _(Underscore). Alternate Key: All such attributes/columns, which can
act as a primary key but are not the primary key in a
4. Candidate key(s), which is not selected as Primary Key, table.
is known as Alternate key(s).

Data Management – Sql 161

7. The Primary Key is an attribute/set of attributes that 12. Candidate Key: Pno, Name
identifies a tuple/ row/ record uniquely. Degree:4
Cardinality:5
Example: 13. Cardinality is defined as the number of rows in a table.
Degree is the number of columns in a table.
Rollnumber in the table STUDENT Eg: Consider the following tables:
Supposing Table :Account contains 3 rows and 2 columns.
OR Cardinality of Account table is : 3
Degree of Account table is :2
AccessionNumber in the table LIBRARY 14. (i) Select FIRSTNAME, LASTNAME, ADDRESS,

OR CITY From EMPLOYEES
Where CITY= ‘Paris’;
EmpNumber in the table EMPLOYEE (ii) Select * From EMPLOYEES

OR

PanNumber in the table INCOMETAX OR

MemberNumber in the table MEMBER OR

AccNumber in the table BANK

8. Candidate Key: All such attributes/columns, which can
uniquely identify each row/record in a table

Primary Key: An attribute/column among the Candidate Order By FIRSTNAME;
Keys which is used to uniquely identify each row/record
in a table (iii) Select FIRSTNAME, LASTNAME, SALARY
+ BENEFITS "TOTAL SALARY" From
9. Candidate Key: It is the one that is capable of becoming EMPLOYEES, EMPSALARY
primary key i.e.,a column or set of columns that identifies
a row uniquely in the relation. Where EMPLOYEES.EMPID=EMPSALARY.
EMPID;
Alternate Key: A candidate key that is not selected as
a primary key is called an Alternate Key. (iv) Select Max(SALARY) From EMPSALARY

10. DDL stands for Data Definition language and comprises W h e r e D E S I G N AT I O N = ' M a n a g e r ' O R
of commands which will change the structure of database DESIGNATION = ‘Clerk’;
object.
(v) FIRSTNAME SALARY

DML stands for Data Manipulation Language and Rachel 32000
comprises of commands which are used to insert, edit,
view & delete the data stored in a database object. Peter 28000

DDL Commands are: ALTER, DROP (vi) COUNT (DISTINCT DESIGNATION)

DML Commands are: UPDATE, SELECT 4

11. A table may have more than one such attribute/group (vii) DESIGNATION SUM(SALARY)
of attribute that identifies a tuple uniquely, all such
attribute(s) are known as Candidate Keys. Manager 215000

Clerk 135000

Table: Item 15. (i) Select * from client where city=”Delhi”;

Ino Item Qty (ii) Select * from product where price between 50 and
100;
I01 Pen 560

I02 Pencil 780 (iii) Select a.clientname,a.city ,b.productname, b.price
from client a, product b where a.P_ID and b.P_ID;
I04 CD 450

I09 Floppy 700 (iv) Update product set price = price +10;

I05 Eraser 300

I03 Duster 200 (v) City

Banglore

  Candidate Keys Delhi

Mumbai

162 Together with®  Computer Science (Python)—12

(vi) Manufacturer MAX MIN Count(*) (g) (i) 5
(Price) (Price) (ii) 30
2 (iii) 18.33
ABC 65 55 2 (iv) 65500
50 2
LAK 50
105
XYZ 130 19. (a) SELECT GAMENAME, GCODE FROM GAMES;

(vii) Client Name Manufacturer (b) SELECT * FROM GAMES WHERE PRIZE
Total Health ABC MONEY > 7000;
Cosmetic Shop ABC
Pretty Woman XYZ ( c ) S E L E C T * F R O M G A M E S O R D E R B Y
XYZ SCHEDULEDATE;
Live Life
LAK (d) SELECT NUMBER, SUM(PRIZEMONEY)
Dreams FROM GAMES GROUP BY NUMBER;

(e1) COUNT (DISTINCT NUMBER)

16. (a) S E L E C T * F R O M T E A C H E R W H E R E 2
DEPARTMENT = “Computer”;
4
(b) SELECT NAME FROM TEACHER WHERE
DEPARTMENT = “Maths” AND SEX = “F”; (e2) MAX(ScheduleDate) MIN(ScheduleDate)

(c) SELECT NAME FROM TEACHER ORDER BY ----------------- -----------------
DATE_OF_JOIN;
19-Mar-2004 12-Dec-2003
(d) SELECT NAME, SALARY, AGE FROM
TEACHER WHERE SEX = “M”; (e3) SUM (Prize Money)
59000
(e) SELECT COUNT(*) FROM TEACHER WHERE
AGE>23; (e4) DISTINCT (GCODE)
101
17. (a) SELECT * FROM CLUB WHERE SPORTS = 108
“Swimming”; 103

(b) SELECT Name FROM CLUB ORDER BY date_ 20. (a) (i) SELECT * FROM WORKER ORDER BY
of_app desc; DOB DESC;

(c) SELECT COACHNAME, PAY, AGE, PAY*15/100 (ii) SELECT NAME, DESIG FROM WORKER
AS BONUS FROM CLUB; WHERE PLEVEL IN (“P001”, “P002”);

(d) INSERT INTO CLUB VALUES (11, “Neelam”, (iii) SELECT * FROM WORKER WHERE DOB
35, “Basketyball”, “2000/04/01”, 2200, “F”); BETWEEN “19-JAN-1984” AND “18- JAN-
1987”;
(e) (i) 4
(iv) INSERT INTO WORKER VALUES
(ii) 34
(19, ‘Daya kishore’, ‘Operator’, ‘P003’, ’19-
18. (a) SELECT * FROM FURNITURE WHERE TYPE Jun-2008’, ’11-Jul-1984’);
= “Baby cot”;
(b) (i) COUNT(PLEVEL) PLEVEL
(b) SELECT ITEMNAME FROM FURNITURE 1 P001
WHERE PRICE > 15000; 2 P002
2 P003
(c) SELECT ITEMNAME,TYPEFROMFURNITURE
WHERE DATEOFSTOCK<”2002/01/22” ORDER (ii) MAX(DOB)) MIN(DOJ)
BY ITEMNAME DESC; (iii) 12-Jul-1987 13-Sep-2004

(d) SELECT ITEMNAME, DATEOFSTOCK FROM Name Pay
FURNITURE WHERE DISCOUNT>25; Radhey Shyam 26000
Chander Nath 12000
(e) SELECT COUNT(*) FROM FURNITURE
WHERE TYPE=”Sofa”;

(f) INSERT INTO ARRIVAL VALUES (14, “Valvet
touch”, “Double bed”, “2003/03/03”);

Data Management – Sql 163

(iv) PLEVEL PAY+ALLOWANCE 23. (a) (i) SELECT IName, price from Item ORDER
P003 18000 BY Price;

21. (a) (i) Select vehiclename from carhub where color (ii) SELECT SNo, SName FROM Store WHERE
= ‘white’; Area=’CP’;

(ii) Select vehiclename, make, capacity from (iii) SELECT IName, MIN(Price), MAX(Price)
carhub order by capacity; FROM Item GROUP BY IName;

(iii) Select max(charges) from carhub; (iv) SELECT IName, Price, SName FROM Item,
Store Where Item.SNo =Store.SNo;
(iv) Select cname, vehiclename, from customer,
carhub where customer.vcode = carhub. (b) (i) DISTINCT INAME
vcode; Hard disk
LCD
(b) (i) Count(Distinct Make)
Mother Board
4

(ii) MAX(Charges) MIN(Charges) (ii) Area Count(*)
35 12 CP 2
GK II 1
(iii) Count(*) Nehru Place 2
5

(iv) Vehiclename (iii) COUNT(DISTINCT AREA)
SX4 3

C Class (iv) INAME PRICE
Keyboard 25
22. (a) SELECT * FROM ITEMS ORDER BY INAME; Mother Board 650
Hard Disk 225
(b) SELECT INAME, PRICE FROM ITEMS WHERE
PRICE BETWEEN 10000 AND 22000;

(c) SELECT TCODE, COUNT(*) FROM ITEMS 24. (i) SELECT Wno,Name,Gender FROM Worker
GROUP BY TCODE; ORDER BY Wno DESC;

(d) SELECT PRICE, INAME, QTY FROM ITEMS (ii) SELECT Name FROM Worker
WHERE QTY > 150;

(e) SELECT INAME FROM TRADERS WHERE   WHERE Gender=’FEMALE’;
CITY IN (‘DELHI’, ‘MUMBAI’);
(iii) SELECT Wno, Name FROM Worker

(f) SELECT COMPANY, INAME FROM ITEMS   WHERE DOB BETWEEN ‘1987-01-01’ AND
ORDER BY COMPANY DESC; ‘1991-12-01’;

(g1) MAX(PRICE) MIN(PRICE) OR

38000 1200 SELECT Wno, Name FROM Worker

(g2) AMOUNT   WHERE DOB >=‘1987-01-01’ AND DOB
(g3) 1075000 <=‘1991-12-01’

DISTINCT TCODE (iv) SELECT COUNT(*) FROM Worker
1075000
T02   WHERE GENDER=’MALE’AND DOJ > ‘1986-
T03 01-01’;

(v) COUNT(*) DCODE

2 D01

(g4) INAME TNAME 2 D05
DISP HOUSE INC
LED SCREEN 40 ELECTRONIC SALES (vi) Department

MEDIA

CAR GPS SYSTEM MARKETING

164 Together with®  Computer Science (Python)—12

Infrastructure Marketing

Finance Media

Human Resource Finance

(vii) Name Department City Human resource

George K Media Delhi (vii) Name Department

Ryma Sen Infrastructure Mumbai George k Infrastructure

(viii) Max(doj) Min(dob) Ryma sen Media

2014-06-09 1984-10-19 (viii) Max(doj) Min(dob)

25. (i) Select Eno,name,gender from employee order 20140609 19841019
by eno;
26. (i) Select no, name, tdate from travel order by no
(ii) Select name from employee where gender=’male’; desc;

(iii) Select Eno,name from employee (ii) Select name from travel

where dob between ‘1987-01-01’ and ‘1991-12-   where code=101 or code=102;
01’;
(iii) Select no, name from travel

or   where tdate between ‘2015-04-01’ and ‘2015-
12-31’;
Select eno,name from employee

where dob >=‘1987-01-01’ and dob <=‘1991- (iv) Select * from travel where km > 100 order by
12-01’; nop;

or (v) Count(*) Code

select eno,name from employee 2 101

where dob >‘1987-01-01’ and dob <‘1991-12- 2 102
01’;
(vi) Distinct code

(iv) Select count(*) from employee 101

where gender=’female’ and doj > ‘1986-01-01’; 102

or 103

Select * from employee 104

where gender=’female’ and doj > ‘1986-01-01’; 105

(v) Count Dcode (vii) Code Name Vtype

2 d01 104 Ahmed khan Car

2 d05 105 Raveena suv

(vi) Department (viii) Name km*perkm

Infrastructure Raveena 3200


Click to View FlipBook Version