SQL FULL REVISION
SQL FULL REVISION
Data types of SQL- Following are the most common data types of SQL.
NUMBER / INTEGER CHAR VARCHAR DATE DECIMAL
DDL DML
Data definition language Data manipulation language
Create Insert
Drop Update
Alter Delete
Select
Creating a Database-To create a database in
RDBMS, create command is used. INSERT Statement -To insert a new tuple(row or
Syntax, record) into a table is to use the insert statement
create database database-name; (i) To insert records into specific columns
Example Syntax:
create database Test; insert into table_name(column_name1,
------------------------------------------- column_name2…)values
CREATE TABLE Command: Create table (value1,value2….);
command is used to create a table in SQL.
Syntax : e.g. INSERT INTO student
CREATE TABLE tablename (rollno,name )VALUES(101,'Rohan');
(column_name data_type(size),
column_name2 data_type(size)…. (ii) insert records in all the columns
); insert into table_name
values(value1,value2……);
e.g. create table student (rollno integer(2), name
char(20), dob date); e.g.INSERT INTO student
(VALUES(101,'Rohan','XI',400,'Jammu');
-----------------------------------------------------------------
Alter command is used for alteration of table Update command –it is used to update a row of a
structures. Various uses of alter command, such table. syntax,
as, UPDATE table-name set column-name = value where
condition;
to add a column to existing table
e.g.
to rename any existing column
UPDATE Student set s_name='Abhi',age=17 where
to change datatype of any column or to s_id=103;
modify its size. -----------------------------------------------------------------
alter is also used to drop a column.
Delete command
Example:
ALTER command- Add Column to existing It is used to delete data(record) from a table.It can
Table
Using alter command we can add a column to an also be used with condition to delete a particular row.
existing table. (i) syntax:- to Delete all Records from a Table
Syntax,
alter table table-name add(column- DELETE from table-name;
name datatype); Example
e.g.
alter table Student add(address DELETE from Student;
char);
ALTER command-To Modify an existing
Column (ii) syntax: to Delete a particular Record from a
alter command is used to modify data type of an Table
existing column .
Syntax:- DELETE from Student where s_id=103;
-----------------------------------------------------------------
alter table table-name modify(column-name
datatype); SELECT command
e.g. Select query is used to retrieve data from a tables. It is
alter table Student modify(address varchar(30)); the most used SQL query. We can retrieve complete
tables, or partial by mentioning conditions using
ALTER command- To Rename a column WHERE clause.
Using alter command you can rename an existing Syntax :
column. (i) DISPLAY SPECIFIC COLUMNS
SELECT column-name1, column-name2, column-
Syntax:- name3, column-name from table-name;
alter table table-name change old-column-name
new_ column-name; Example
e.g. SELECT s_id, s_name, age from Student;
alter table Student change address Location;
(ii) DISPLAY ALL COLUMNS from
The above command will rename address column Table- A special character asterisk * is
to Location. used to address all the data(belonging to
all columns) in a query. SELECT
ALTER command -To Drop a Column statement uses * character to retrieve all
alter command is also used to drop columns also.
records from a table.
Syntax:-
Example: SELECT * from student;
alter table table-name drop(column-name)
e.g.
alter table Student drop column (address);
CONSTRAINTS-
Constraints: Constraints are the conditions that i. Not Null constraint : It ensures that the column
can be enforced on the attributes of a relation. The cannot contain a NULL value.
constraints come in play whenever we try to
insert, delete or update a record in a relation. ii. Unique constraint : A candidate key is a
They are used to ensure integrity of a relation, combination of one or more columns, the value of
hence named as integrity constraints. which uniquely identifies each row of a table.
1. NOT NULL iii. Primary Key : It ensures two things :
2. UNIQUE (i) Unique identification of each row in
3. PRIMARY KEY the table.
4. FOREIGN KEY (ii) No column that is part of the Primary
5. CHECK Key constraint can contain a NULL value.
6. DEFAULT
Example:
Create table Fee iv. Foreign Key : The foreign key designates a
(RollNo integer(2) Foreign key (Rollno) column or combination of columns as a foreign
references Student (Rollno), key and establishes its relationship with a primary
Name char(20) Not null, key in different table.
Amount integer(4),
Fee_Date date);
Example:
create table Employee v. Check Constraint : Sometimes we may
(EmpNo integer(4) Primary Key, require that values in some of the columns of our
Name char(20) Not Null, table are to be within a certain range or they must
Salary integer(6,2) check (salary > 0), satisfy certain conditions.
DeptNo integer(3)
);
WHERE clause
Where clause is used to specify condition while retrieving data from table. Where clause is used mostly with
Select, Update and Delete query. If condition specified by where clause is true then only the result from table is returned.
Syntax
SELECT column-name1, column-name2, column-name3, column-nameN
from table-name
WHERE [condition];
Relational Operator (comparison ) IN- used to show the records from a LIST
>, <, >=, <=, <> (not equal to ) =( equal to )
Display all records of those employees
whose belong to mumbai,delhi,jaipur only
HAVING Clause
It is used to give more precise condition for a statement. It is used to mention condition in Group based
SQL functions, just like WHERE clause.
Syntax:
select column_name, function(column_name)
FROM table_name
WHERE column_name condition
GROUP BY column_name
HAVING function(column_name) condition;
Consider the following Sale table.
Order By Clause- arrange or sort data Group By Clause- it is used to group the
To sort data in descending order DESC keyword results of a SELECT query based on one or more
columns
Syntax :
SELECT column-list|* SELECT column_name,
from table-name aggregate_function(column_name)
order by asc / desc; FROM table_name
WHERE condition
To display all records in ascending order of GROUP BY column_name;
the salary.
SELECT * from Emp order by salary; To find name and age of employees grouped by
To display all records in descending order of their salaries
the salary. Example
SELECT * from Emp order by salary DESC; SELECT name, age
from Emp
group by salary;
------------------------------------------------------------
-Group by in a Statement with WHERE clause
select name, max(salary) from Emp
where age > 25 group by salary;
where having
Where- Where clause is used to specify having- It is used to mention condition in Group
condition on single row.
Where clause is used mostly with Having clause is used only with group by clause
Select, Update and Delete command/query
Which command is used to change the Which keyword is used to select rows
number of columns in a table? containing
Ans ALTER column that match a wildcard pattern?
Ans LIKE
Differentiate between Degree and All aggregate functions except
Cardinality. ignore null values in their input collection.
Ans Degree – it is the total number of a) Count (attribute) b) Count (*)
columns in the table. c) Avg () d) Sum ()
Cardinality – it is the total number of Ans count(*)
tuples/Rows in the table.
Group functions can be applied to any Which command is used to change the
numeric values, some text types and existing information of table?
DATE values. (True/False) Ans update
Ans True
Which clause is used in query to place the Which command is used for counting the
condition on groups in MySql? number of rows in a database?
i) where ii) having i) row ii) count
iii) group by iv) none of the above iii) rowcount iv) row_count
Ans (ii) having Ans rowcount
A Resultset is an object that is returned In SQL, name the clause that is used to place
when a cursor object is used to query a condition on groups
table. True/False Ans Having
Ans True
In SQL, which command is used to change the Which operator performs pattern matching
structure of already created table. in SQL?
Ans Alter table Ans Like
What does the following function result In SQL, what are aggregate functions?
into? count(field_name) Ans These functions work with data of
Ans It returns the number of non-null records multiple rows at a time and return a single
from the field. value.
How many Primary and Foreign keys can a In SQL, write the name of the aggregate
table have? function which is used to calculate & display
Ans Primary Key – 1 Foreign Key – Many the average of numeric values in an attribute
of a relation.
Ans AVG()
Write an SQL query to display all the What is the use of LIKE keyword in SQL?
attributes of a relation named “TEST” along Ans LIKE keyword is used to find matching
with their description. CHAR values with WHERE clause.
Ans DESCRIBE TEST; or DESC TEST;
Which of the following is NOT a DML What is the purpose of following SQL
command? a). SELECT b). DELETE command: SHOW DATABASES;
c). UPDATE d). DROP Ans This command will print name of all
Ans (d) DROP the databases present in RDBMS.
Identify the error in the following SQL query In SQL, name the command/clause that is
which is expected to delete all rows of a table used to display the rows in descending order
TEMP without deleting its structure and write of a column. Ans Order By …… Desc
the correct one:
DELETE TABLE
TEMP;
Ans DELETE FROM TEMP;
In SQL, what is the error in following Write any two aggregate functions used in
query : SELECT NAME, SAL, SQL.
DESIGNATION WHERE
DISCOUNT=NULL; Ans max(),min(),avg(),count()
Ans SELECT NAME,SAL,DESIGNATION
WHERE DISCOUNT IS NULL;
Which of the following is a DML command? In SQL, write the query to display the list of
a) SELECT b) Update databases.
c) INSERT d) All Ans SHOW DATABASES’
Ans (d) All
Which of the following will suppress the entry A non-key attribute, whose values are
of duplicate value in a column? derived from primary key of some other
a) Unique b) Distinct table.
c) Primary Key d) NOT NULL a). Alternate Key b). Foreign Key c).
Ans (b) Distinct Primary Key d). Candidate Key
Ans (b) foreign Key
Identify the DDL Command. Which clause is used with a SELECT
(i) Insert into command (ii) Create table command in SQL to display the records in
command (iii) Drop table Command (iv) ascending order of an attribute?
Delete command Ans Order by
Ans (ii) Create table command (iii) Drop table
Command
A relation has 45 tuples & 5 attributes, what In SQL, which aggregate function is used to
will be the Degree & Cardinality of that count all records of a table?
relation? Ans count(*)
a). Degree 5, Cardinality 45
b). Degree 45, Cardinality 5
c). Degree 50, Cardinality 45
d). Degree 50, Cardinality 2250
Ans (a) Degree 5, Cardinality 45
Anita is executing sql query but not getting Sunita executes following two statements but
the appropriate output, help her to do the got the variation in result 6 and 5 why?
correction. (i) select count(*) from user ;
Select name from teacher where (ii) select count(name) from
subject=Null; user ;
Ans Select name from teacher where (iii) Ans
subject is Null; Count(*) will count rows where as
count(name) will count name column only
which is having one null value.
What is the difference between where and Write a command to add new column
having in SQL. marks in table ‘student’ data type int.
Ans Where is used apply condition in Ans Alter table student add marks int(3)
query, where as having is used only
with group.
Write query to display the structure of In SQL, what is the use of BETWEEN
table teacher. operator?
Ans describe teacher or desc teacher Ans The BETWEEN operator selects values
within a given range
In SQL, name the clause that is used to In SQL, what is the use of IS NULL
display the tuples in ascending order of an operator?
attribute. Ans To check if the column has null value
Ans Orderby / no value
Write any one aggregate function used in Which of the following is a DDL command?
SQL. a) SELECT b) ALTER
Ans SUM / AVG / COUNT / MAX / MIN c) INSERT d)
UPDATE
Ans (b) ALTER
In SQL, write the query to display the list of Which of the following types of table
tables stored in a database constraints will prevent the entry of duplicate
Ans Show tables; rows?
a) check b) Distinct
c) Primary Key d) NULL
Ans (c) Primary Key
Which is known as range operator in MySQL. If column “salary” of table “EMP” contains the
a) IN b) BETWEEN dataset {10000, 15000, 25000, 10000, 25000},
c) IS d) what will be the output of following
DISTINCT SQL statement?
Ans (b) BETWEEN SELECT SUM(DISTINCT SALARY)
FROM EMP; a) 75000 b) 25000
c) 10000 d) 50000
Ans (d) 50000
Which of the following functions is used to Name the clause used in query to place the
find the largest value from the given data in condition on groups in MySQL?
MySQL? Ans having
a) MAX ( ) b) MAXIMUM ( )
c) LARGEST ( ) d) BIG ( )
Ans (a) MAX()
Write SQL statement to find total number of Write command to list the available
records in table EMP? databases in MySQL.
Ans count(*) Ans show databases
In SQL, name of the keyword used to In SQL, what is the use of ORDER BY
display unique values of an attribute. clause ?
Ans DISTINCT Ans To display the values in sorted order
Write the function used in SQL to display Which of the following is a DML command?
current date a) CREATE b)ALTER c) INSERT d)
Ans curdate() DROP
Ans (c) insert
In SQL, write the command / query to display Which of the following type of column
the structure of table ‘emp’ stored in a constraints will allow the entry of unique and
database. not null values in the column?
Ans desc emp a) Unique b) Distinct
c) Primary Key d)
NULL
Ans (c) Primary Key
In SQL, name the clause that is used to In SQL, what is the use of <>
display the unique values of an attribute of a operator?
table. Ans not equal to
Ans distinct
Write any two aggregate function used in Which of the following is/ are DML
SQL command(s)?
Ans max/min/avg/sum/count(*) a) SELECT b) ALTER
c) DROP d)
UPDATE
Ans (a) select (d) update
In SQL, write the query to display the Which of the following types of table
list databases. constraints will not prevent NULL entries in a
Ans show databases table?
a) Unique b) Distinct
c) Primary Key d) NOT
NULL
Ans (c) Primary Key
MySQL -3 and 4 marks Questions
A department is considering to maintain their worker data using SQL to store the data. As a database administer, Karan
has decided that :
The attributes of WORKER are as follows: WORKER_ID - character of size 3 FIRST_NAME – character of size 10
LAST_NAME– character of size 10 SALARY - numeric
JOINING_DATE – Date
DEPARTMENT – character of size 10
WORKER_I D FIRST_NA ME LAST_NAM E SALARY JOINING_D ATE DEPARTM ENT
d) Karan wants to remove all the data from table WORKER from the database
Department. Which command will he use from the following:
i) DELETE FROM WORKER;
ii) DROP TABLE WORKER;
iii) DROP DATABASE Department;
iv) DELETE * FROM WORKER;
e) Write a query to display the Structure of the table WORKER, i.e. name of the
attribute and their respective data types.
Ans
Observe the following table and answer the question (a) to (e) (Any 04)
TABLE: VISITOR
VisitorID VisitorName ContactNumber
V001 ANAND 9898989898
V002 AMIT 9797979797
V003 SHYAM 9696969696
V004 MOHAN 9595959595
(a) Write the name of most appropriate columns which can be considered as
1
Candidate keys?
(b) Out of selected candidate keys, which one will be the best to choose as Primary
1
Key?
(c) What is the degree and cardinality of the table? 1
(d) Insert the following data into the attributes VisitorID, VisitorName and
Write a output for SQL queries (i) to (iii), which are based on the table: SCHOOL and ADMIN given below:
TABLE: SCHOOL
CODE TEACHERNAME SUBJECT DOJ PERIODS EXPERIENCE
1001 RAVI SHANKAR ENGLISH 12/03/2000 24 10
1009 PRIYA RAI PHYSICS 03/09/1998 26 12
1203 LISA ANAND ENGLISH 09/04/2000 27 5
1045 YASHRAJ MATHS 24/08/2000 24 15
1123 GANAN PHYSICS 16/07/1999 28 3
1167 HARISH B CHEMISTRY 19/10/1999 27 5
1215 UMESH PHYSICS 11/05/1998 22 16
TABLE: ADMIN
CODE GENDER DESIGNATION
1001 MALE VICE PRINCIPAL
1009 FEMALE COORDINATOR
1203 FEMALE COORDINATOR
1045 MALE HOD
1123 MALE SENIOR TEACHER
1167 MALE SENIOR TEACHER
1215 MALE HOD
a)
i) SELECT SUM (PERIODS), SUBJECT FROM SCHOOL GROUP BY SUBJECT;
ii) SELECT TEACHERNAME, GENDER FROM SCHOOL, ADMIN WHERE DESIGNATION = ‘COORDINATOR’ AND
SCHOOL.CODE=ADMIN.CODE;
iii) SELECT COUNT (DISTINCT SUBJECT) FROM SCHOOL;
Ans
i) ENGLISH 51 PHYSICS 76 MATHS 24 CHEMISTRY 27
ii) PRIYA RAI FEMALE LISA ANAND FEMALE
iii) 4
b)
i) To decrease period by 10% of the teachers of English subject.
ii) To display TEACHERNAME, CODE and DESIGNATION from tables SCHOOL and ADMIN whose gender is male.
iii) To Display number of teachers in each subject.
iv) To display details of all teachers who have joined the school after 01/01/1999 in descending order of experience.
v) Delete all the entries of those teachers whose experience is less than 10 years in SCHOOL table.
Ans
Relation : Employee
id Name Designation Sal
101 Naresh Clerk 32000
102 Ajay Manager 42500
103 Manisha Clerk 31500
104 Komal Advisor 32150
105 Varun Manager 42000
106 NULL Clerk 32500
Ans
i) id
ii) Ans. select avg(sal) from employee;
iii) Ans. select designation, count(*) from employee group by designation;
iv) Ans. select designation, count(*), sum(sal) from employee group by designation having count(*)>1;
v) Degree : 4 Cardinality : 6
Write the outputs of the SQL queries (i) to (iii) based on the relation COURSE
CID CNAME FEES STARTDATE TID
C201 AGDCA 12000 2018-07-02 101
C202 ADCA 15000 2018-07-15 103
C203 DCA 10000 2018-10-01 102
C204 DDTP 9000 2019-09-15 104
C205 DHN 20000 2019-08-01 101
C206 O LEVEL 18000 2018-07-25 105
Ans
(i) DISTINCT TID
101
103
102
104
105
(ii) TID COUNT(*) MIN(FEES)
101 2 12000
(iii) COUNT(*) SUM(FEES)
4 65000
Write SQL commands for the following queries (i) to (v) on the basis of relation Mobile Master and Mobile Stock.
TABLE: MOBILEMASTER
M_ID M_Company M_Name M_Price M_Mf_Date
MB001 SAMSUNG GALAXY 4500 2013-02-12
MB003 MOKIA N1100 2250 2011-04-15
MB004 MICROMAX UNITE3 4500 2016-10-17
MB005 SONY XPERIAM 7500 2017-11-20
MB006 OPPO SELFIEEX 8500 2010-08-21
TABLE: MOBILESTOCK
S_ID M_ID M_QTY M_SUPPLIER
S001 MB004 450 NEW VISION
S002 MB003 250 PRAVEEN GALLERY
S003 MB001 300 CLASSIC MOBILE STORE
S004 MB006 150 A-ONE MOBILES
S005 MB003 150 THE MOBILE
S006 MB006 50 MOBILE CENTRE
(i) Display the Mobile Company, Name and Price in descending order of their manufacturing date.
(ii) List the details of mobile whose name starts with “S” or ends with “a”.
(iii) Display the Mobile supplier & quantity of all mobiles except “MB003”.
(iv) List showing the name of mobile company having price between 3000 & 5000.
(v) Display M_Id and sum of Moble quantity in each M_Id.
Ans
(i) SELECT M_Company, M_Name, M_Price FROM MobileMasterORDER BY M_Mf_Date DESC;
(ii) SELECT * FROM MobileMaster WHERE M_Name LIKE “S%” or M_Name LIKE “%a”;
(iii) SELECT M_Supplier, M_Qty FROM MobileStock WHERE M_Id <>“MB003”;
(iv) SELECT M_Company FROM MobileMaster WHERE M_PriceBETWEEN 3000AND 5000;
(v) SELECT M_Id, SUM(M_Qty) FROM MobileStock GROUP BY M_Id;
As a database administrator
Name of the table : SOFTDRINK
The attributes are as follows:
Drinkcode, Calories - Integer
Price - Decimal
Dname - Varchar of size 20
Drinkcode Dname Price Calories
101 Lime and Lemon 20.00 120
102 Apple Drink 18.00 120
103 Nature Nectar 15.00 115
104 Green Mango 15.00 140
105 Aam Panna 20.00 135
106 Mango Juice Bahar 12.00 150
a) Identify the attributes that can be called Candidate keys.
b) What is the cardinality and degree of the table SOFTDRINK.
c) Include the following data in the above table.
Drinkcode = 107, Dname = “Milkshake” and Calories = 125
d) Give the command to remove all the records from the table.
e) Write a query to create the above table with Drinkcode as the Primary Key.
Ans
a) Drinkcode and Dname
b) Cardinality = 6, Degree = 4
c) Insert into softdrink(drinkcode,dname,calories) values (107,”Milkshake”,125);
d) Delete from softdrink;
e) Create table softdrink(drinkcode integer(5) Primary Key, dname varchar(20), Price decimal(6,2),
calories integer(5));
Write the outputs of the SQL queries i) to iii) based on the tables given below:
Table: ITEM ID
Item_Name Manufacturer Price
PC01 Personal Computer ABC 35000
LC05 Laptop ABC 55000
PC03 Personal Computer XYZ 32000
PC06 Personal Computer COMP 37000
LC03 Laptop PQR 57000
Table: CUSTOMER
C_ID CName City ID
01 N Roy Delhi LC03
06 R Singh Mumbai PC03
12 R Pandey Delhi PC06
15 C Sharma Delhi LC03
16 K Agarwal Bangalore PC01
i) Select Item_Name, max(Price), count(*) from Item group by Item_Name ;
ii) Select CName, Manufacturer from Item, Customer where Item.ID = Customer.ID;
iii) Select Item_Name, Price * 100 from Item where Manufacturer = “ABC”;
Ans
i) Personal Computer 37000 3
Laptop 57000 2
ii) N Roy PQR
R Singh XYZ
R Pandey COMP
C Sharma PQR
K Agarwal ABC
iii) Personal Computer 3500000
Laptop 5500000
Table: Suppliers
Scode Sname
21 Premium Stationary
23 Soft Plastics
22 Tetra Supply
i) To display details of all the items in the Store table in descending order of LastBuy.
ii) To display Itemno and item name of those items from store table whose rate is more than 15 rupees.
iii) To display the details of those items whose supplier code is 22 or Quantity in store is more than 110 from the table
Store.
iv) To display minimum rate of items for each Supplier individually as per Scode from the table Store.
v) To display ItemNo, Item Name and Sname from the tables with their corresponding matching Scode.
Ans
A CD/DVD Shop named “NEW DIGITAL SHOP” stores various CDs & DVDs of songs/albums/movies and use SQL to
maintain its records. As a Database Administrator, you have decided the following:
Name of Database - CDSHOP
Name of Relation - LIBRARY
Attributes are:-
(a) CDNO - Numeric values
(b)NAME - Character values of size (25)
(c) QTY - Numeric values
(d)PRICE - Decimal values
Table: LIBRARY
CDNO NAME QTY PRICE
10001 Indian Patriotic 20 150
10004 Hanuman Chalisa 15 80
10005 Instrumental of Kishore 25 95
10003 Songs of Diwali 18 125
10006 Devotional Krishna Songs 14 75
10002 Best Birthday Songs 17 NULL
Answer the following questions based on the above table LIBRARY:-
(a) Write the Degree & Cardinality of the relation LIBRARY.
(b) Identify the best attribute which may be declared as Primary key.
(c) Insert the following record in the above relation: (10009, ”Motivational Songs”, 15, 70)
(d) Write an SQL query to display the minimum quantity.
(e) Database administrator wants to count the no. of CDs which does not have any Price value.
Write the query for the same.
Ans
(a)Degree- 4 , cardinality- 6
(b) CDNO
(c) INSERT INTO LIBRARY VALUES (10009, ”Motivational Songs”, 15, 70);
(d) SELECT MIN(QTY) FROM LIBRARY;
(e) SELECT COUNT(*) FROM LIBRARY WHERE PRICE IS NULL;
Write the Outputs of the SQL queries (i) to (iii) based on the given below tables:
TABLE: TRAINER
TID TNAME CITY HIREDATE SALARY
101 SUNAINA MUMBAI 1998-10-15 90000
102 ANAMIKA DELHI 1994-12-24 80000
103 DEEPTI CHANDIGARH 2001-12-21 82000
104 MEENAKSHI DELHI 2002-12-25 78000
105 RICHA MUMBAI 1996-01-12 95000
106 MANIPRABHA CHENNAI 2001-12-12 69000
(a)
(i)SELECT DISTINCT(CITY) FROM TRAINER WHERE SALARY>80000;
(ii) SELECT TID, COUNT(*), MAX(FEES) FROM COURSE GROUP BY TID HAVING COUNT(*)>1;
(iii) SELECT T.TNAME, C.CNAME FROM TRAINER T, COURSE C WHERE T.TID=C.TID AND T.FEES
Ans (a)
(i)
MUMBAI
DELHI
CHANDIGARH
CHENNAI
(ii)
TID COUNT(*) MAX(FEES)
101 2 20000
(iii)
T.TNAME C.CNAME
MEENAKSHI DDTP
(b)
(i)Display all details of Trainers who are living in city CHENNAI.
(ii) Display the Trainer Name, City & Salary in descending order of their Hiredate.
(iii) Count & Display the number of Trainers in each city.
(iv) Display the Course details which have Fees more than 12000 and name ends with ‘A’.
(v) Display the Trainer Name & Course Name from both tables where Course Fees is less than 10000.
Ans
(i) SELECT * FROM TRAINER WHERE CITY IS “CHENNAI”;
(ii) SELECT TNAME, CITY, SALARY FROM TRAINER ORDER BY HIREDATE DESC;
(iii) SELECT CITY, COUNT(*) FROM TRAINER GROUP BY CITY;
(iv) SELECT * FROM COURSE WHERE FEES>12000 AND CNAME LIKE ‘%A’;
(v) SELECT T.TNAME, C.CNAME FROM TRAINER T, COURSE C WHERE T.TID=C.CID AND C.FEES;
Modern Public School is maintaining fees records of students. The database administrator Aman decided that- • Name
of the database -School
• Name of the table – Fees
• The attributes of Fees are as follows:
Rollno - numeric Name – character of size 20
Class - character of size 20
Fees – Numeric
Qtr – Numeric
(i) Identify the attribute best suitable to be declared as a primary key
(ii) Write the degree of the table.
(iii) Insert the following data into the attributes Rollno, Name, Class, Fees and Qtr in fees table.
(iv) Aman want to remove the table Fees table from the database School. Which command will he use from the
following:
a) DELETE FROM Fees;
b) DROP TABLE Fees;
c) DROP DATABASE Fees;
d) DELETE Fees FROM Fees;
(v) Now Aman wants to display the structure of the table Fees, i.e, name of the attributes and their respective data
types that he has used in the table. Write the query to display the same.
Ans
i)Primary Key – Rollno
ii)Degree of table= 5
iii)Insert into fees values(101,’Aman’,’XII’,5000);
iv)DELETE FROM Fees
v)Describe Fees
Consider the table TEACHER given below. Write commands in SQL for (i) to (iii)
TABLE: TEACHER
ID Name Department Hiredate Category Gender Salary
1 Taniya SocialStudies 03/17/1994 TGT F 25000
2 Abhishek Art 02/12/1990 PRT M 20000
3 Sanjana English 05/16/1980 PGT F 30000
4 Vishwajeet English 10/16/1989 TGT M 25000
5 Aman Hindi 08/1/1990 PRT F 22000
6 Pritam Math 03/17/1980 PRT F 21000
7 RajKumar Science 09/2/1994 TGT M 27000
8 Sital Math 11/17/1980 TGT F 24500
i. To display all information about teachers of Female PGT Teachers.
ii. To list names, departments and date of hiring of all the teachers in descending order of date of joining.
iii. To count the number of teachers and sum of their salary department wise
Ans
Write SQL commands for the queries (i) to (iii) and output for (iv) & (v) based on a table COMPANY and CUSTOMER .
TABLE:COMPANY
CID NAME CITY PRODUCTNAME
111 SONY DELHI TV
222 NOKIA MUMBAI MOBILE
333 ONIDA DELHI TV
444 SONY MUMBAI MOBILE
555 BLACKBERRY MADRAS MOBILE
666 DELL DELHI LAPTOP
TABLE:CUSTOMER
CUSTID NAME PRICE QTY CID
101 Rohan Sharma 70000 20 222
102 Deepak Kumar 50000 10 666
103 Mohan Kumar 30000 5 111
104 SahilBansal 35000 3 333
105 NehaSoni 25000 7 444
106 SonalAggarwal 20000 5 333
107 Arjun Singh 50000 15 666
(i) To display those company name which are having price less than 30000.
(ii) To display the name of the companies in reverse alphabetical order.
(iii) To increase the price by 1000 for those customer whose name starts with ‘S’
(iv) SELECT PRODUCTNAME,CITY, PRICE FROM COMPANY,CUSTOMER WHERE COMPANY.CID=CUSTOMER.CID AND
PRODUCTNAME=”MOBILE”;
(v) SELECT AVG(QTY) FROM CUSTOMER WHERE NAME LIKE “%r%;
Ans
i) SELECT COMPANY.NAME FROM COMPANY,CUSTOMER WHERECOMPANY.CID = CUSTOMER.CID AND
CUSTOMER.PRICE<30000;
ii) SELECT NAME FROM COMPANY ORDER BY NAME DESC;
iii) UPADE CUSTOMER SET PRICE = PRICE+1000 WHERE NAME LIKE ‘S%’;
iv) PRODUCTNAME CITY PRICE
MOBILE MUMBAI 70000
MOBILE MUMBAI 25000
v) 12
ABC school is considering to maintain their student’s information using SQL to store the data. As a database
administrator Harendra has decided that:
Name of database : school
Name of table : student
Attributes of the table are as follow:
AdmissionNo-numeric
FirstName –character of size 30
LastName - character of size 20
DOB - date
Table student
AdmissionNo FirstName LastName DOB
012355 Rahul Singh 2005-05-16
012358 Mukesh Kumar 2004-09-15
012360 Pawan Verma 2004-03-03
012366 Mahesh Kumar 2003-06-08
012367 Raman Patel 2007-03-19
Ans
i.Degrre-4 Cardinility-5
ii. AdmissionNo
iii. insert into student values(012368,’Kamlesh’,’Sharma’,’2004-01-01’)
iv. Delete command
v. Drop table student
Table : Employee
EmployeeId Name Sales JobId
E1 Sumit Sinha 110000 102
E2 Vijay Singh Tomar 130000 101
E3 Ajay Rajpal 140000 103
E4 Mohit Kumar 125000 102
E5 Sailja Singh 145000 103
Table: Job
JobId JobTitle Salary
101 President 200000
102 Vice President 125000
103 Administrator Assistant 80000
104 Accounting Manager 70000
105 Accountant 65000
106 Sales Manager 80000
Give the output of following SQL statement:
(i) Select max(salary),min(salary) from job
(ii) Select Name,JobTitle, Sales from Employee,Job where Employee.JobId=Job.JobId and JobId in (101,102)
(iii) Select JobId, count(*) from Employee group by JobId;
Ans
i.200000, 65000
ii.
Vijay Singh Tomar President 130000
Sumit Sinha Vice President 110000
Mohit Kumar Vice President 125000
iii. 101 1
102 2
103 2
Write SQL Commands for the following queries based on the relations PRODUCT and CLIENT given below.
Table: Product
P_ID ProductName Manufacturer Price ExpiryDate
TP01 Talcum Powder LAK 40 2011-06-26
FW05 Face Wash ABC 45 2010-12-01
BS01 Bath Soap ABC 55 2010-09-10
SH06 Shampoo XYZ 120 2012-04-09
FW12 Face Wash XYZ 95 2010-08-15
Table: Client
C_ID ClientName City P_ID
1 Cosmetic Shop Delhi FW05
6 Total Health Mumbai BS01
12 Live Life Delhi SH06
15 Pretty One Delhi FW05
16 Dreams Bengaluru TP01
14 Expressions Delhi NULL
(i) To display the ClientName and City of all Mumbai- and Delhi-based clients in Client table.
(ii) Increase the price of all the products in Product table by 10%.
(iii) To display the ProductName, Manufacturer, ExpiryDate of all the products that expired on or before ‘2010-12-31’.
(iv)To display C_ID, ClientName, City of all the clients (including the ones that have not purchased a product) and their
corresponding ProductName sold.
(v) To display productName, Manufacturer and ClientName of Mumbai City.
Ans
(i)select ClientName, City from Client where City = ‘Mumbai’ or City = ‘Delhi’;
(ii) update Product set Price = Price + 0.10 * Price;
(iii) select ProductName, Manufacturer, ExpiryDate from Product where ExpiryDate < = ‘2010-12-31’;
(iv) select C_ID, ClientName, City, ProductName from Client Left Join Product on Client. P_ID = Product.P_ID;
(v) select ProductName, Manufacturer, ClientName from product,client Where product.P_ID=Client.P_ID and
city=’Mumbai’;
A school KV is considering to maintain their eligible students’ for scholarship’s data using SQL to store the data. As a
database administer, Abhay has decided that :
• Name of the database - star
• Name of the table - student
• The attributes of student table as follows:
No. - numeric
Name – character of size 20
Stipend - numeric
Stream – character of size 20
AvgMark – numeric
Grade – character of size 1
Class – character of size 3
Table ‘student’
No. Name Stipend Stream AvgMark Grade Class
1 Karan 400.00 Medical 78.5 B 12B
2 Divakar 450.00 Commerce 89.2 A 11C
3 Divya 300.00 Commerce 68.6 C 12C
4 Arun 350.00 Humanities 73.1 B 12C
5 Sabina 500.00 Nonmedical 90.6 A 11A
6 John 400.00 Medical 75.4 B 12B
7 Robert 250.00 Humanities 64.4 C 11A
8 Rubina 450.00 Nonmedical 88.5 A 12A
9 Vikas 500.00 Nonmedical 92.0 A 12A
10 Mohan 300.00 Commerce 67.5 C 12C
Ans
(i) create table student(no integer,name char(20), stipend integer,stream char(20),avgmark integer, grade char(1),class
char(3));
(ii)No is Best suitable primary key
(iii) Degree = 7, cardinality = 10
(iv) select * from student order by name;
(v) update student set grade=’A’ where name=’Karan’;
Consider the following tables Sender and Recipient. Write SQL commands for the statements (a) to (c) and give the
outputs for SQL queries (d) to (e).
Table: Sender
SenderID SenderName SenderAddress Sendercity
ND01 R Jain 2, ABC Appls New Delhi
MU02 H Sinha 12 Newtown Mumbai
MU15 S Jha 27/A, Park Street Mumbai
ND50 T Prasad 122-K,SDA New Delhi
Table: Recipients
RecID SenderID RecName RecAddress recCity
KO05 ND01 R Bajpayee 5, Central Avenue Kolkata
ND08 MU02 S Mahajan 116, A-Vihar New Delhi
MU19 ND01 H Singh 2A, Andheri East Mumbai
MU32 MU15 P K Swamy B5, C S Terminals Mumbai
ND48 ND50 S Tripathi 13, BI D Mayur Vihar New delhi
a. To display the RecIC, Sendername, SenderAddress, RecName, RecAddress for every Recipient
b. To display Recipient details in ascending order of RecName
c. To display number of Recipients from each city
d. To display the details of senders whose sender city is ‘mumbai’
e. To change the name of recipient whose recid is ’Ko05’ to’ S Rathore’.
Ans
a. Select R.RecIC, S.Sendername, S.SenderAddress, R.RecName, R.RecAddress from Sender S, Recepient R where
S.SenderID=R.SenderID ;
b. SELECT * from Recipent ORDER By RecName;
c. SELECT COUNT( *) from Recipient Group By RecCity;
d.Select * from sender where Sendercity=’mumbai’;
e. update recipient set RecName=’S Rathore’ where RecID=’ KO05’
A departmental store MyStore is considering to maintain their inventory using SQL to store the data. As a database
administer, Abhay has decided that :
• Name of the database - mystore
• Name of the table - STORE
• The attributes of STORE are as follows:
ItemNo - numeric
ItemName – character of size 20
Scode - numeric
Quantity – numeric
Table : STORE
ItemNo ItemName Scode Quantity
2005 Sharpener Classic 23 60
2003 Ball Pen 0.25 22 50
2002 Get Pen Premium 21 150
2006 Get Pen Classic 21 250
2001 Eraser Small 22 220
2004 Eraser Big 22 110
2009 Ball Pen 0.5 21 180
Ans
(a) ItemNo 1
(b) Degree = 4 Cardinality = 7
(c) INSERT INTO store (ItemNo,ItemName,Scode) VALUES(2010, “Note Book”,25);
(d) DROP TABLE store; 1
(e) Describe Store;
Write the outputs of the SQL queries (i) to (iii) based on the relations Teacher and Posting given below:
Table : Teacher
T_ID Name Age Department Date_of_join Salary Gender
1 Jugal 34 Computer Sc 10/01/2017 12000 M
2 Sharmila 31 History 24/03/2008 20000 F
3 Sandeep 32 Mathematics 12/12/2016 30000 M
4 Sangeeta 35 History 01/07/2015 40000 F
5 Rakesh 42 Mathematics 05/09/2007 25000 M
6 Shyam 50 History 27/06/2008 30000 M
7 Shiv Om 44 Computer Sc 25/02/2017 21000 M
8 Shalakha 33 Mathematics 31/07/2018 20000 F
Table : Posting
P_ID Department Place
1 History Agra
2 Mathematics Raipur
3 Computer Science Delhi
(a)
i. SELECT Department, count(*) FROM Teacher GROUP BY Department;
ii. SELECT Max(Date_of_Join),Min(Date_of_Join) FROM Teacher;
iii. SELECT Teacher.name,Teacher.Department, Posting.Place FROM Teacher, Posting WHERE Teacher.Department =
Posting.Department AND Posting.Place=”Delhi”;
Ans
i. Department Count(*)
History 3
Computer Sc 2
Mathematics 3
(b)
i.To show all information about the teacher of History department.
ii. To list the names of female teachers who are in Mathematics department.
iii. To list the names of all teachers with their date of joining in ascending order.
iv. To display teacher’s name, salary, age for male teachers only.
v. To display name, bonus for each teacher where bonus is 10% of salary.
Ans
i. SELECT * FROM teacher WHERE department= “History”; 5
ii. SELECT name FROM teacher WHERE department= “Mathematics” AND gender= “F”;
iii. SELECT name FROM teacher ORDER BY date_of_join;
iv. SELECT name, salary, age FROM teacher WHERE gender=’M’;
v. SELECT name, salary*0.1 AS ‘Bonus’ FROM teacher;
An organization SoftSolutions is considering to maintain their employees records using SQL to store the data. As a
database administer, Murthy has decided that :
• Name of the database - DATASOFT
• Name of the table - HRDATA
• The attributes of HRDATA are as follows:
ECode – Numeric
EName – character of size 30
Desig – Character of size 15
Remn – numeric
Table: HRDATA
ECode EName Desig Remn
80001 Lokesh Programmer 50000
80004 Aradhana Manager 65000
80007 Jeevan Programmer 45000
80008 Arjun Admin 55000
80012 Priya Executive 35000
Ans
a) Ecode
b) Degree: 4, Cardinality: 5
c) Insert into HRDATA (Ecode, Ename, Remn) VALUES (80015, “Allen”, 43000)
d) DELETE FROM HRDATA WHERE ENAME LIKE “Jeevan”;
e) UPDATE HRDATA SET REMN = REMN * 1.10;
Consider the following tables: COMPANY and MODEL. Write the outputs of the SQL queries (a) to (c) based on the
relations COMPANY and MODEL given below:
Table: COMPANY
Write SQL commands for (i) to (v) on the basis of relations given below:
Table: BOOKS
book_id Book_name author_name Publishers Price Type qty
L01 Let us C Sanjay Mukharjee EPB 450 Comp 15
L02 Genuine J. Mukhi FIRST PUBL. 755 Fiction 24
L04 Mastering C++ Kantkar EPB 165 Comp 60
L03 VC++ advance P. Purohit TDH 250 Comp 45
L05 Programming with Python Sanjeev FIRST PUBL. 350 Fiction 30
Table: ISSUED
Book_ID Qty_Issued
L02 13
L04 5
L05 21
Ans
i) SELECT * FROM BOOKS WHERE PUBLISHER LIKE „FIRST PUBL.‟ AND AUTHOR_NAME LIKE „P. Purohit‟;
ii) Select Price from Books where PUBLISHER LIKE „EPB‟;
iii) UPDATE BOOKS SET PRICE = PRICE * 0.90 WHERE PUBLISHER LIKE „EPB‟;
iv) SELECT BOOK_NAME, PRICE FROM BOOKS B, ISSUED I WHERE B.BOOK_ID = I.BOOK_ID AND QTY_ISSUED > 5;
v) SELECT SUM(PRICE) FROM BOOKS GROUP BY TYPE;
A Medical store “Lifeline” is planning to maintain their inventory using SQL to store the data. A database administer has
decided that:
Name of the database -medstore
Name of the table –MEDICINE
The column of MEDICINE table are as follows:
ino - integer
iname – character of size 15
mcode - integer
qty – integer
Ans
(a) ino
(b) Degree= 6 Cardinality =7
(c) UPDATE MEDICINE set iname= ‘Paracetamol Tablet’,mcode=25, qty=100 where ino = 1003 ;
(d) DROP TABLEMEDICINE;
(e) Select distinct mcode from MEDICINE;
Write SQL commands for the following queries (i) to (v) based on the relations Vehicle and Travel given below.
Table :Travel
NO NAME TDATE KM CODE NOP
101 Janish Kin 2015-11-13 200 101 32
103 Vedika Sahai 2016-04-21 100 103 45
105 Tarun Ram 2016-03-23 350 102 42
102 John Fen 2016-02-13 90 102 40
107 Ahmed Khan 2015-01-10 75 104 2
104 Raveena 2016-05-28 80 105 4
Table : Vehicle
CODE VTYPE PERKM
101 VOLVO BUS 160
102 AC DELUXE BUS 150
103 ORDINARY BUS 90
105 SUV 40
104 CAR 20
i. To display NO, NAME, TDATE from the table Travel in descending order of NO.
ii. To display the NAME of all the travelers from the table Travel who are travelling by vehicle with code 101 or 102.
iii. To display the NO and NAME of those travelers from the table Travel who travelled between ‘2015-12-31’ and
‘2016-04-01’.
iv. To display the CODE,NAME,VTYPE from both the tables with distance travelled (km) less than 90 Km.
v. To display the NAME of those traveler whose name starts with the alphabet ‘R’.
Ans
To fetch some useful information from the database, can use either
fetchone() method to fetch single record
fetchall() method to fetch multiple values from a database table.
fetchmany()- to fetch limited no of records
Once a database connection is established, we are ready to create tables or records into the database tables
using execute method of the created cursor.
NETWORKING
Two or more computing devices connected to one another in order to exchange information or
share resources, form a computer network.
Advantages-
Share resources- Share Storage Share Software and hardware Security Back up and Roll back is easy
Switching Techniques