EXAM PATTERN
EXERCISE
Which of the following operator displays a
OBJECTIVE Type Questions oars ifeitherthe first condition oF the secon
Directions (Q. Nos. 1-10) There are multiple choice Condition is true?
type questions. Select the correct option. (a AND (b) BETWEEN
1. Which of the following is an advantage of SQL? (or (@) None of these
(a) High speed Ans. (0) OR
(b) Client/server language 7, The ...... keyword sorts the records in
(©) Easy to learn ; ascending order by default.
(4) Allofthe above (@) LIKE (0) UPDATE
Ans. (4) Allof the above (©) ORDER (4) ORDER BY
2. Which statement of SQL provides statements ns, (d) ORDER BY
for manipulating the database objects?
() DDL (&) DML 8. Aggregate functions are also known as
(pc. (@teL (@) group functions _(b) group method
Ans, (b) DML (Data Manipulation Language) (©) sum function (@) Add funetion
3. Which of the following command is used to Ans. (a) group functions
remove the table definition and all data? 9. Which of the following function returns the
(a) Create (b) Select total number of values?
(©) Drop (@) None of these (Max MIN
Ans, (©) Drop (¢ COUNT (uM
4. Which of the following is a correct syntax to Ans, (c) COUNT
add a column in SQL command?
(@) ALTER TABLE table_nane ADD colunn_nane 10. Which of the following join gives the
data, type: intersection of two tables?
(b) ALTER TABLE ADD column_name data_type: (a) Outer join (b) Inner join
(c) ALTER table_name ADD column_name (©) Equi join (d) None of these
data_type: Ans. (b) Inner join
(@) None of the above
‘Ans, (a) ALTER TABLE table_fiane AOD. coluni_nane |.’ Directions (Q. Nos. 11-20) Fill in the blanks.
data_type: “= Mf, SQLis running in all.
5. Which keyword can be used to return only Ans. servers
different values in a particular column or a £2, 2 proves teas :
whole table? P jements for creation and
(@) WHERE deletion of the database tables, views.
(b) DISTINCT Ans. DDL (Data Definition Language)
(ALL 13, .... data type stores year, month and day
(4) BETWEEN values,
Anz. (DISTINCT Ans. DATE
=. “
© scanned with OKEN ScannerFr
structured Query Language
_.{s used to add, delete or modify
{4 The SOL. astraints in the existing table,
cotumns and con
ans ALTER TANLE
IS, The Is agulck way of etecting al etumns,
ng “esters
are Fhe __atause esd to extract only those
16 rir that fulfil a specie itera.
ans WHERE
operators used to match a value similar to
+ Feet patter ina column using % and.
ans UKE
«function returns the largest value from the
Saected column,
ans aX
19, The —- statement is used with the aggregate
- Fanctions to group the result set by one or more
columns.
‘Ans, GROUP BY
20, —-isasimple SQL join condition that uses
‘qual sign as a comparison operator.
Ans. Equijoin
Directions (0. Nos. 21-33) Answer the following
questions.
21, Expand the following abbreviation:
( SL
(@) DML
Ans. () SQL- Structured Query Language
() DML- Data Manipulation Language
22, Mention two characteristics of SQL.
Ans. (i) SQLisa very simple and easy to learn.
@ SQL allows the users to create, update, delete and
retrieve data from a database.
23, Name any two DDL commands.
Ans. DDL consists of various commands such a:
(0 Create
(i) Alter
24, Name any four Transaction Control Language
(TCL) commands.
Ans. Four 7CL commands ae listed below:
(i) Commit
(i) Rollback
(ii) Savepoint
(iv) Set Transaction
25.
Ans,
26.
Ans.
27,
Ans.
28.
Ans,
29,
Ans.
30.
Ans.
3
Ans,
32.
Ans.
33.
Ans.
215
What Is the use of Set Transaction command?
Set Transaction command establishes properties for the
current transactions,
Give the SQL statement to create a table Student
with Noll Number, Name, Age and Mari
CREATE TABLE Student (Rol ]_Nusber NUMBER(S)
Primary key, Mame CHAR (20), Age Number (2).
Marks Number (49):
Give the syntax of DROP statement.
DROP TABLE table_nane:
How will you select the content of the columns
named LastName and FirstName from the
Employee table.
SELECT Lastliame, Firstliane FROM Employee:
‘What is the use of WHERE clause in SQL?
‘The WHERE clause is used to extract only those records
that fulfil a specified criteria
Write the query to select all the persons from
the table Persons and sort the persons by their
last name in ascending order.
SELECT * FROM Persons ORDER BY LastNat
ASC:
‘Write the query to count the total number of
employees from Payments table.
SELECT COUNT(*) “Employees” FROM Paynents:
Give the syntax of Having clause.
SELECT column_name, aggregate_function
(column_name)
FROM table_name
WHERE condition
GROUP BY column_nane
HAVING aggregate_function (colunn_nane)
;
Name any two logical operators.
‘And, OR
SHORT ANSWER Type Questions
1
Ans.
2
Ans.
Write the disadvantages of SQL.
Refer to text on page no 199.
Which commands are used to control user's
privileges and how?
‘There are two commands that are used to control a user's
privileges
() GRANT
REVOKE
© scanned with OKEN Scanner216
‘The GRANT command is used to give an existing user
privileges and REVOKE command is used to remove
privileges. If user does not exist, GRANT will create a
‘new user at the same time and give them all privileges.
ite between COMMIT and ROLLBACK
3. Different
command,
COMMIT command is used to permanent all the changes
made by DML commands, while ROLLBACK means that
ittundoes all changes since the beginning of a transaction,
for since a save point.
Ans.
4, How to create a database?
Refer to text on page 200,
5, Write a query on the Salespeople table, whose
output will exclude all salespeople with a rating
>= 100, unless they are located in Delhi.
SELECT * FROM Salespeople *
WHERE rating < 100 OR city = ‘Delhi’:
Or SELECT * FROM Salespeople WHERE NOT
rating > = 100 OR city = ‘Delhi’;
Or SELECT * FROM Salespeople WHERE NOT
(rating > = 100 AND city © ‘DeThi");.,
6. Explain the use of ORDER BY clause.
Ans, The ORDER BY keyword is used to sort the result set
along a specified column with the SELECT command,
‘The ORDER BY keyword sorts the records in ascending
order by default. If you want to sort the records in a
descending order, you can use the DESC keyword.
Syntax
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC/DESC:
7. Create a table named Programmers with the
following structure
P.Name __VARCHAR(20)
boy Dat
SAL NUMBER
() Display the name of the programmer, which
has the highest salary.
(li) Update the salary of all programmer by 2000,
whose name start with letter R.
() SELECT PName MAX(SAL)
FROM Progranmers;
(i) UPDATE Programmers SET SAL = SAL +
2000 WHERE PName LIKE ‘RS":
Ans.
8. Explain IS NULL clause in SQL.
Ans. If we want to search the column whose value is NULL in
a table, then we use IS NULL clause,
| All/none | COMPUTER SCIENCE Class 194,
Syntax
SELECT 1S NULL:
9, Differentiate between char(n) and varchar(n)
* Gata types with respect to databases,
[CBSE SQP Term,
‘Ans. Differentiate between char(a) and varchar(n) are gy
follows
chain) varchar(o)
‘arable engin
Tatoos a fixed longih __Itstoes a variable engi
{lng botwoen 1 and 255. sng
characters
ithe val sof emalier No blanks are added by
Ine enitadde blank varchar) even vale of
spaces. small length.
space ie wasted nit. Nowastage of space in
ae varchar(n).
10, Write the output of the queries (i) to (iv) based
on the table FURNITURE given below.
[CBSE SQP Term 1,
Table ; FURNITURE t
mo wane PATEOEPURCH cost piscoun
2001 DoubloBed —OGUAN2018 4500010
TOIO Dinning Table 1O-MAR-2020 510005
2008 Single Bed _19UL2021__22000 0
(C003 Long back @ODEC-2016 120003
Chair
7006 Console Table _17-NOV.2010 15000 12
8006 Bunkbed _OTAN-2021 7800014
() SELECT SUMCOISCOUNT) FROM FURNITURE
WHERE COST>15000;
(ii) SELECT MAX(DATEOFPURCHASE) FROM
FURNITURE;
(lil) SELECT * FROM FURNITURE WHERE
DISCOUNTDS AND FID LIKE *T3*:
(jv) SELECT DATEOFPURCHASE FROM FURNITURE
WHERE NAME IN ("Dinning Table".
“Console Table"):
Ans. (i)
«i
19-dui-2021
© scanned with OKEN Scannerqontsed QE Language
PO Too MaR=2020
7-NOV-2019
{f, What are DDL and DML?
ns DDL (Data Definition Language) is part of SQL.
which provides commands for creating, Seriya
dropping the tables. Different DDL commands are
CREATE, ALTER, DROP and RENAME.
DML (Data Manipulation Language) isa part of SQL,
which provides commands for inserting, deleting and
updating the information in a database. Different DML
‘commands are SELECT, UPDATE, INSERT.
Describe the four data types in SQL.
‘Ans. Refer to the text on page 200.
Write the queries for the following questions
‘using the table Item with the following fields.
(Item_Code, ItemName, Quantity, Price)
() Display the price 500 of item having code as
108.
(ii) Display the names of all items with quantity
greater than 50 and price less than 500.
(ii) Display the item code of all items with
quantity less than 70.
Ans. (i) UPDATE ITEM SET Price = Price + 00
WHERE TtemCode 106
(i) SELECT ItemName FROM Item
WHERE (Quantity > 50) AND (Price < 600):
(ii SELECT Item_Code FROM Item
WHERE Quantity < 70:
14, Consider the following table with their fields
IAME, DESIG, SALARY.
EMPLOYEE (€_CODE, EN
ae 00)
PF, HRA, DA of all the
'YEE table. HRA is 25%
PF is 5% of
nding order
List the names, salary,
employees in the EMPLO
of salary and DA is 10% of salary.
salary. The result should be in desce!
of salary.
Ans. SELECT E_Nane. SALARY, SALARY * 0-25
AS HRA, SALARY*O.10
AS DA, SALARY*0.05 AS PF
217
FROM EMPLOYEE
(ORDER BY SALARY DESC:
Write a short note on DISTINCT keyword with
an example.
‘Ans. Refer to the text on page no 205.
16, Define UPDATE command of SQL with its basic
syntax and also give one of its example.
‘Ans. An UPDATE command is used to directly change oF
modify the value stored in one or more fields in &
specified record.
Syntax
UPDATE table_name
SET colunnl = valuel,
column? = value2,.+-
WHERE ;
eg, Consider the table PERSONS to update the address
as Nissestien 67.
UPDATE PERSONS SET Address
= ‘Nissestien 67°:
17. Write a output for SQL queries (i) to (ii), which
are based on the table ITEMS.
7 TABLE: ITEMS 8
Code! Name ‘aty| Price | Company |TCode
1001 [DIGITAL PAD 121. | 120|11000) XENITA Tot
4006 | LED SCREEN 40 70|3¢000|saToRA | To2
1o0s|can GPs system | 50] 2150 |GEOKNOW | Tot
4003 | DIGITAL CAMERA 12x | 160| 8000 |DIGICLICK ‘| TO2
1005 |PEN pRIvE 3268 _|600| 1200 |STOREHOME] To3
() SELECT MAX(Price), MIN(Price) FROM
ITEMS:
(i) SELECT Price * Oty AMOUNT
FROM ITEMS WHERE Code=1004;
(iil) SELECT DISTINCT TCode FROM ITEMS;
Ans. (i)
MAX(Price)
38000
MIN(Price)
1200
@w Sines dea
‘AMOUNT
107500
aw
a
© scanned with OKEN Scanner218
18, Give the output of the following SQL
statements, which are based on the table
| Allmone | COMPUTER SCIENCE Class 12th
(i) SELECT CNAME FROM CUSTOMER WHERE,
CNAME LIKE "LS":
(iii) SELECT DISTINCT AREA FROM CUSTOMER:
APPLICATNS.
TABLE: APPLICANTS Ans. ()
No. | NAME | FEE |GENDER| C10 | JOINYEAR COUNT (*) _ GENDER
wo12|Amandeep| 30000 | M | Aot | 2012 4 a
11o2|avsha | 25000] fF | Ao | 2000 a
1103 ekant | 30000} M | az | 2011 (i) No rows selected
1049 | Arun 3oo00 | M | aoa | 2009 Gi)
1025] Amber | 40000 | Mm | Age | 2011 DISTINGT AREA
1106 | Ela ooo | F | aos | 2010 NORTH
1017 Nita =| 5000 | Ff | aoa | aoe SOUTH
1108 |actuna | 30000] F | aos | 2ore eAST
2109|shakti | 35000 | Mm | aos | 2011 west
a et 20. Write the output for SQL queries (i) to (ii),
(i) SELECT NAME, JOINYEAR FROM APPLICANTS
WHERE GENDER =*F* AND C_ID="A02
(i) SELECT MINCJOINYEAR) FROM APPLICANTS:
WHERE GENDER = ‘M";
(ii) SELECT AVG(FEE) FROM APPLICANTS WHERE
C_ID="A01" OR C_ID="A05";
Ans. ()
NAME JOINYEAR
‘Avisha 2008
Gi) —_____
(MIN (JOINYEAR)
2009
(ii)
AVG (FEE)
3166.66
19, Write the output for SQL queries (i) to (ii),
which are based on the table CUSTOMER.
‘TABLE: CUSTOMER
cD. (CNAME GENDER | SID | AREA
1001 SHARMA FEMALE | 101 | NORTH
1002 | — MRTWARY mate | 102 | SOUTH
1003 MK KHAN MALE | 103 | EAST
1004 AKSINGH Male | 102 | EAST
1005 ‘SSEN FeMaLe | 101 | WEST
1006 RDUBEY Male | 104 | NORTH
1007 | MAGARWAL FEMALE | 104 | NORTH
1008 SDAS FEMALE | 103 | SOUTH
1009 RK PATIL Mate | 102 | NORTH
toro | NkrisHNAMURTY | _MaLe | _102_| SOUTH
() SELECT COUNT(*), GENDER FROM CUSTOMER
GROUP BY GENDER:
a
which are based on the table CARDEN.
TABLE: CARDEN
Goode [CarName| Make | Color | Capacity | Charges
sor | Aster | Summ | RED | 3 4
503 | indigo | Tata | suven | 3 2
502 | innova | Toyota | WHITE |. 7 15
soo | sxe | suzuki | SUVER | 4 4
510 | Cass |Mercedes| RED | 4 38
(SELECT COUNT(DISTINCT Make) FROM
CARDEN:
(i) SELECT COUNT(*) Make FROM CARDEN;
(ii) SELECT CarName FROM CARDEN WHERE
Capacity = 4:
Ans. (i)
‘COUNT
(OISTINCT Make)
4
@ an
Make
5
«a
Canlame
6
C-Class ‘
24, (i) Atable, ITEM has been created in a database
with the following fields
ITEMCODE, ITEMNAME, QTY, PRICE.
Give the SQL command to add a new field,
DISCOUNT (of type Integer) to the ITEM
table.
© scanned with OKEN Scannerstructured Query Language
(l) Categorize following commands Into DDL
and DML commands?
INSERT INTO, DROP TABLE, ALTER TABLE,
| UPDATE..SET {CBSE SQP Term 11)
(0 ALTER TABLE ITEM AOD Dtscount.1N
(i) DDL means ‘Data Definition Language’. I is used to
create and modify the structure of database objects in
SQL. $0, DDI. commands are DROP TABLE, ALTER
TABLE,
DML is ‘Data Manipulation Language’ whi
to:manipulate data itself
So, DML commands are
UPDATE..SET.
is used
INSERT INTO,
Charu has to create a database named
MYEARTH in MySQL.
She now needs to create a table named CITY in
the database to store the records of various
cities across the globe. The table CITY has the
following structure.
Table CITY
FidNamo Data Typo ‘Remarks
GITYCODE __—_CHARIS)
orname CHAR)
Size INTEGER
We_warene 6 INTEGER 7
“_POPULATIONRATE INTEGER
POPULATION INTEGER
Help her to complete the task by suggesting
appropriate SQL commands. (CBSESQPTerm Il]
} ANS. Command to create database
CREATE DATABASE MYEARTH:
‘Command to create table
CREATE TABLE CITY(
CITYCODE CHAR(S) PRIMARY KEY,
CITYNAME CHAR(30),
SIZE INT,
AVGTEMP INT,
POPULATIONRATE INT,
POPULATION INT,
Ve
LONG ANSWER Type Questions
1. Answer the questions (i) to (v) on the basis of
the following tables SHOPPE and ACCESSORIES.
TABLE: SHOPPE
is ‘SName ‘Area
Oe
1 _ABC Computeranics cP
—SEL_A8C Computeronics GP
Soe At intotech Media GK
eh Meda KN
Ans,
219
___SNamo
13 Toch Shoppo.
Nohru Place
"8005 __Hilach Toch Store Nehru Place
TABLE: ACCESSORIES
ce ore co
Eo Et cet ee a
‘403 Keyboard
oan
Se a
roca neerac anna oad
rarlasico ono ge
me on
a
T10 Hard Disk 4500 S03,
(i) To display Name and Price of all the
Accessories in ascending order of their Price.
(li) To display Id and SName of all Shoppe
located in Nehru Place.
{l) To display Minimum and Maximum Price of
‘each Name of Accessories.
(iv) To display Name, Price of all Accessories and
their respective SName, where they are
available.
(v) To display name of accessories whose price is,
greater than 1000.
(i) SELECT Name, Price
FROM ACCESSORIES
ORDER BY Price;
(i) SELECT Id, SName
FROM SHOPPE
WHERE Area = ‘Nehru Place’;
SELECT MIN(Price) “Minimum Price”,
MAX(Price) “Maximum Price”, Name
FROM ACCESSORIES
GROUP BY Name;
SELECT Name, Price, SName
FROH ACCESSORIES A, SHOPPE S
WHERE A.Id = S.1d;
but this query enable to show the result because
‘Ald and S.1d are not identical.
(v) SELECT Name From
ACCESSORIES
WHERE Price>1000;
i)
(wy)
© scanned with OKEN Scanner20:
2. Consider the following tables STORE and
| AllZnone | COMPUTER SCIENCE Class 12th
STRCDE POINTS GRADE
2 NUL
SCODE NAME AGE
answer the questions: 06 Gagan ce AB Bera at NUL
TABLE: STORE to Kumar 19 NU
Teme tone oy Raw A
= arenes Classic 8 s 2 31-JUN-09 Ho awe 13 NULL
eal carecreani toric Tye ny eS
2006 Gel Pen Classic 2 250 20 11-MAR-09 115 Kapil i : 2 a
2001 Eraser Small 22 220 19-JAN-09 120 Gurdeep 18 2 6 Loess
ano eeares Ses ios 0 amceoon Tame; STREAN
2009 Ball Pen 05 21190 18 _0aNOv.09 —aae arm
Write SQL commands for the following 1 SCIENCE+COMP-
oe cb
(i) To display details of all the items in the
STORE table in ascending order of LastBuy. 3 SCIENCE+ECO
(ii) To display ItemNo and Item name of fi 4 COMMERCE +MATHS
thse en om STORE ate <_ covets Matis
(es Toate te eins cede i ice Sean TT
Supplier code (Scode) is 22 or Quantity in Store = ay
(Qty) 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.
(¥) To display the item with its quantity which
include pen in their name.
Ans. (i) SELECT * FROM STORE ORDER BY LastBuy:
(i) SELECT ItemNo, Item FROM STORE WHERE
Rate>15:
(iil) SELECT * FROM STORE WHERE Scode = 22
OR Oty>110;
(jv) SELECT MIN(Rate) FROM STORE GROUP BY
Scode:
(¥) SELECT Ttem, Oty FROM STORE WHERE Item
LIKE ‘#Penk!;
3. Consider the following tables STUDENT and
STREAM. Write SQL commands for the
statements (i) to (v).
TABLE: STUDENT
SCODE NAME AGE STRCDE POINTS GRADE
101 Amit ot 6 NUL
102 Aun isa 4 NUL
103 Zaheer 142 1 NUL
() To display the name of streams in
alphabetical order from table STREAM.
(ii) To display the number of students whose
POINTS are more than 5.
(iii) To update GRADE to'A'for all those
students, who are getting more than 8 as
POINTS.
(iv) ARTS+MATHS stream is no more available.
Make necessary change in table STREAM.
(v) To display student's name whose stream
name is science and computer.
Ans. (i) SELECT STRNAME FROM STREAM ORDER BY
STRNAME:
(i) SELECT COUNT(*) FROM STUDENT WHERE
POINTS > 5;
(ii) UPDATE STUDENT SET GRADE = ‘A’ WHERE
POINTS > 8;
(iv) DELETE FROM STREAM WHERE STRNAME
= TARTS +, MATHS 5
(©) SELECT NAME FROM STUDENT
WHERE STUDENT. STRCDE = STREAM.STRCDE
AND STRNAME = "SCIENCE + COMP";
© scanned with OKEN ScannerStructured Query Language
Consider the following tables GARMENT and
FABRIC. Write SQL commands for the
statements (1) to (v).
‘TABLE: GARMENT
eee
GOODE DESCRIPTION PRICE FCODE READYDATE
yoo PENCILSKIAT —_1150__—~FO3_‘19-DEC-08
_ina_e
“ooo FORMAL SHIRT 1250 FO1_—2AN-08
‘poi? INFORMALSHIRT 1650 __FO2 __O6JUN-O8
tones _6ABY TOP 750 f03__O7-APROT
‘0090 _TULP SKIRT #50 Foe __31-MARO?
‘oo9 EVENINGGOWN 650 FOS _OBUN-08
voma INFORMAL PANT 1500 F02 20-OCT-08
Trot FORWAL PANT 1950 FO! 09-MAR-0B
10020 FROCK
30a FROCK __
221
(iv) SELECT FCODE, MAX(PRICE), MINCPRICED
FROM GARMENT GROUP BY FCODE:
(W) SELECT DESCRIPTION, PRICE FROM GARMENT
WHERE GARMENT. FCODE = FABRIC. FCODE
AND TYPE = "SILK":
5, Consider the following tables. Write SOL
commands for the statements (i) to (v).
TABLE: SENDER
‘SenderlD SenderName SenderAddress __SendorCity
NDOT Ruain ‘Now Dethi
Muc2 Hi Sinha 12, Newtown __ Mumbai
MuIs Suna 27K Park Sreet__ Mumbai
NDSO_TPrasad_ ‘122K, SDA__New Debhi
TABLE: RECIPIENT
RociD SenderlO RecName RocAddress _RcCity
“R005 _NOO1 _Bajpayeo 5, Centra Avenue Kolkata
089 _ SLACKS NOo3__MUG2 _$Mahajan_116,AVinar New Del
“MUI9__NOO1_HSingh 2A. Andheri East_ Mumbai
“Mu32_—MUIS PK Swamy _B5.CS Torminus_Mumbal
O43 NDSO S$ Tripathi 19,810, Now Det
Mayur Vihar
Fog SILK () To display the names of all Senders from
Mumbal,
FOI TERELENE
() To display GCODE and DESCRIPTION of
‘each GARMENT in descending order of
GCODE.
(U) To display the details of all the GARMENTS,
which have READYDATE in between
08-DEC-07 and 16-JUN-08 (inclusive of both
the dates).
(Ui) To display the average PRICE of all the
GARMENTS. Which are made up of FABRIC
with FCODE as FO3.
(iv) To display FABRIC wise highest and lowest
price of GARMENTS from GARMENT table.
(Display FCODE of each GARMENT
alongwith highest and lowest price.)
(¥) To display garment's description with their
ro Price whose fabric is silk.
@ SELECT GCODE. DESCRIPTION FROM GARMENT
ORDER BY GCODE DESC:
(i) SELECT*FROM GARMENT
WHERE READYDATE BETWEEN *08-DEC-07°
AND *16-JUN-08": :
(ii) SELECT AVGCPRICE) FROM GARMENT WHERE
FCODE = *F03
(i) To display the RecID, SenderName,
SenderAddress, RecName, RecAddress for
every Recipient.
(lil) To display Recipient details in ascending
order of RecName.
(iv) To display number of Recipients from each
City.
(v) To display the detail of recipients who are in
Mumbai.
‘Ans. (i) SELECT Senderliame FROM SENDER WHERE
SenderCity = ‘Munbal":
(i) SELECT RecID, Sendertane,
SenderAddress, Reclame, RecAddress
FROM RECIPIENT, SENDER WHERE
RECIPIENT. Sender10 = SENDER. Sender ID;
(iil) SELECT * FROM RECIPIENT ORDER BY
Reclame;
(iv) SELECT COUNT(*) AS “Ho. of
Recipients”, RecCity FROM RECIPIENT
GROUP BY RecCity:
(v) SELECT * FROM RECIPIENT
WHERE RecCity = “Humbai";
© scanned with OKEN Scanner222
6. Write the SQL commands for (i) to (v) on the
basis of the table HOSPITAL
Datootadm Charges Sox
zvene 300M
oor 200 F
02a 200M
ovine 200M
1910208
31_ Nuclear Medicine
()) To show all information about the patients of
Cardiology Department.
(i) To list the name of female patients, who are
in Orthopaedic Department.
(iii) To tist names of all patients with their date of
admission in ascending order.
(iv) To display Patient's Name, Charges, Age for
male patients only.
(¥) To display name of doctor are older than 30
years and charges for consultation fee is
more than 500.
Ans. (i) SELECT * FROM HOSPITAL WHERE
Department = ‘Cardiology’:
(i) SELECT Name FROM HOSPITAL WHERE
Department = ‘Orthopaedic’ AND Sex
Parl
(iil) SELECT Name FROM HOSPITAL ORDER BY
Dateofadm:
(iv) SELECT Name, Charges, Age FROM
HOSPITAL WHERE Sex = °M":
(W) SELECT AME FROM HOSPITAL WHERE Age>30
AND Charges>500:
7. Write SQL commands for (i) to (v) on the basis
| Allinone | COMPUTER SCIENCE Class 12th
No, ITEMNAME — TYPE
cri Cons Ta
5 Common zone _Doutio Bed
6 Jorrylook Baby cot
7 Vonking Office Table
8 Royaligor Sola
© Parkeiting Sola
oan
9/03/03 20000 20
11_ Wao Wood Douto Bod
eee rao 02091018
a ee
() To show all information about the Sofa from
the INTERIORS table.
(ji) To list the ITEMNAME, which are priced at
more than 10000 from the INTERIORS table.
(lil) To list ITEMNAME and TYPE of those items,
in which DATEOFSTOCK is before 22/01/02
from the INTERIORS table in descending
order of ITEMNAME.
(iv) To insert a new row in the INTERIORS table
with the following data
(14, ‘TrueIndian’, ‘Office Table’,
*25/03/03". 15000, 20)
(¥) To display the name of item with their price
which have discount more than 20.
‘Ans. (j) SELECT * FROM INTERIORS WHERE TYPE
= ‘Sofa’:
(i) SELECT ITEMNAME FROM INTERIORS WHERE
PRICE > 10000;
SELECT ITEMNAME, TYPE FROM INTERIORS
WHERE DATEOFSTOCK < *22/01/02"
ORDER BY ITEMNAME DESC:
(iv) INSERT INTO INTERIORS VALUES
(14, "TrueIndian’, “Office Table’.
*25/03/03" .15000, 20);
(¥) SELECT ITEHNAM, PRICE FROM INTERIORS
WHRE DISCOUNT>20;,
8. Given the following tables for a database
of table INTERIORS. LIBRARY
TABLE: INTERIORS TABLE: BOOKS
DATEOF DISCO- Book_ Author_
No. ITEMNAME — TYPE DATEOF price DISCO” Book Id Name ‘Namo- Publishers Price Type Qty
1 Redrose Double Bed 23/02/02 32000 15. F0001 The Wiliam — First Publ 750 Fiction 10
Tears Hopkins
ella sie ea :
SN mayer eee | Ta fe Fi” wna 6
© scanned with OKEN Scannerstructured Query Language
BOOK
‘Author,
Book !4 Namo
Auor. pypishers rico Type Qty
0001 MyFirst Brain & EPB 250 Tet 10
C++ Brooke
a
yoo C++ AW. — TOH 925 Tot | 5
Brainwo Rossaine
tks.
ae
‘co00i Fast «Lata EPB 350 Cookery 8
Cook Kapoor
_TABLE:ISSUED_
F001 3
T0901 1
‘C0001 5
Write SQL queries for (i) to (v).
() To show Book name, Author name and Price
of books of EPB Publishers.
{@) Tolist the names from books of Fiction type.
(ii) To display the names and price of the books
in descending order of their price.
iv) To increase the price of all books of First Publ
Publishers by 50.
(v) To display the detail of book whose quantity
Jess than 10,
‘Ans. () SELECT Book_Name, Author_Name, Price
FROM BOOKS WHERE Publishers = ‘EPR*:
(i SELECT Book_Name FROM BOOKS WHERE Type
= ‘Fiction
(ii) SELECT Book Name, Price FROM BOOKS
ORDER BY Price DESC:
(je) UPDATE BOOKS SET Price = Price + 50
WHERE Publishers = ‘First Publ":
() SELECT *FROM BOOKS
WHERE oty<10;
9, Write SQL commands for (i) to (v) on the basis
of table STUDENT
TABLE: STUDENT
SNO NAME STREAM FEES AGE SEX
1_ARUNKUMAR COMPUTER 750.0017 M
2 _DIWAJENEJA COMPUTER 750.00 18 __F
3_KESHARMEHRA BIOLOGY 500.00 16 __M.
4 HARISHSINGH ENG.DR 950.00 18M.
HI ECONOMK 19
§ NISHAARORA COMPUTER 750.00 15 F.
7 _DEEPAKKUMAR ECONOMICS 300.0016 __M
8 _SARIKAVASWANI BIOLOGY 500.00
(i List the name of all the students, who have
taken stream as COMPUTER.
223
(W) To count the number of female students.
(lil) To display the number of students stream wise.
(iv) To display all the records in sorted order of
name.
(v) To display the stream of student whose name
is Harish.
‘Ans. ()) SELECT NAME FROM STUDENT WHERE STREAM
"COMPUTER" :
(i) SELECT COUNT(*) FROM STUDENT WHERE SEX
aa
(ii) SELECT STREAM, COUNT(*) FROM STUDENT
GROUP BY STREAM:
(iv) SELECT * FROM STUDENT ORDER BY NAME:
(%) SELECT STREAM FROM STUDENT
WHERE NAME LIKE "SHARISHE";
10. Given the following family relation. Write SQL
‘commands for questions (i) to (v) based on the
table FAMILY
TABLE: FAMILY
No. Name female, Male Income Occupation
1 Misha 3 2 ‘Sevice
2 Gupta 4 1 Business
3_Khan 6 3 Mixed
4 Chaddha 2 2 Business
Yadav 7 2 Mixed
6_Jos 3 2 Senice
7_Mauya 6 3 Farming
8 Rao 5 2 10000 Senice
() To select all the information of family, whose
Occupation is Servic
(ii) To list the name of family, where female
members are more than 3.
(iii) To list all names of family with income in
ascending order.
(iv) To count the number of family, whose income
is less than 10000.
(¥) To display the detail of family whose income
is more than 10000 and occupation is mixed
type.
‘Ans. (i) SELECT * FROM FAMILY WHERE Occupation
= ‘Service's
(i) SELECT Name FROM FAMILY WHERE
FemaleMembers > 3:
(ii) SELECT Name, Income FROM FAMILY ORDER
BY Income;
(iv) SELECT COUNT(*) FROM FAMILY WHERE
Income < 10000;
(v) SELECT *FROM FAMILY
WHERE INCOME >. 10000
AND Occupation = “Mixed”
© scanned with OKEN Scanner226
15, Write SQL commands for (i) to (v) on the basis
of table EMPLOYEE
‘TABLE: EMPLOYEE
1S nawe easic veramtuent ORO ace sex
1 KARR mo PERSONNEL —aTRBOT =
2 OVAKAR esto COMPUTER _ov—8 at
3 DIWA 7300 ACCOUNTS 19/02/0734 Fr
TTC ARIN 8) PERSONEL oveNRS =)
5 SONA 8500 ACCOUNTS 20186 90
@ JOHN 00 FRANCE 20am? 08M
7 ROBERT tos) PERSOWWEL_eo0aR? 9M
8 RUBINA 9450 MAINTENANCE 22/0298 37 F
9 VIKAS 7500 COMPUTER 13/01/94 41M.
40 MOHAN 9300 MAINTENANCE 19/02/98 97M
() Which command will be used to list the
names of the employees, who are more than
34 years old sorted by NAME.
(a) SELECT NAME FROM EMPLOYEE WHERE
‘AGED34 ORDER BY NAME;
(b) SELECT * FROM EMPLOYEE WHERE
AGE>34 ORDER BY NAME:
(©) SELECT NAME FROM EMPLOYEE WHERE
AGED34;
(@ SELECT NAME FROM EMPLOYEE AGE>34
ORDER BY NAME:
(i) Write a query to display a report, listing
NAME, BASIC, DEPARTMENT and annual
salary. Annual salary equals to BASIC * 12.
(Gi) Insert the following data in the EMPLOYEE
table
11, ‘VAY’, 9300, ‘FINANCE; '13/7/98', 35,"M"
(iv) Write a query to count the number of
employees, who are either working in
PERSONNEL or COMPUTER department.
(v) Write the degree and cardinality of the table
EMPLOYEE.
‘Ans. (i) (a) SELECT NAME FROM EMPLOYEE WHERE AGE
> 34 ORDER BY NAME:
(i) SELECT NAME, BASIC, DEPARTMENT,
BASIC*12 “Annual Salary” FROM
EMPLOYE:
(i) INSERT INTO EMPLOYEE VALUES(11,
“VIOAY", 9300, “FINANCE”, °13/7/98".
35.°M"):
(iv) SELECT COUNT(*) FROM EMPLOYEE
| Allynone | COMPUTER SCIENCE Class 12th
WHERE DEPARTMENT = “PERSONNELY ‘OR’? >
DEPARTMENT = ‘COMPUTER’ :
(o) Degree of the given table's 7 and cardinality is 10
16. Write SQL commands for (i) to (v) on the basis
of table COLLEGE
TABLE: COLLEGE
No Name Age Department Dateotvoin Basic Sex
1 Shalaz 45 Biology ya/02/88 10500 M
2 Sameera 54 Biology yoroveo 9500 F
3 Yagyen 43. Physics 27/0298 8500 M
“4 Pratyush 94 Chemisty —_‘11/01/93__7500_M
5 Aen 51 Mathematics 22/01/91 _8500__ M
%@ Reeta 27 Chemisty 14/02/04 9000
7 Unashi 29 Biology 10/0293 8500 F
@ Teena 35 Mathematics 02/02/89 10500__F.
@ Vien 49 Mathematics 03/01/88 9000 M_
40 Prakash 22. Physics 1710282 8000 M
(i) Write a query to change the Basic salary to
10500 of all those teachers from COLLEGE,
who joined the COLLEGE after 01/02/89 and
are above the age of 50.
(ii) Write a query to display Name, Age and Basic
ofall those from COLLEGE, who belong to
Physics and Chemistry department only.
(iil) Which command will be used to delete a row
from table COLLEGE, in which NAME is
VIREN?
(jv) Insert the following data in the given table
COLLEGE
11,Saurav’, 50, ‘Chemistry’, '18/05/93',
12000,'M’
(¥) Identify the attribute best suitable to be
declared as a primary key.
‘Ans. (j) UPDATE COLLEGE SET Basic = 10500
WHERE DateofJoin>'01/02/89" AND
Age>50:
(i) SELECT Name, Age, Basic FROM COLLEGE
WHERE Department="Physics* OR
Department="Chemistry';
(iil) DELETE FROM COLLEGE WHERE Name
= ‘VIREN"
(iv) INSERT INTO COLLEGE VALUES (11,
‘Saurav’, 50, ‘Chemistry’, ‘18/05/93".
12000, *M");
(#) No attribute is best suitable to be declared as 4
primary key.
© scanned with OKEN ScannerStructured Query Language
CASE BASED Type Questions
{.. Consider the following table Persons and
"newer the questions that follows
PID LastName FirstName Address _ City
yor Hansen Ola Timoteivn 10__Sandnes
402 _Svendson Tove Borgyn23_Sandnes
03 Petterson Kari Storgt 20 _ Stavanger
04 _Nisen Johan Bakken 2 _ Stavanger
05 Tessem Jakob NULL NULL.
(i) Write the degree and cardinality of table
Persons.
‘Ans, Degree =5
cardinality = 5
(ay demtty the attribute best suitable to be
declared as a primary key.
Ans, FD
‘Which command is used to show the content
of table Persons?
‘Ans. DESC Persons:
(iv) To display the detail of persons whose city is
Sandnes.
‘Ans, SELECT*FROH Persons
WEHRE City=*Sandnes*;
(\) Insert the row with value (106, John, Miller,
NULL, Sandnes)
‘Ans. INSERT INTO Persons (106, *John*,
*Willer*, NULL, "Sandnes");
2, Consider the table Teacher and answer the
questions that follow
PID Name Salary Subject DOJ
Tor_Aadhna 17000 Science 2013-01-08
To2_Fitka 15000 Mathematics 2013-12-14
Jo3 Ravindra 12000
Tos _Dushyant 15000
Science 2013-11-23
English 2014-01-10
ToS Swati 20000 Mathematics 2014-02-10
106 _Shrey 18000 Computer 2014.06.07
() Write the degree and cardinality of table
Teacher.
Ans. Degree = 5 Cardinality = 6
(i) Find the attribute best suitable to be declared
as a primary key.
Ans. TD
227
(lil) To display the detail of teacher whose subject
is comptuer.
Ans. SELECT*FROM Teacher WHERE Subject =
“Computer”:
(iv) Find the output, SELECT Name FROM
‘Teacher WHERE Salary > 15000;
Ans.
Nam
Aradhna
(v) To display the name of teacher whose data of
Joining is 2014-02-10;
‘Ans, SELECT Name FROM Teacher
FROM 00J = "2014-02-10";
3. Ina Database, there are two tables with the
instances given below:
Table : STUDENTS
ADMNO NAME CLASS SEC ANO PPORES prone
w2i1__ MEENA 2A D4 A286 9245678
12i2__VANI Ait B25 456789
1219 MEENA 128A 1 NULL NULL
1214 KARISH 108 BB —«3—AB-234 4967690
Table : SPORTS
‘ADMNO- GAME COACHNAME GRADE
1215 CRICKET MR.RAVI A
1213 VOLLEYBALL _MRAMANDEEP_ 8
1211 VOLLEYBALL -MR.GOVARDH A
AN,
1212 BASKETBALL MR. TEWARI 8
[CBSE Question Bank
() Choose the command to display name and
game of those students whose address is
available in STUDENTS table.
(a) SELECT NAME, GAME FROM STUDENTS,
‘SPORTS WHERE
STUDENTS. ADHNO*SPORTS. ADHNO. AND
ADDRESS IS NOT NULL:
(W)SELECT NAME, GAME FROM STUDENTS,
SPORTS WHERE
STUDENTS. ADMNO=SPORTS.ADMNO AND
ADDRESS IS NULL;
(©) SELECT NAME, GAME FROM STUDENTS,
SPORTS WHERE
STUDENTS. ADMNO=SPORTS . ADMNO,
ADDRESS 1S NULL:
© scanned with OKEN Scanner228
(@)SELECT NAME, GAME FROM STUDENTS,
SPORTS WHERE
STUDENTS. ADHNO-SPORTS.ADHNO NOT 9
ADDRESS TS NULL:
Ans. (a) For writing the query it is required to select
NAME and GAME field from STUDENTS table and
SPORTS table using an equi join operation.
(ii) Identify the statement to delete a column
phone from the table STUDENTS.
(@)ALTER TABLE STUDENTS OROP PHONE:
(b)DROP PHONE:
()UPDATE DROP PHONES j
(@)DELETE FROM STUDENTS WHERE DROP
PHONES
‘Ans.(o) ALTER command is used, if there is any
updation required in definition of a table. DROP
clause is used with ALTER cofrimand to delete a
column from a table.
Syntax to delete any column from table is
ALTER TABLE DROP
host ocalhost". con.close ( )
user = “systen". 8. Consider the table Student whose fields are
passwd = “test”. ‘SCODE Namo Age strede_ Points Grade
ese yey
database “Heventory Corea ae wee eee HU
= ADD 102 Arjun +13. 3 4 NULL
te ("ALTER TABLE Item
Cursor.execute te racturingdate Date 103 Zaheer_—_14 2 1 NULL
woT NULL") 104__ Gagan 15 S 2 NULL
ycon.close () 405 __Kumar 1368 CNULL.
6. Consider the following table structure
Table: Faculty with fields as Write the Python code to update grade to'A' for
able:
all these students who are getting more than 8
F1D(P) as points.
Frame Ans. import mysql.connector as mydb
wiresdate con = nydb.connect (host = “localhost”.
oan user = “Admin”,
a ae
passwd = “Admin@l23”,
Write the Python code to create the above table. ee
‘Ans, inport mysql connector cursor = con.cursor ( )
aycon = mysq). connector.connect sql = “UPDATE Student SET Grade =
host = “localhost”, WHERE Points > 8”
user = “root”, try:
passwd = “systen’ cursor. execute (sql)
database = "Schoo!”) con.conmit ( )
cursor = rycon.cursor ( ) except :
db = cursor.execute (“CREATE TABLE con.rol back ¢ )
Faculty ( con.close ( )
FID varchar (3) Primary key,
aa veces ao) wr wee 9. Aresultset is extracted from the database using
Tnoee“yorchar C40), the cursor object (that has been
hire dite Date, already created) by giving the following
Salary Float)) statement. (CBSE SQP Term
nycon.close ( ) Nydata-cursor. fetchone()
7. Consider the table Persons whose fields are De ee
PID, LastName, FirstName, Address, City. cece ee
Write a Python code to add a new row but add ._ .
data only in the P_Id, LastName and columns as ae On ae dae aoa coe
pan, ePeeron, Ka respectively. Ans. () fetchon() method rere the nex ow faery
ins. import nysqi. result set and returns a single sequence, or none ifno
Meera eres more rows are avalableSo one record will be
con = mysql connector.connect
sa ” returned by fetchone( ) method.
(host local nost : (i) tuple is the datatype of Mydata object after the given
id * id command is executed. Tuples are used to store
‘adminel23”, hheterogeneous elements, which are elements
database = “systen”) belonging to different data types.
Sql= “INSERT INTO Persons (P_ID, LastName, 10. Write the code to create the following table
FirstName) VALUES Student with the following fields
ery, Oe Peterson". "Kart" ReilNe
: ‘irstName
cursor.execute (sql) LastName
© scanned with OKEN Scanner| Allznone | COMPUTER SCIENCE Class 12th
‘
240
Address nycon.conmit ( )
ContactNo except +
Marks aycon.roliback ( )
Course nycon.close ()
Rank 12. Consider the table MobileStock with following
Inthe table, Rank should be Good, Best, fields
Bad, Worst, Average. HLId, Hllane, Hoty, H_Supplier
Ant. impart mysql .connector Write the Python code to fetch all records with
aycon = mysql .connector.connect ( elds M1. M.Name and M. Supplier from
ast (or svoce laste database Mobile.
ea te Ans. import mysql connector as sydd
database ~ “School”) nycon = aydb.connect (host = “localhost”,
user = “root”. passwd = “systen",
cursor = ycon.cursor ( ) ts pass
db = cursor.execute database = “Hobile")
(CREATE TABLE Student( cursor = mycon.cursor ( )
RollNo —Int(5) Primary key, sql = “SELECT M_Id, MName, H_Supplier
FirstName varchar(30) NOT NULL, FROM obi TeStock™
LastNane — varchar(30), try:
Address varchar(50), cursor. execute (sql)
Contacto varchar(20). display = cursor. fetchall ©
peer leas for i in display
Course _char(20), pret)
Rank char(10) check (Rank IN(*Good",
‘Best’, ‘Bad’, ‘Worst’, ‘Average’))))
mycon.close ( )
M1. Consider the table Faculty whose columns’
except :
mycon.rollback ( )
mycon.close ( )
13. Consider the following table Traders with
name are
FID, Fame, Lname, Hire_date, following fields
Salary. Course_nane Tod Tame Gity
Write the code to insert the following record To Electronic Sales Mumbai
into the above table. =e
101 | Riya | Sharma [12-10-2004] 25000 | Java Advance ise ra ie biep Haus ate CR
102 [Kean | Mishra_| 3-12-2010 | 28000 | Data Stvetue ‘Write Python code to display the names of
‘Ans. inport aysql .connector those traders who are either from Delhi or
aycon = aysqi .connector.connect from Mumbai.
(host = “localhost”, Ans. import mysql. ‘connector
user = “root”, passwd = “systen", aycon = mysql ;connector.confect,
database = “Test”) ; (host = “locathost™, user = “root”,
cursor = con.cursor ( ) passwd = “systen",
sql = “INSERT INTO Faculty (F_1D, name, database = “Adnin)
Lnane, Hire_date, Salary. cursor = mycon. cursor ( )
Course_Nane) VALUES sq] = “SELECT * FROM Traders WHERE
(as, $5, 15,45, 45, 35)" City = ‘Mumbai OR City = ‘Delhi’
val = (101, ‘Riya’, ‘Sharma’, try:
Seb more | ante ; cursor.execute(sq1)
Rivdnee’}" luz, *kivtane, dis = cursor.fetchall (-)
“wishea’, *3-12-2010", 28000, Pe oeagae ty
Data Structure’)] Se
try: nycon.rolIback (
cursor.executemany (sql, val) car cies
© scanned with OKEN Scanner4 re
241
Interface Python with SQL
LONG ANSWER Type Questions
J. Create following table using Python code where
Database - Test ~ Moot 2000
Table = Watches ‘oo? Gurgaon 19 3500
Username - Root 1003 __Hharka New Oothi_21_ 2100.
te M008 Sachn Faridabad __18 3800
Password - __ System Mou
Write the Python code for the following '
Watchid WatchName Price Type Qty. store
Woo! High Time 10000_Unisex_100
15000 Ladies 150
Woo? _Lite Time
woos Wave, 20000 Gents __200,
7000 Unisex __ 250
‘25000 _Gonls__ 100
woo! High Fashion
WOS__ Golden Time
ng. ieport mysai.connector
ty = mysql .connector connect
(nost = “localhost”,
user = “Root”, passwd = “System”,
database = “Test”)
cursor ( )
cursor =
gp = cursor.execute (“CREATE TABLE Watches
(watch_Id varchar(5) Primary Key,
watchName char(20) NOT NULL,
Price float,
Type varchar (20),
Qty_store Int(5) NOT NULL)"
sql = “INSERT INTO Watches
(Watchid, WatchName, Price, Type,
Qty_store) VALUES (Zs, 5, %5,
ts, 35)"
val = ((“WOO1", “High Time”, 10000,
“Unisex”, 100),
(wo02", “Life Time”, 15000,
“Ladies”, 150),
woos",
“Gents”
woos
“unisex”, 250),
(*WO05", “Golden. Tim
“Gents”, 100))
try:
cursor. executemany (sql, val)
myscommit ( )
except
my.roliback ( )
my.close ( )
(W) Update the Address of member whose
Memberld ts M003 with Noida.
(il) Delete the record of those member whose
name Is Sachin.
Ans, (i) Import mysql -connector
mycon = mysql connector connect
(host = “localhost”,
user = “Admin”, passwd = “Admin@l23™.
database = “Systen”) -
cursor = mycon.cursor ( )
try:
cursor.execute (“UPOATE Club SET
Address = “Noida” WHERE Menberid
= "M003")")
mycon.conmit ( )
except :
mycon.rol!back ( )
mycon.close ( )
import mysql. connector
mycon = mysql. connector.connect
(host = “locaThost™,
user = “Admin”,
passwd = “Adnin@l23",
database = “Systen")
cursor = mycon.cursor ( )
try:
Cursor.execute (“DELETE FROM Club
WHERE MemberName = *Sachin*)*
cursor.conmit ( )
except:
mycon.roliback ( )
mycon.close ( )
3. Consider the table MobileMaster
Mid M_Company MName M_Prico M_Mt_Oate
BOOT Samsung _Galayy __4500_ 2014-02-12
MB002_Nokia NI100 2250 2011-04-15
‘MB003_Sony ExperiaM 9500 _ 2017-11-20
MB004_Oppo SolieEx 8500 _2010-08-21
© scanned with OKEN Scanner242
Write the Python code for the following
() To display details of those mobiles whose
price Is greater than 8000.
(ii) To increase the price of mobile Samsung by
2000.
Ans. (i) import mysql.connector as mydb
mycon = mydb. connect
localhost",
passwd = “system",
database = “Admin”)
cursor = mycon.cursor ( )
sql = “SELECT * FROM MobileMaster
WHERE MLPrice > 8000"
try:
cursor.execute (sql)
display = cursor. fetchall ( )
for i in display:
print(i)
except:
mycon.rollback (.)
mycon.close ( )
Gi) import mysql.connector as mydb
‘mycon = mydb. connect
(host = “localhost”,
user = “root”,
passwd = "system",
database = “Admin”)
cursor = mycon.cursor ( )
Sq] = “UPDATE MobileMaster SET M_Price
MPrice + 2000
WHERE M_Company = ‘Samsung’ ”
ee try:
cursor.execute (sql)
mycon.commit ( )
except
mycon. rollback ( )
mycon.close( )
4. Write the Python code for (i) and (fi) on the
basis of table College.
| Allnone | COMPUTER SCIENCE Class 194,
ees
No Namo Ago Dopariment Datootloln Basle Gey
1 Aon 61 Mathomatics 22/01/81 8500 _ iy
2 Roota 27 Chomistyy 14/02/04 9000
‘3Viron 49 Mathomatics 03/01/88 __ 9000 M4
“4 Prokash 22 Physics 17/02/02 8000
5 Shalaz 45 Biology 19/02/68 10500 _m4
© Urvashi 29 Biology ‘1002/03 8500_F
() To insert a new row in the table College with
the following data
15, "Atin", 27, “Physics”, "15/05/02", 8500, *M"
(li) To delete a row from table in which nam
Viren.
Ans, (i) import mysql.connector as aydb
con = mydb.connect (
host = “localhost”,
user = “root
passwd = “admin@123”,
database = Management”)
cursor = con.cursor ()
sq] = “INSERT INTO College (No, tame,
age, Department, Dateofdoin,
Basic, Sex) VALUES
(15, ‘atin’, 27, ‘Physics",
"15/05/02", 8500, *M")”
cursor.execute (sq1)
con.close ( )
(i) import mysq).connector as mydb
con = mydb. connect
(host = “localhost”,
user = “root”,
passwd = “admin@l23”,
database = “Management”)
cursor = con.cursor ( )
try:
cursor.execute (DELETE FROM College
WHERE Name = “Viren” " )
con.commit ( )
except +
con.rollback ( )
con.close ( )
© scanned with OKEN Scanner