UT1 CS Notes DBMS MySQL Python Interface
UT1 CS Notes DBMS MySQL Python Interface
DATABASE MANAGEMENT
A database is an organized collection of interrelated data that serves many applications. Its is generally
a computer record keeping system. In a database we can not only store the data but we can also change
the data as per the user requirement. These databases are generally managed by special software called
DBMS (Database Management System)
86 | P a g e
Multiple choice Questions(MCQ):
1 DBMS stands for_____________
a)Data Base Management Software b) Data Base Maintenance System
c)Data Basic Management System d) Data Base management system
2 In RDBMS, R stands for_________
a)Relational b) Rotational c) Rational d)None of the above
3 A Database contains one or more_______
a)Data b) Tables c) Files d)Links
4 What is not true in respect of DBMS?
a)Database enforces standards b)Database increases redundancy
c)Database facilitates sharing of data d) Database helps to maintain integrity
5 Cardinality is total ___________
a)number of rows in a table b)number of columns in a table
c)number of data items in a table d) none of the above
6 Degree refers to total_________
a) number of rows in a table b) number of columns in a table
c) number of data items in a table d) none of the above
7 Data about data is _________
a) Data redundancy b) Meta Data
b) Database schema d) None of the above
8 Repetition of data is called _________
a) Data redundancy b) Data Description
c) Data inconsistency d) None of the above
9 Mismatched redundant copies of data is known as data ___________
a)Dependence b) Inconsistency c) Isolation d) Redundancy
10 A ________________is an organized collection of structured data.
a)Database b) File c) DBMS d) Information
11 A data ______________ is a set of rules that define valid data.
a)Query b) Constraint c) Dictionary d) All of the above
12 A relational database consists of a collection of ______________
a)Fields b) Records c) Keys d) Tables
13 A row in a database is called ______________
a)Fields b) Records c) Keys d) Tables
14 The term ____________ is used to refer to a field in a table.
a)Attribute b) Row c) Tuple d) Instance
15 Which of the following statements is not true about relational database?
a) Relational data model is the most widely used data model.
b) The data is arranged as a collection of tables in relational database.
c) Relational database increases data redundancy and inconsistency.
d) None of the above.
ANSWERS:
1 d 2 a 3 b 4 b
5 a 6 b 7 b 8 a
9 b 10 a 11 b 12 d
13 b 14 a 15 c
87 | P a g e
Very Short Answer Questions
1 What is meant by a database?
2 Define primary key?Give an example.
3 What do you mean by candidate key?
4 What is meant by degree and cardinality of a table?
5 What is meant by DBMS?
6 What is meant by database schema?
7 What is meant by data constraint?
8 What is meant by relation?
Very Short Answer Questions: Answers
1 A database is an organized collection of structured information, or inter-related data,
typically stored in a computer system.
2 A primary key is a column or set of columns that contain values that uniquely identify
each row in a table.
For example Rno can be primary key of the table student.
Table:Student
RNO NAME MARK
100 Tanay 30
101 Kiran 50
102 Manu 30
3 It is an attribute or a set of attributes capable of being the Primary Key, to uniquely
identify each record in that table.
89 | P a g e
It is used to create database schema and can be used to It is used to add, retrieve or update the data.
define some constraints as well.
It basically defines the column (Attributes) of the table. It add or update the row of the table. These
rows are called as tuple.
DATATYPES
• Text Data types
Char(size) – fixed length of size bytes
Varchar(size)-variable length of size bytes
Varchar2(size)-variable length of size bytes
• Number Data types
Integer(size)or Int- It represents a number without decimal point
Float(Size)-It represents a floating point number
Real-Same as float but no size argument is used
• Date data type
Date , Time
CONSTRAINTS
A Constraint is a condition or check applicable on a field or set of fields.
Types of Constraints:
• Unique Constraint :-This ensures that no rows have the same value in the specified column(s)
Example
CREATE TABLE EMP (ecode integer unique,
ename char(20),sex char(1),
grade char(2));
Unique constraint applied on ecode of EMP table ensures that no rows have the same ecode
value .
• Primary key Constraint:-
This declares a column as the primary key of the table. This is similar to unique constraint except
that one column (or one group of columns) can be applied in this constraint .
The primary key cannot allow NULL values but Unique key allows NULL values.
The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table is
created:
CREATE TABLE Persons
(ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int PRIMARY KEY (ID));
• Not null: -This constraint ensures column should not be NULL
Example:
CREATE TABLE EMP(
ecode integer Not null unique,
ename char(20),
sex char(1),
grade char(2));
90 | P a g e
DATABASE COMMANDS IN MYSQL
• CREATE DATABASE
CREATE DATABASE is the SQL command used for creating a database in MySQL.
Imagine you need to create a database with name “movies”. You can create a database in MySQL by
executing following SQL command
Syntax: mysql>CREATE DATABASE movies;
• SHOW DATABASES
You can see list of existing databases by running following SQL command.
Syntax: mysql>SHOW DATABASES;
• USE
You can use SQL command USE to select a particular database.
Syntax: mysql>USE database_name;
• DROP DATABASE
The DROP DATABASE statement is used to drop an existing SQL database.
Syntax: mysql>DROP DATABASE database_name;
CREATE TABLE
The CREATE TABLE statement is used to create a new table in a database.
Syntax:
CREATE TABLE table_name ( column1 datatype, column2 datatype, column3 datatype, ....);
Example: The following example creates a table called "Persons" that contains five columns:
PersonID, LastName, FirstName, Address, and City:
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255) );
SHOW TABLES
We can get the number of table information of a database using the following statement:
mysql> SHOW TABLES;
DESCRIBE TABLE
Use the DESCRIBE command to show the structure of the table, such as column names, constraints on
column names, etc. The DESC command is a short form of the DESCRIBE command. Both DESCRIBE and
DESC commands are equivalent.
Syntax The following are the syntax to display the table structure:
mysql> DESCRIBE | DESC table_name;
ALTER TABLE
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table. The ALTER
TABLE statement is also used to add and drop various constraints on an existing table.
ALTER TABLE - ADD Column/Attribute
• ALTER TABLE - ADD A COLUMN
ALTER TABLE table_name ADD column_name datatype;
Example ALTER TABLE Customers
ADD Email varchar(255);
DROP TABLE
The DROP TABLE statement is used to drop an existing table in a database.
Syntax DROP TABLE table_name;
DROP TABLE Shippers;
INSERT:
The INSERT INTO statement is used to insert new records in a table.
INSERT INTO Syntax:
It is possible to write the INSERT INTO statement in two ways:
1. Specify both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
2. If you are adding values for all the columns of the table, you do not need to specify the column names
in the SQL query. However, make sure the order of the values is in the same order as the columns in
the table. Here, the INSERT INTO syntax would be as follows:
INSERT INTO table_name VALUES (value1, value2, value3, ...);
DELETE:
The DELETE statement is used to delete existing records in a table.
DELETE Syntax:
DELETE FROM table_name WHERE condition;
Note: Be careful when deleting records in a table! Notice the WHERE clause in the DELETE statement.
The WHERE clause specifies which record(s) should be deleted. If you omit the WHERE clause, all
records in the table will be deleted!
The following SQL statement deletes all rows in the "Customers" table, without deleting the table:
DELETE FROM Customers;
UPDATE
The UPDATE statement is used to modify the existing records in a table.
UPDATE Syntax: UPDATE table_name SET column1 = value1, column2 = value2, ...
WHERE condition;
UPDATE Table
92 | P a g e
The following SQL statement updates the first customer (CustomerID = 1) with a new contact person
and a new city.
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
SELECT
The SELECT statement is used to select data from a database.
The data returned is stored in a result table, called the result-set.
SELECT Syntax: SELECT column1, column2, ... FROM table_name;
Here, column1, column2, ... are the field names of the table you want to select data from. If you want to
select all the fields available in the table, use the following syntax:
SELECT * FROM table_name;
WHERE Clause:
The WHERE clause is used to filter records.
It is used to extract only those records that fulfill a specified condition.
WHERE Syntax: SELECT column1, column2, ...FROM table_name WHERE condition;
IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
The IN operator is a shorthand for multiple OR conditions.
IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
BETWEEN Operator
The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates.
The BETWEEN operator is inclusive: begin and end values are included.
BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
LIKE Operator
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
There are two wildcards often used in conjunction with the LIKE operator:
• The percent sign (%) represents zero, one, or multiple characters
• The underscore sign (_) represents one, single character
The percent sign and the underscore can also be used in combinations!
LIKE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
SQL Aliases
SQL aliases are used to give a table, or a column in a table, a temporary name.
Aliases are often used to make column names more readable.
An alias only exists for the duration of that query.
An alias is created with the AS keyword.
Alias Column Syntax: SELECT column_name AS alias_name FROM table_name;
94 | P a g e
Alias Table
Syntax: SELECT column_name(s) FROM table_name AS alias_name;
DISTINCT
The SELECT DISTINCT statement is used to return only distinct (different) values.
Inside a table, a column often contains many duplicate values; and sometimes you only want to list the
different (distinct) values.
SELECT DISTINCT Syntax:
SELECT DISTINCT column1, column2, ...FROM table_name;
SELECT Example Without DISTINCT
The following SQL statement selects all (including the duplicates) values from the "Country" column in
the "Customers" table:
Eg: SELECT Country FROM Customers;
Now, let us use the SELECT DISTINCT statement and see the result.
SELECT DISTINCT Examples
The following SQL statement selects only the DISTINCT values from the "Country" column in the
"Customers" table:
SELECT DISTINCT Country FROM Customers;
The following SQL statement lists the number of different (distinct) customer countries:
SELECT COUNT(DISTINCT Country) FROM Customers;
NULL value
A field with a NULL value is a field with no value.
If a field in a table is optional, it is possible to insert a new record or update a record without adding a
value to this field. Then, the field will be saved with a NULL value. It is not possible to test for NULL
values with comparison operators, such as =, <, or <>.
We will have to use the IS NULL and IS NOT NULL operators instead.
IS NULL Syntax
SELECT column_names FROM table_name WHERE column_name IS NULL;
IS NOT NULL Syntax
SELECT column_names FROM table_name WHERE column_name IS NOT NULL;
The IS NULL Operator
The IS NULL operator is used to test for empty values (NULL values).
The following SQL lists all customers with a NULL value in the "Address" field:
SELECT CustomerName, ContactName, Address FROM Customers WHERE Address IS NULL;
The IS NOT NULL Operator
The IS NOT NULL operator is used to test for non-empty values (NOT NULL values).
The following SQL lists all customers with a value in the "Address" field:
SELECT CustomerName, ContactName, Address FROM Customers WHERE Address IS NOT NULL;
ORDER BY
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in
descending order, use the DESC keyword.
ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
95 | P a g e
ORDER BY column1, column2, ... ASC|DESC;
Example
SELECT * FROM Customers
ORDER BY Country;
ORDER BY DESC Example
The following SQL statement selects all customers from the "Customers" table, sorted DESCENDING by
the "Country" column:
SELECT * FROM Customers
ORDER BY Country DESC;
ORDER BY Several Columns Example
The following SQL statement selects all customers from the "Customers" table, sorted by the "Country"
and the "CustomerName" column. This means that it orders by Country, but if some rows have the same
Country, it orders them by CustomerName:
Eg: SELECT * FROM Customers ORDER BY Country, CustomerName;
96 | P a g e
count( ) function
Count ( ) has got three formats:
count(*)
This function returns the number of rows in the table that satisfy the criteria of select statement.
In its counting, it includes duplicate rows and rows with NULL values in any of the column
Example:
Q: Count the number of employees in the employee table.
count(<col name>)
This function returns the number of not null values in the specified column, but includes duplicate values
in counting
Example
97 | P a g e
Grouping Records (Group by clause)
• To divide the rows in a table into smaller groups of information, group by clause is used.
• It combines all identical rows in a group of fields.
• A column name is used for grouping
Syntax: -
SELECT [DISTINCT] <COL LIST> FROM <TABLE NAME>
[WHERE <CONDITION>]
[GROUP BY < GROUP BY EXPR>]
[HAVING <CONDITION>]
ORDER BY <COL NAME>/<EXPR> ASC/DESC];
NOTE -
• Group by expression specifies the columns whose values determine the basics for grouping rows
• WHERE clause is always before GROUP BY if required.
Example
Q. Display the no of employees in each zone.
Q. Display the no of employees in each zone whose salary is greater than 32000
Having clause
• This clause is used to restrict rows resulting after grouping.
• Steps followed in execution of select with group by and having clause-
1. Rows are grouped according to the columns in the group by clause.
2. Then the group function is applied.
3. Groups matching with having clauses are displayed.
98 | P a g e
Example
Q. Display only whose departments with sum of salaries whose total salary is greater than 70000.
99 | P a g e
JOINS IN MYSQL
• A join is used when data from two or more tables is required.
• Rows in one table can be joined to the rows in another table based on the common values existing
in corresponding columns of two tables.
• Joins are used to retrieve data from tables related to each other with primary- foreign key
relationships.
• There are many types of joins:
EQUI JOIN
• Specified columns from the joining tables are checked for equality.
• Values from joining tables are retrieved only if the condition in where clause is satisfied.
SYNTAX:-
SELECT <column_name (s)>
FROM <table_name1>, <table_name2>, ...., <table_nameN>
WHERE <table_name1>.<column_name> = <table_name2>.<column_name>;
Q: To display the name of the employee and their department
Note-You should always qualify the columns when joining tables having the same name as
corresponding columns. To qualify the columns we use “.” (dot) operator.
Natural Join
This clause is based on all the columns in the two tables that have the same name. It selects the rows
from two tables that have equal values in the matched columns.
SYNTAX:-
SELECT [column_names / *] FROM table_name1 NATURAL JOIN table_name2;
Example- consider the same tables employee and department.
Q: To display the name of employee and department of all employee.
Note-No need to specify the column names to join. Works with same column name in both the tables.
The Resulting table has unique columns.
100 | P a g e
MULTIPLE CHOICE QUESTIONS
1 Which of the following SQL commands is used to use/select a particular database?
a. use b. select c. view d. project
2 Which SQL command is used to define and maintain physical structure or schema of table
in database like creating, altering and deleting database object such as table and
constraints?
a. DDL b. DML c. DCL d. TCL
3 Which commands is used to show all table in current using database?
a. display tables; b. show tables; c. view tables; d. select all tables;
4 Identify the MySQL Commands that belongs to DML category :
a. ALTER b. DROP c. DELETE d. CREATE
5 Which command is used in where clause to search NULL values in a particular column?
a. IS NULL b. IN NULL c. NOT NULL d. IS NOT NULL
6 Wild card operator (%,_) are used with?
a. count b. max c. like d. min
7 Prapti is presently working in the database SUBJECT. She wants to change and go to
the database RECORD. Choose the correct statement in MySQL to go to the database
RECORD.
a. GO TO DATABASE RECORD; b. USE DATABASE RECORD;
c. CHANGE DATABASE RECORD; d. USE RECORD;
8 Which SQL clause is used in database table to eliminate duplicate rows from the query
result?
a. group by b. distinct c. describe d. duplicate
9 Which SQL function is used to count the entire number of row in database table?
a. count b. count(*) c. max d. min
10 Which SQL function is used to determine the no. of row or non-null values?
a. min b. max c. count d. sum
ANSWERS
1 a 2 a 3 b 4 c 5 a
6 c 7 b 8 b 9 b 10 c
ASSERTION AND REASONING QUESTIONS
Directions: In the following questions, A statement of Assertion (A) is followed by a statement of
Reason (R). Mark the correct choice as:
(A) Both A and R are true and R is the correct explanation of A
(B) Both A and R are true and R is not the correct explanation of A
(C) A is true but R is false
(D) A is false but R is true
1 Assertion(A): The resultset refers to a logical set of records that are fetched from the
database executing an SQL Query.
Reason (R): Resultset stored in a cursor object can be extracted by using fetch(…)
functions.
2 Assertion(A): In SQL, aggregate function avg( )calculates the average value on a set of
values and produce a single result.
Reason (R): The aggregate functions are used to perform some fundamental arithmetic
tasks such as min( ), max( ), sum( ) etc.
101 | P a g e
3 Assertion(A): Primary key is a set of one or more attributes that identify tuples in a
relation.
Reason (R): The primary key constraint is a combination of the NOT NULL and UNIQUE
constraints.
4 Assertion(A): Foreign key is a non-key attribute whose value is derived from primary key
of another table.
Reason (R): Each foreign key refers a candidate key in a relation.
5 Assertion(A): The SELECT statement in SQL is used to retrieve data from one or more
tables.
Reason(R): The SELECT statement can be used to retrieve all columns or a subset of
columns from a table.
ANSWERS
1 b 2 B 3 a 4 b 5 a
SHORT ANSWER TYPE QUESTIONS
1 Deepika wants to remove all rows from the table BANK. But she needs to keep the structure
of the table. Which command is used to implement the same?
2 While creating table ‘customer’, Rahul forgot to add column ‘price’. Which command is used
to add new column in the table. Write the command to implement the same.
3 Mitali is a database programmer, She has to write the query from EMPLOYEE table to search
for the employee who are not getting any commission, for this she has written the query as:
SELECT * FROM EMPLOYEE WHERE commission=null; But the query is not producing the
correct output, help her and correct the query so that she gets the desired output.
4 Which clause is used to eliminate the duplicate rows from output?
5 Which command is used to see information like name of columns, data type, size.
6 Differentiate between order by and group by clause in SQL with appropriate example.
7 Categorize the following commands as DDL or DML: INSERT, UPDATE, ALTER, DROP.
8 Muneer has created a database “school” and table “student”. Now he wants to view all the
databases present in his laptop. Help him to write SQL command for that , also to view the
structure of the table he created
9 Ms. Minakshi has just created a table named “Staff” containing Columns Sname,
Department and Salary. After creating the table, she realized that she has forgotten to add a
primary key in the table. Help her in writing an SQL command to add a primary key - StaffId
of integer type to the table [Link], write the command to insert the following record
in the table: StaffId – 111,Sname- Shalu,Department: Marketing,Salary: 45000
10 Meera working as database developer in Syntel Pvt Ltd Company Agra. She is designing as
SQL table names A & B .If a MySQL table A has 5 columns and 6 rows and another table B has
3 columns and 4 rows, then what will be the degree and cardinality of the cartesian product
of A and B?
11 Sunil decides to delete phoneno column from a table student . Write the SQL command to
remove the column in the student table. Also mention the type of SQL command.
12 Write SQL command to remove the Primary Key constraint from a table, named M_ID is the
primary key of the table MOBILE.
13 Write SQL command to make the column M_ID the Primary Key of an already existing table,
named MOBILE.
14 What constraint should be applied on a table column so that duplicate values are not allowed
in that column, but NULL is allowed.
102 | P a g e
ANSWERS:
1 delete from BANK;
2 ALTER TABLE customer add price int;
3 SELECT * FROM EMPLOYEE WHERE commission is null;
4 Distinct
5 DESCRIBE or DESC
6 ORDER BY is used to sort the result set based on one or more columns, either in ascending
(ASC) or descending (DESC) order whereas group by is used to group rows that have the
same values in specified columns into summary rows, often used with aggregate functions.
Eg: SELECT name, salary FROM employees ORDER BY salary DESC;
This will list all employees and their salaries, sorted by salary from highest to lowest.
SELECT department, AVG(salary) AS average_salary FROM employees GROUP BY
department;
This will group employees by department and show the average salary for each department.
7 DDL –ALTER , DROP
DML-INSERT , UPDATE
8 SHOW DATABASES;
SHOW TABLES;
9 ALTER TABLE Staff ADD StaffId INT;
ALTER TABLE Staff ADD CONSTRAINT pk_staff PRIMARY KEY (StaffId);
INSERT INTO Staff (StaffId, Sname, Department, Salary) VALUES (111, 'Shalu', 'Marketing',
45000);
10 Degree = 8 Cardinality = 24
11 ALTER TABLE student DROP phoneno
It’s a DDL command.
12 ALTER TABLE mobile DROP PRIMARY KEY;
13 ALTER TABLE mobile ADD PRIMARY KEY (M_ID);
14 UNIQUE constraint makes sure that duplicate values are not allowed in that column, but NULL
will be allowed.
SHORT ANSWER QUESTIONS II
1 Meenu has been entrusted with the management of NSE Database. She needs to access some
information from STOCK and TRADERS tables for a survey analysis.
Help him extract the following information by writing the desired SQL queries as mentioned
below.
103 | P a g e
1005 LAPTOP 600 35000 HP T03
Write SQL queries for the following:
(i) Display the SNAME, QTY, PRICE, TCODE, and TNAME of all the stocks in the STOCK and
TRADERS tables.
(ii) Display the details of all the stocks with a price >= 35000 and <=50000 (inclusive).
(iii) Display the SCODE, SNAME, QTY*PRICE as the “TOTAL PRICE” of BRAND “NEC” or
“HP” in ascending order of QTY*PRICE.
iv) Display the number of stock items in each TCODE.
OR
To display the Cartesian Product of these two tables
2 Consider the following tables employees, empsalary.
Table : Employees
Empid Firstname Lastname Address City
010 Ravi Kumar Raj nagar GZB
105 Harry Waltor Gandhi nagar GZB
152 Sam Tones 33 Elm St. Paris
215 Sarah Ackerman 440 U.S. 110 Upton
244 Manila Sengupta 24 Friends street New Delhi
300 Robert Samuel 9 Fifth Cross Washington
335 Ritu Tondon Shastri Nagar GZB
400 Rachel Lee 121 Harrison St. New York
441 Peter Thompson 11 Red Road Paris
Table: EmpSalary
Empid Salary Benefits Designation
010 75000 15000 Manager
105 65000 15000 Manager
152 80000 25000 Director
215 75000 12500 Manager
244 50000 12000 Clerk
300 45000 10000 Clerk
335 40000 10000 Clerk
400 32000 7500 Salesman
441 28000 7500 salesman
Write the SQL commands for the following:
a) To show first name, last name, address and city of all employees who lives in Paris.
b) To display the details of Employees table in descending order of First name.
c) To display the first name, last name and salary of all employees from the tables
Employee and EmpSalary, who are working as Manager.
Give the Output of following SQL commands:
d) Select designation, sum(salary) from empsalary group by
designation having count(*) > 2;
OR
d) Select sum(benefits) from empsalary where designation =’clerk’;
3 Consider the table PRODUCT and CLIENT given below:
PR_ID PR_NAME MANUFACTURER PRICE QTY
BS101 BATH SOAP PEARSE 45.00 25
104 | P a g e
SP210 SHAMPOO SUN SILK 320.00 10
SP235 SHAMPOO DOVE 455.00 15
BS120 BATH SOAP SANTOOR 36.00 10
TB310 TOOTH BRUSH COLGATE 48.00 15
FW422 FACE WASH DETOL 66.00 10
BS145 BATH SOAP DOVE 38.00 20
C_ID C_NAME CITY PR_ID
01 DREAM MART COCHIN BS101
02 SHOPRIX DELHI TB310
03 BIG BAZAR DELHI SP235
04 LIVE LIFE CHENNAI FW422
Write SQL Queries for the following:
i) Display the details of those clients whose city is DELHI
ii) Increase the Price of all Bath soap by 10
iii) Display the details of Products having the highest price
iv) Display the product name, price, client name and city with their corresponding
matching product Id.
4 Write SQL Commands for (a) to (e) and write the outputs for (f) on the basis of table:
FURNITURE
NO ITEM NAME TYPE DATEOFSTOCK PRICE DISCOUNT
1 White Lotus Double Bed 2002-02-23 3000 25
2 Pink feathers Baby Cot 2002-01-29 7000 20
3 Dolphin Baby Cot 2002-02-19 9500 20
4 Decent Office Table 2002-02-01 25000 30
5 Comfort zone Double Bed 2002-02-12 25000 30
6 Donald Baby cot 2002-02-24 6500 15
7 Royal Finish Office Table 2002-02-20 18000 30
8 Royal tiger Sofa 2002-02-22 31000 30
9 Econo sitting Sofa 2001-12-13 9500 25
10 Eating Paradise Dinning Table 2002-12-19 11500 25
1. To show all the information about the Baby cots from the furniture table.
2. To list the itemname which are priced at more than 15000 from the furniture table.
3. To list itemname and type of those items, in which dateofstock is after 2002-02-01 from
the furniture table in descending order of itemname
4. To display itemname and dateofstock of those items, in which the discount percentage
is more than 25 from the furniture table.
ANSWERS:
1 i)select sname, qty, price , [Link], tname
from stock, traders where [Link] = [Link];
ii) select * from stock where price between 35000 and 50000;
iii) select scode, sname, qty * price as "total price" from stock
where brand in ('nec', 'hp') order by qty * price asc;
iv) select tcode, count(*) as stock_count from stock group by tcode;
2 i) select firstname, lastname, address, city from employees where city = 'paris';
105 | P a g e
ii) select * from employees order by firstname desc;
iii) select e. firstname, e. lastname, s. salary from employees e
join empsalary s on [Link] = [Link] where [Link] = 'manager';
iv) manager 215000
clerk 135000
or
32000
3 A) D_NAME
GUPTA
HANEEF
B) D_DEPT
ENT
MEDICINE
ORTHO
CARDIOLOGY
SKIN
C) D_NAME EXPERIENCE
DEEPTI 6
SUMAN 7
JOSEPH 10
GUPTA 12
HANEEF 12
VEENA 12
4 i) select * from client where city = 'delhi';
ii) update product set price = price + 10 where pr_name = 'bath soap';
iii) select * from product where price = (select max(price) from product);
iv) select p.pr_name, [Link], c.c_name, [Link] from product p join client c on p.pr_id = c.pr_id;
5 i) select * from furniture where lower(type) = 'baby cot';
ii) select item_name from furniture where price > 15000;
iii) select item_name, type from furniture where dateofstock > '2002-02-01'
order by item_name desc;
iv) select item_name, dateofstock from furniture where discount > 25;
107 | P a g e
cur = [Link]( )
Here ‘cur’ is the cursor object created on ‘con’ connection object. What the Cursor Object Does:
a) Execute SQL Commands.
b) Fetch Result from Database.
6. Executing Queries using execute( ) function with cursor object.
• The execute( ) function accepts the QUERY in the form of a STRING.
• The RESULT of the query is received in the cursor object.
import [Link] as m
con= [Link](host='localhost', user='root', passwd='1234', database='class')
cur = [Link]( )
query = "SELECT * FROM users"
[Link](query)
7. Fetching the Result
• Fetching/Extracting the Data/Result stored inside CURSOR object after Executing the
QUERY.
• For this we have 3 functions which are applied on the CURSOR object ‘cur’.
a) fetchall( ): It will return list of all the records retrieved in tuple form.
b) fetchone( ): It will return one record from the result set.
c) fetchmany(n): It will return number of records as per value of n and by default only
one records in tuple form.
The SYNTAX for extracting data –
import [Link] as m
con= [Link](host='localhost', user='root', passwd='1234', database='class')
cur = [Link]( )
query = "SELECT * FROM users"
[Link](query)
data = [Link]( )
or
data = [Link]( )
or
data = [Link](n)
for row in data:
print(row) # Displaying Each Record of the TABLE.
As ROWS of the table are received inside a TUPLE, we can display each ROW by iterating over
data/result extracted from the cursor in python.
8. ROWCOUNT
• It is the property of the cursor object that returns the number of rows fetched from the
cursor object till that moment and not the number of records the executed query will give.
SYNTAX –
count = [Link]
import [Link] as m
con =[Link](host="localhost",user="root", passwd="system", database="student")
cur=[Link]( ) # ASSUME TABLE HAS 10 ROWS
108 | P a g e
[Link]("select * from student") # All 10 ROWS are now in CURSOR object
data = [Link]( ) # Only 1 ROW is fetched from CURSOR till now
print([Link]) # Output = 1
data = [Link](4) # Total 5 ROWS have been fetched from CURSOR
print([Link]) # Output = 5
data = [Link]( ) # Total 6 ROWS have been fetched from CURSOR
print([Link]) # Output = 6
data = [Link]( ) # Remaining 4 ROWS have been fetched as well
print([Link]) # Output = 10
9. commit( )
After executing insert or update query we must commit our transaction using commit method of
connection object.
Eg: [Link]( )
10. [Link]( )
Closing the connection, Since the database can keep limited number of connections at a time, we
must close the connection using connection_object.close( ).
Eg: [Link]( )
STATIC QUERIES
Queries which are formed without passing any python object/variable/data.
Now we can execute any MySQL query through Python. Below are few examples static queries.
a) TO CREATE A TABLE IN MYSQL USING PYTHON INTERFACE
import [Link] as m
con =[Link](host="localhost",user="root", passwd="system", database="student")
cur=[Link]( )
[Link]("CREATE TABLE FEES (ROLLNO INT, NAME VARCHAR(20), AMOUNT INT);")
b) TO SHOW THE TABLES IN MYSQL USING PYTHON INTERFACE
import [Link] as m
con =[Link](host="localhost",user="root", passwd="system", database="student")
cur=[Link]( )
[Link]("SHOW TABLES")
for data in cur:
print(data)
c) TO DESCRIBE TABLE STRUCTURE USING PYTHON INTERFACE
import [Link] as m
con =[Link](host="localhost",user="root", passwd="system", database="student")
cur=[Link]( )
[Link]("DESC STUDENT")
for data in cur:
print(data)
d) TO EXECUTE SELECT QUERY USING A PYTHON INTERFACE
import [Link] as m
con =[Link](host="localhost",user="root", passwd="system", database="student")
cur=[Link]( )
[Link]("select * from student")
109 | P a g e
r=[Link]( )
while r is not None:
print(r)
r=[Link]( )
e) TO EXECUTE SELECT QUERY WITH WHERE CLAUSE USING A PYTHON INTERFACE
import [Link] as m
con =[Link](host="localhost",user="root", passwd="system", database="student")
cur=[Link]( )
[Link]("select * from student where marks>90")
r=[Link]( )
count=[Link]
print("total no of rows:",count)
for row in r:
print(row)
f) TO UPDATE A DATA IN A TABLE USING PYTHON INTERFACE
import [Link] as m
con =[Link](host="localhost",user="root", passwd="system", database="student")
cur=[Link]( )
[Link]("UPDATE STUDENT SET MARKS=100 WHERE MARKS=40")
[Link]( )
print([Link],"RECORD UPDATED")
g) TO DELETE A RECORD FROM THE TABLE USING PYTHON INTERFACE
import [Link] as m
con =[Link](host="localhost",user="root", passwd="system", database="student")
cur=[Link]( )
[Link]("DELETE FROM STUDENT WHERE MARKS<50")
[Link]( )
print([Link],"RECORD DELETED")
h) TO DROP AN ENTIRE TABLE FROM MYSQL DATABASE USING PYTHON INTERFACE
import [Link] as m
con =[Link](host="localhost",user="root", passwd="system", database="student")
cur=[Link]( )
[Link]("DROP TABLE STUDENT")
i) TO ADD A COLUMN IN THE EXISTING TABLE USING PYTHON INTERFACE
import [Link] as m
con =[Link](host="localhost",user="root", passwd="system", database="student")
cur=[Link]( )
[Link]("ALTER TABLE STUDENT ADD AGE NT”)
[Link]( )
j) TO DROP A COLUMN FROM THE TABLE USING PYTHON INTERFACE
import [Link] as m
con =[Link](host="localhost",user="root", passwd="system", database="student")
cur=[Link]( )
[Link]("ALTER TABLE DROP AGE ”)
[Link]( )
k) TO ALTER THE DATATYPE OF A COLUMN IN A TABLE USING PYTHON INTERFACE
import [Link] as m
110 | P a g e
con =[Link](host="localhost",user="root", passwd="system", database="student")
cur=[Link]( )
[Link]("ALTER TABLE STUDENT MODIFY GRADE CHAR(3)")
PARAMETERIZED QUERIES
Parameterize the query to add python variables/object into the string query to access values as
per the user’s input.
Example: to display record of a particular rollno.
There are two ways to use parameterized queries:
a) with { }.format pattern
b) with fstring & { } braces
1) Using {}.format pattern
(a)
rn = int(input(‘Enter Roll no. ‘)) # SUPPOSE USER ENTERS 10 AS ROLL NO
query = "select * from student where rollno = { }".format(rn)
[Link](query)
Note: “Here the format function will assign the value 10 in place of { } braces inside the
string query. python will convert it to-> query = "select * from student where rollno = 10"
(b)
Suppose we want to display the data based on the column name & value given by user
col_name = eval(input(‘Enter Column Name ‘)) # User entered Rollno
col_value = eval(input(‘Enter Column Value ‘)) # User entered 12
query = "select * from student where { } = { }".format(col_name , col_value)
# python will convert it to ->>> query = "select * from student where Rollno = 12 "
[Link](query)
(c)
Suppose we want to display the data from a specific class & section given by user
cls = eval(input(‘Enter Class ‘)) # User entered 12
sec = eval(input(‘Enter Section ‘)) # User entered A
query = "select * from student
where class = { } and section = ‘{ }’ ".format(cls , sec)
# python will convert it to ->>> query = "select * from student
where class = 12 and section = ‘A’ "
[Link](query)
Note: Here we add ‘f’ before the string & write the variable inside { } braces which
assigns the value 10 in place of {rn} inside the string query. python will convert it to->
query= "select * from student where rollno = 10"
111 | P a g e
(b)
Suppose we want to display the data based on the column name & value given by user
col_name = eval(input(‘Enter Column Name ‘)) # User entered Rollno
col_value = eval(input(‘Enter Column Value ‘)) # User entered 12
query = f”select * from student where { col_name } = { col_value } “
[Link](query)
Note: python will convert it to ->>> query = "select * from student where Rollno = 12 "
(c)
Suppose we want to display the data from a specific class & section given by user
cls = eval(input(‘Enter Class ‘)) # User entered 12
sec = eval(input(‘Enter Section ‘)) # User entered A
query = f ”select * from student where class = {cls} and section = ‘{sec}’ “
[Link](query)
Note: python will convert it to ->>> query = "select * from student where class = 12
and section = ‘A’ "
1 Assertion (A): The cursor( ) method is used to execute SQL queries in Python.
Reason (R): The cursor object allows interaction with the database.
2 Assertion (A): [Link]( ) is used to delete all records from a table.
Reason (R): fetchall( ) retrieves all records returned by a SELECT query.
3 Assertion (A): [Link]( ) requires parameters like host, user, password,
and database to connect successfully.
Reason (R): [Link]( ) is used to establish a connection between Python
and MySQL.
4 Assertion (A): commit( ) is used after every SELECT query to save the fetched results.
Reason (R): commit( ) saves changes made by INSERT, UPDATE, and DELETE operations.
5 Assertion (A): The close( ) method is mandatory after the database operations are
completed.
Reason (R): Keeping database connections open unnecessarily may lead to resource
leakage.
Answers
1 A 2 D 3 A 4 D 6 A
113 | P a g e
4 What is a database cursor?
5 How to retrieve data from a table?
Answers
1 To create database connectivity, follow the given steps:
Step 1: Start Python
Step 2: Import [Link]
Step 3: Open a connection to the database
Step 4: Create a cursor instance
Step 5: Execute a query
Step 6: Extract data from result set
Step 7. Clean up the environment
2 A connection (represented by the connection object) is the session between the application
program and database. To do anything with database, one must have a connection object.
3 A result set refers to a logical set of records that are fetched from the database by executing
a query and made available to the application program.
4 A database cursor is a special control structure that facilitates row by row processing of
records in the result set, i.e., the set of records retrieved as per the query.
5 There are multiple ways to retrieve data:
i. fetchall( ) – fetches all the remaining rows of a query result, current pointer position
forwards
ii. fetchone( ) – fetches the next row as a sequence; returns None when no more data
iii. fetchmany(n) :It will return number of records as per value of n and by-default only one
record.
LONG ANSWER QUESTIONS
1 Write a Python code to connect to a database
2 How to create a database in MySQL through Python ?
3 Write the Python code to display the present databases in MySQL
4 How to create a table in MySQL through Python ?
5 Write the Python code to insert data into student table of database kvs .
6 How to fetch data in Python from a student table of education database?
7 Write the Python code to update a record in the student table of education database.
8 Write the Python code to delete a record from the student table of education database
9 [Link] want to interface python with mysql and write some code help him to write the
code
import_____________.connector as m #Line1
mydb=m.________(host=”localhost”,user=”root”,
passwd=”tiger”,database=” choo ”) # Line2
cursor=mydb.___________( ) #Line3
cursor._______________(“select * from student”) #Line4
data=cursor.__________( ) #Line5 To retrieved all records
count=cursor.__________ #Line6
10 What is the difference between fetchone( ), fetchmany( ), fetchall( )?
Answers
1 import [Link] as m
Mycon=[Link](host=”localhost”,user=”root”, password=”tiger”,database=”project”)
print(mycon)
114 | P a g e
2 import [Link] as m
mycon= [Link](host=”localhost”,user=”root”,password=”tiger”)
cursor=[Link]( )
[Link](“create database education”)
[Link]( )
3 import [Link] as m
mycon= [Link](host=”localhost”,user=”root”,password=”tiger”)
cursor=[Link]( )
[Link](“show databases”)
for i in cursor:
print(i)
4 import [Link] as m
mycon= [Link](host=”localhost”,user=”root”, password=”tiger”)
cursor=[Link]( )
query = “create table student(admn_no int primary key, sname varchar(30), gender char(2),
DOB date, stream varchar(10), mark float”
[Link](query)
[Link]( )
5 import [Link] as m
mycon= [Link](host=”localhost”,user=”root”,password=”tiger”)
cursor=[Link]( )
no=int(input(“Enter admission no “))
n=input(“Enter name “)
g=input(“Enter gender ”)
dob=input(“Enter DOB “)
st=input(“Enter stream “)
m=float(input(“Enter m rk ”))
query= “insert into student values( {}, ‘{}’ , ‘{}’ , ’{}’ , ’{}’ , {} )”.format( no,n,g,dob, st,m)
[Link](query)
[Link]( )
6 import [Link] as m
mycon= [Link](host=”localhost”,user=”root”,password=”tiger”,
database = ‘education’)
cursor=[Link]( )
[Link](“select * from student”)
for row in cursor:
print(row)
7 import [Link] as m
mycon= [Link](host=”localhost”,user=”root”,password=”tiger”, database = ‘education’)
cursor=[Link]( )
[Link](“update student set marks =67 where admn_no=306”)
[Link]( )
8 import [Link] as m
mycon= [Link](host=”localhost”,user=”root”,password=”tiger”, database = ‘education’)
cursor=[Link]( )
[Link](“delete from student where admn_no=308 ”)
[Link]( )
115 | P a g e
9 Line1:-mysql, Line2:-connect, Line3:cursor, Line4: execute, Line5: fetchall, Line6: rowcount
10 fetchone( )
• Returns: A single row from the result set as a tuple (or None if no more rows).
fetchmany(size)
• Returns: A list of up to size rows, each as a tuple.
fetchall( )
• Returns: A list of all remaining rows as tuples in the result set.
Answers:
1 import [Link] as m
mycon= [Link](host=”localhost”,user=”root”,password=”Pencil”)
mycursor=[Link]( )
def Add(mycursor):
[Link](‘use ITEMDB’)
n = int(input(‘Enter no. of Items to be entered: ’))
for i in range(n):
ino = int(input(‘Enter Item no: ’))
inm = input(‘Enter Item name: ’)
ipr = float(input(‘Enter Item price: ’))
iq = int(input(‘Enter Item quantity: ’))
query = f ”insert into STATIONARY values({ino},’{inm}’,{ipr},{iq})”
[Link](query)
[Link]( )
def Display(mycursor):
[Link](‘use ITEMDB’)
query = ‘Select * from STATIONARY where price > 120’
[Link](query)
data = [Link]( )
for record in data:
print(‘Item No = ‘ , record[0])
print(‘Item Name = ‘ , record[1])
print(‘Item Price = ‘ , record[2])
print(‘Item Qty = ‘ , record[3])
Add(mycursor)
Display(mycursor)
[Link]( )
2 def Display(mycursor):
query = ‘Select * from CLASS where Fee > 5000’
[Link](query)
data = [Link]( )
for record in data:
print(‘Roll No = ‘ , record[0])
print(‘Name = ‘ , record[1])
print(‘DOB = ‘ , record[2])
print(‘Fee = ‘ , record[3])
import [Link] as m
mycon=[Link](host=”localhost”,user=”root”,password=”tiger”, database=’SC’)
mycursor=[Link]( )
Display(mycursor)
117 | P a g e
[Link]( )
3 def Add(mycursor):
n = int(input(‘Enter no. of Student Records to be entered: ’))
for i in range(n):
rn = int(input(‘Enter Student Roll No: ’))
nm = input(‘Enter Student name: ’)
dob = input(‘Enter Student DOB as ‘YYYY-MM-DD’ : ’))
fee = float(input(‘Enter Student Fee: ’))
query = f ”insert into CLASS values({rn},’{nm}’,’{dob}’,{fee})”
[Link](query)
[Link]( )
import [Link] as m
mycon=[Link](host=”localhost”,user=”root”,password=”tiger”, database=’SC’)
mycursor=[Link]( )
Add(mycursor)
[Link]( )
4 def Add(mycursor):
[Link](‘use COMPANY’)
n = int(input(‘Enter no. of Records to be entered: ’))
for i in range(n):
en = int(input(‘Enter Student Roll No: ’))
enm = input(‘Enter Student name: ’)
dob = input(‘Enter Student DOB as ‘YYYY-MM-DD’ : ’))
sal = float(input(‘Enter Student Fee: ’))
query = f ”insert into EMP values({en},’{enm}’,’{dob}’,{sal})”
[Link](query)
[Link]( )
import [Link] as m
mycon=[Link](host=”localhost”,user=”root”,password=”password”)
mycursor=[Link]( )
Add(mycursor)
[Link]( )
118 | P a g e
Data Base Management(Questions and PYQ)
Q Which Command is use to add/Delete column or Q Which clause is used in SQL to filter the groups based
attribute in/from a table? condition.
Ans: Alter Command
[Link] command is use to delete a table from the Ans:Having
Database. Q which SQL filter used after records after the group by
Ans: Drop operation.
[Link] command is used to add new record or row in a
table? a) Order by b) Where c) Having d) Join
[Link] Q To find the total number of rows in a table including
[Link] command is use to select/display/ duplicates which aggregate function would you use
show/retrieve /fetch data from the table.
Ans. Select a) Sum() b) count() c) max() d) count(*)
[Link] of the following aggregate functions can be
[Link] command is used to change the existing
used in conjunction with the HAVING clause to filter
information or data of table?
groups based on their average value?
OR
Which command is use to modify the rows in the table? (A) COUNT() (B) SUM() (C) AVG() (D) MIN()
Ans: Update
[Link] command is use to delete the record or row [Link] aggregate function can be used to find the
from the table? cardinality of a table?
Ans: Delete (A) sum() (B) count() (C) avg() (D) max()
[Link] Clause use in Command to search for NULL
values in any column? Q Which SQL data type is used to store decimal number
Ans: IS NULL with exact precision.
[Link]……. Clause of select query allow us to select any
a) Float b) Double c) decimal d) varchar
these rows in the result satisfied condition.
Ans: Where Q Which SQL command is used to remove the table form
[Link] operator is used for pattern matching? database.
Ans:Like
[Link] clause is used to see the output of query in Ans:Drop
ascending and descending order. [Link] Datatype is most suitable for storing a persons
OR phone number.
The Clause which display the record from the table in
sorted form. a)varchar(n) b) char(n) c) text d) int
Ans: Order by
Q Which Datatype is most suitable for storing a persons
Q. which clause is used to group the column with
aggregate function. email address.
Ans. Group by a)varchar(n) b) char(n) c) text d) int
[Link] to remove the row from table student
Ans: Delete from student; Q which SQL data type is best suited for storing variable
[Link] does SQL stands for? length character string up to specified maximum.
Ans: Structured Query Language
a)varchar(n) b) char(n) c) text d) int
[Link] command is used to create a new database?
Ans. Create database database_name; Q Sagar wants to find records with NULL values in one of
[Link] will be the output of the following command the columns. Which clause does he have to use?
Select count(*) from employee;
a)The total number of employee in the table. Ans:NOT NULL
b)The number of employee with null value in id column. Q. Which SQL command is used to define a new table in
a database?
c) The number of employee with not null value in id
column. (A) INSERT INTO (B) UPDATE (C) ALTER TABLE (D) CREATE
TABLE
b) The average number of employee per department.
Ans. b)
Data Base Management(Questions and PYQ)
[Link] is the output of the following SQL statement ? Q Which command is used to view all tables of
database?
Select Ang(salary) from employee where
department=’sales’; Ans: Show tables;
a)The average salary of all employee in the table. [Link] the table EMPLOYEES and DEPRTMENT and
answer the question .
b)The average salary of employee in the sales
department. Table:EMPLOYEES
c) The highest salary of all employee in the sales ENO ENAME DOJ DNO
department. E1 Nusrat 2001-11-21 D3
E2 Kabir 2005-10-25 D1
b) The lowest salary of all employee in sales department.
Ans. b)
Table:Department
[Link] is output of the following SQL statement ?
ENO DNAME
Select *from employee where salary between 40000 D1 ACCOUNTS
and 50000; D2 HR
D3 ADMIN
a)All employees whose salary is equal or greater than
40000 and equal or less than 50000.
1. What is the Degree of the table EMPLOYEES?
b)All employee whose salary is equal to 40000 or 50000.
What is the Cardinality of table DEPARTMENT?
c) All employee whose salary is exactly 40000 or 50000.
Ans: Degree of table Emplyees=4
b) All employee whose salary is exactly 40000 0r greater
Cardinality Of table Department=3
than 50000.
[Link] is primary key ? explain
Ans. a)
Ans: A primary key is a attribute which uniquely identify a
Q what is the full from of DDL and DML?
row or record which is never NULL or duplicate.
Ans:DDL(Data Definition Language)
[Link] is selection and projection?
DML(Data Manipulation Language)
Ans. Selection: Operation upon a relation to select a
[Link] is the output of the following command? horizontal subset of relation.
Select department, count(*) from employees group by Projection: Operation upon a relation to select a vertical
department having count(*)>5; subset of relation.
a)The number of employees in each department with QWrite the output of the following commands on table
more than 5 employees. CUSTOMERS and PURCHASES.
b) The department with more than 5 employee and their Table:CUSTOMERS
total number of employees.
CNO CNAME CITIES
c) The departments with less than 5 employees and their C1 Sanyam Delhi
total number of employee. C2 Shruti Delhi
C3 Mehar Mumbai
b) The number of departments with more than 5
C4 Sakshi Chennai
employee.
C5 Ritish Indore
Ans: b) C6 Rahul Delhi
C7 Ameer Chennai
Q Which SQL aggregate function is used to count all
C8 Minakshi Bangalore
record of a table.
C9 Anshul Mumbai
Ans: Count(*)
Data Base Management(Questions and PYQ)
Table: Purchases OR
Sno Qty Pur_Date Cno SELECT COUNT(CNAME),CITIES FROM CUSTOMERS
S1 15 2018-12-25 C2 GROUP BY CITIES;
S2 10 2018-11-10 C1
iv) SELECT * FROM PURCHASE WHERE QTY>15;
S3 12 2018-11-10 C4
S4 7 2019-01-12 C7 Q.
S5 11 2019-02-12 C2
Table:Teachers
S6 10 2018-10-12 C6
TID NAME AGE DEPT DOJ SAL GENDER
S7 5 2019-05-09 C8 T118 Navin 40 Computer 2010- 12000 M
S8 20 2019-05-09 C3 01-10
T107 Chetna 37 History 2008- 20000 F
S9 8 2018-05-09 C9
03-24
S10 15 2018-11-12 C5 T105 Sandeep 46 Maths 2006- 30000 M
S11 6 2018-08-04 C7 12-12
T110 Sangeeta 35 History 2010- 25000 F
(i) Select count(distinct cities ) from customers; 07-01
(ii) Select max(Pur_Date) from Purchases; T101 Rudransh 42 Maths 2004- 40000 M
(iii) Select CNAME,Qty ,Pur_Date from 09-05
T121 Neeraj 38 Physics 2011- 28000 M
Customers,Purchases where 04-01
[Link]=[Link] and Qty [Link] show the information about the teachers of the
in(10,20); history department.
Ans (i) 5 [Link] list the names of teacher earing a salary between
Explanation: Total entry in cities column is 9 but distinct 20000 and 30000
value of cities is 5.
[Link] count the number of male teacher.
(ii) 2019-05-09
[Link] gender wise total number of teachers.
Explanation: max function will first search for maximum
year value that is 2019 in table then it will search for [Link] list the name , age of teachers of female teacher in
max month then max day. descending order of date of joining.
CNAME Qty Pur_Date [Link] delete the record the teacher Neeraj.
Sanyam 10 2018-11-10
Ans.
Rahul 10 2018-10-12
[Link] * FROM TEAHERS WHERE
Mehar 20 2019-05-09
DEPT=’HISTORY’;
[Link] NAME FROM TEACHERS WHERE SAL
Q. Write SQL queries which are based on the table BETWEEN 20000 AND 30000;
Customers and Purchases given in question no. 26 [Link] COUNT(GENDER) FROM TEACHERS
WHERE GENDER=’M’;
i) To display details of all customers whose cities [Link] GENDER,COUNT(GENDER) FROM
are neither Delhi nor Mumbai TEACHERS GROUP BY GENDER;
ii) To display the CNAME and Cities of all [Link] NAME,AGE FROM TEACHERS
Customers is ascending order of their CNAME. WHERE GENDER=’F’ OREDR BY DOJ DESC;
iii) To display the numbers of Customers along with [Link] TEACHERS SET
their respective cities in each of the cities . SETL=SAL+(SAL*10)/100 WHERE
iv) To display details of all Purchases whose DEPT=’MATHS’;
Quantity is more than 15. 7. DELETE FROM TEACHERS WHERE
Ans: NAME=’NEERAJ’;
[Link] NAME FROM HOSPITAL WHERE GEN=”F” AND 5. SELECT TID ,TNAME FROM TAINER WHERE CITY NOT
DEPT IN(‘CAERDIOLOGY’,’SURGERY’); IN(‘DELHI’,’MUMBAI’);
[Link] COUNT(*) FROM HOSPITAL WHERE AGE>30; [Link] will be the output of the following statement
based on the table which are given in Q30.
Data Base Management(Questions and PYQ)
Q61.
Consider the Table Loan Given Below Q62. Consider the following table named GYM with th
following details.
Accno Name Loan EMI Int Intrest
amt rate Prcode Prname Unit price Manufacturer
1001 R.K 300000 36 12 1200 P101 Cross 25000 Avon Fitness
GUPTA trainer
1002 S.P 500000 48 10 1800 P102 Tread Mill 32000 A G Fitile
SHARMA P103 Massage 20000 Fit Express
1003 K.P JAIN 300000 36 NULL 1600 Chair
1004 M.P 800000 60 10 2250 P104 Vibration 22000 Avon Fitness
YADAV Trainer
1005 S.P 200000 36 12.5 4500 P105 Bike 13000 Fit Express
SINLIA a) Display the name of all products in the store.
1006 P. 700000 60 12.5 3500 b) Display the name of all products with unit price
SHARMA less than 20000.
1007 K.S 800000 48 NULL 3800 c) Display the details of all products with unit price
DHALL range 20000 and 30000.
d) Display the name of all products by the
manufacturer “Avon Fitness “ in descending
a) Write a Query to get the output. order of unit price.
Name e) Remove all the product row manufactured by
S.P SINGH “Avon Fitness”
K.S DHALL f) Change the unit price of all the rows by applying
M.P YADAV a 10% increased on all the products.
[Link] g) Display the details of all product with
manufacturer name starting with string ‘A’.
b) What will be the output of the following h) Change the unit price of all the rows by applying
command. a 10% increased on all the products which are
Select name,EMI from loans where manufacture by Fit express.
loanamt>500000 and intrate is NULL;
c) John has given the following command to Ans:
display the count of all the loan holders whose a) Select Prname from gym;
name ends with “Sharma” b) Select prname from gym where unitprice
Select count() from Loans where name like <20000;
‘Sharma%’; c) Select * from gym where unitprice between
d) State the command to display the maximum 20000 and 30000;
Loan amount and Customer name. d) Select prname from gym where
e) Help Ramesh to display the count of loan manufacturer=’avon fitness’ order by unit
holders whose interest is Null. price desc;
e) Delete from gym where manufacturer
Ans:
=’avon fitness’;
a) SELECT NAME FROM LOAN WHERE f) Update gym set
LOANAMT>500000; unitprice=unitprice+(unitprice*10)/100;
b) g) Select* from Gym where manufacturer
like’a%’;
Data Base Management(Questions and PYQ)
h) Update gym set (D) Names of all customers whose age is not between 25
unitprice=unitprice+(unitprice*10)/100 and 35
where manufacturer=”fit Express’;
A)1 (B) 2 (C) 4 (D) 3 B) The Maximum Salary for each department
In a table with attributes A, B and C, where A is a Primary C) The name of the employee with the highest
Key and B and C are non-key attributes, which of the salary
following statements is true about the Candidate Keys of D) The maximum salary of all employees combined
this table?
Q What will be the output of the query?
(A) The table has no Candidate Keys.
SELECT * FROM products WHERE product_name LIKE
(B) B and Care Candidate Keys. 'App%’;
(C) A is the only Candidate Key. (A) Details of all products whose names start with
(D) Both A and B can be Candidate Keys. 'App’
[Link] SQL command can change the degree of a (B) Details of all products whose names end with
table? Ans:alter 'App’
Q5.1 A table product has 5 columns and 10 rows. Another (C) Names of all products whose names start with
table transaction has 6 columns and 18 rows. What will 'App’
be the degree and cardinality of product × transaction? (D) Names of all products whose names end with
Ans Degree =5+6=11 cardinality= 10x18=180 'App'
10. What will be the output of the following query? Q. What will be the output of the following SQL query.
SELECT name FROM customers WHERE age BETWEEN 25 SELECT distinct department from employee where
AND 35; salary>50000;
(A) Names of all customers whose age is exactly 25 or 35 A) All distinct departments with a salary greater than
50000
(B) Names of all customers whose age is between 25 and
35, inclusive B) All departments with a salary than 50000 including
duplicate
(C) Names of all customers whose age is less than 25 or
greater than 35
Data Base Management(Questions and PYQ)
Question 1:
Write queries for (i) to (iv) and find ouputs for SQL queries (v) to (viii), which are based
on the tables.
Table :
VEHICLE
Note:
Answer:
Question 2:
Consider the following tables SCHOOL and ADMIN and answer this question :
Give the output the following SQL queries :
1. Select Designation Count (*) From Admin Group By Designation Having Count (*)
<2;
2. SELECT max (EXPERIENCE) FROM SCHOOL;
3. SELECT TEACHER FROM SCHOOL WHERE EXPERIENCE >12 ORDER BY
TEACHER;
4. SELECT COUNT (*), GENDER FROM ADMIN GROUP BY GENDER;
Answer:
Question 3:
Write SQL qureries for (i) to (iv) and find outputs for SQL queries (v) to (viii), which are
based on the tables TRANSPORT and TRIE
Note:
• NO is Driver Number
• KM is Kilometer travelled
• NOP is number of travellers travelled in vehicle
• TDATE is Trip Date
1. To display NO, NAME, TDATE from the table TRIP in descending order of NO.
2. To display the NAME of the drivers from the table TRIP who are traveling by
transport vehicle with code 101 or 103.
3. To display the NO and NAME of those drivers from the table TRIP who travelled
between ‘2015-02-10’ and ‘2015-04-01’.
4. To display all the details from table TRIP in which the distance travelled is more
than 100 KM in ascending order of NOP
5. SELECT COUNT (*), TCODE From TRIP
GROUP BY TCODE HAVNING COUnT (*) > 1;
6. SELECT DISTINCT TCODE from TRIP;
7. SELECT [Link], NAME, TTYPE
FROM TRIP A, TRANSPORT B
WHERE A. TCODE = B. TCODE AND KM < 90;
8. SELECT NAME, KM *PERKM
FROM TRIP A, TRANSPORT B
WHERE A. TCODE = B. TCODE AND A. TCODE = 105′;
Answer:
Question 4:
Write SQL query to add a column total price with datatype numeric and size 10, 2 in a
table product.
Answer:
ALTER TABLE PRODUCT ADD TOTAL PRICE NUMBER (10,2).
Question 5:
Sonal needs to display name of teachers, who have “0” as the third character in their
name. She wrote the following query.
SELECT NAME FROM TEACHER WHERE NAME = “$$0?”;
But the query is’nt producing the result. Identify the problem.
Answer:
The wildcards are incorrect. The corrected query is SELECT NAME FROM TEACHER
WHERE NAME LIKE ‘_ _0%’.
Question 6:
Deepika wants to remove all rows from the table BANK. But he needs to maintain the
structure of the table. Which command is used to implement the same?
Answer:
DELETE FROM BANK.
Question 7:
While creating table ‘customer’, Rahul forgot to add column ‘price’. Which command is
used to add new column in the table. Write the command to implement the same.
Answer:
ALTER TABLE CUSTOMER ADD PRICE NUMBER (10, 2).
Question 8:
What is the use of wildcard
Answer:
The wildcard operators are used with the LIKE operator to search a value similar to a
specific pattern in a column. There are 2 wildcard operators.
% – represents 0,1 or many characters – – represents a single number or character
Question 9:
Differentiate between DELETE and DROP table commands ?
Answer:
DELETE command is used to remove infor¬mation from a particular row or rows. If
used without condition, it will delete all row information but not the structure of the table.
It is a DML command.
DROP table command is used to remove the entire structure of the table and
information. It is a DDL command
Question 1:
Write SQL commands for the queries (i) to (iv) and output for (v) & (viii) based on a
table COMPANY and CUSTOMER.
1. To display those company name which are having prize less than 30000.
2. To display the name of the companies in reverse alphabetical order.
3. To increase the prize by 1000 for those customer whose name starts with „S?
4. To add one more column totalprice with decimal] 10,2) to the table customer
5. SELECT COUNT(*) , CITY FROM COMPANY GROUP BY CITY;
6. SELECT MIN(PRICE), MAX(PRICE) FROM CUSTOMER WHERE QTY>10;
7. SELECT AVG(QTY) FROM CUSTOMER WHERE NAME LIKE “%r%;
8. SELECT PRODUCTNAME,CITY, PRICE
FROM COMPANY, CUSTOMER WHERE
COMPANY. CID=[Link] AND
PRODUCTNAME=”MOBILE”;
Answer:
5.
6. 50000,70000
7. 11
8.
Question 2:
Consider the following tables SCHOOL and ADMIN and answer this question :
Write SQL statements for the following:
Answer:
Answer:
Question 4:
Answer the questions (a) and (b) on the basis of the following tables SHOP and
ACCESSORIES.
(a) Write the SQL queries:
1. To display Name and Price of all the Accessories in ascending order of their Price.
2. To display Id and SName of all Shop located in Nehru Place.
3. To display Minimum and Maximum Price of each Name of Accessories.
4. To display Name, Price of all Accessories and their respective SName where they
are available.
Answer:
(a)
Question 5:
Write SQL queries for:
1. To display name, fee, gender, joinyear about the applicants, who have joined
before 2010.
2. To display names of applicants, who are playing fee more than 30000.
3. To display names of all applicants in ascending order of their joinyear.
4. To display the year and the total number of applicants joined in each YEAR from
the table APPLICANTS.
5. To display the C_ID (i.e., CourselD) and the number of applicants registered in the
course from the APPLICANTS and table.
6. To display the applicant’s name with their respective course’s name from the
tables APPLICANTS and COURSES.
7. Give the output of following SQL statements:
• SELECT Name, Joinyear FROM APPLICANTS
WHERE GENDER=’F’ and C_ID=’A02′;
• SELECT MIN (Joinyear) FROM
APPLICANTS
WHERE Gender=’m’;
• SELECT AVG (Fee) FROM APPLICANTS
WHERE C_ID=’A0T OR C_ID=’A05′;
• SELECT SUM- (Fee), C_ID FROM C_ ID
GROUP BY C_ID
HAVING COUNT(*)=2;
Answer:
1. SELECT NAME,FEE,GENDER,JOINYEAR
FROM APPLICANTS
WHERE J OINYE AR <2010
2. SELECT NAME FROM APPLICANTS WHERE FEE >30000
3. SELECT NAME FROM APPLICANTS ORDERBY JOINYEAR ASC
4. SELECT YEAR, COUNT]*) FROM
APPLICANTS GROUP BY YEAR;
5. SELECT C_ID, COUNT]*) FROM
APPLICANTS, COURSES GROUP BY ID
WHERE APPLICANTS.C_ID=COURSES. C_ID
6. SELECT NAME,COURSE FROM
APPLICANTS, COURSES
WHERE APPLICANTS. C_ID=COURSES. C_ID
• Avisha 2009
• 2009
• 67
• 55000 A01
Question 6:
Write SQL queries for (a) to (g) and write the output for the SQL queries mentioned
shown in (hi) to (h4) parts on the basis of table ITEMS and TRADERS :
1. To display the details of all the items in ascending order of item names (i.e.,
INAME).
2. To display item name and price of all those items, whose price is in the range of
10000 and 22000 (both values inclusive).
3. To display the number of items, which are traded by each trader. The expected
output of this query should be:
4. To display the price, item name and quantity (i.e., qty) of those items which have
quantity more than 150.
5. To display the names of those traders, who are either from DELHI or from
MUMBAI.
6. To display the names of the companies and the names of the items in descending
order of company names.
7. Obtain the outputs of the following SQL queries based on the data given in tables
ITEMS and TRADERS above.
• SELECT MAX (PRICE), MIN (PRICE) FROM ITEMS;
• SELECT PRICE*QTY
FROM ITEMS WHERE CODE-1004;
• SELECT DISTINCT TCODE FROM ITEMS;
• SELECT INAME, TNAME FROM ITEMS I, TRADERS T WHERE
[Link]=[Link] AND QTY< 100;
Answer:
Question 7:
Write SQL queries for (a) to (f) and write the outputs for the SQL queries mentioned
shown in (gl) to (g4) parts on the basis of tables PRODUCTS and SUPPLIERS
1. To display the details of all the products in ascending order of product names (i.e.,
PNAME).
2. To display product name and price of all those products, whose price is in the
range of 10000 and 15000 (both values inclusive).
3. To display the number of products, which are supplied by each suplier. i.e., the
expected output should be;
• S01 2
• S02 2
• S03 1
4. To display the price, product name and quantity (i.e., qty) of those products which
have quantity more thhn 100.
5. To display the names of those suppliers, who are either from DELHI or from
CHENNAI.
6. To display the name of the companies and the name of the products in
descending order of company names.
7. Obtain the outputs of the following SQL queries based on the data given in tables
PRODUCTS and SUPPLIERS above.
• SELECT DISTINCT SUPCODE FROM PRODUCTS;
• SELEC MAX (PRICE), MIN (PRICE) FROM PRODUCTS;
• SELECT PRICE*QTY
FROM PRODUCTS WHERE PID = 104; (g4)
• SELECT PNAME, SNAME
FROM PRODUCTS P, SUPPLIERS S WHERE E SUPCODE = S.
SUPCODE
AND QTY>100;
Answer:
Question 8:
Consider the following tables CARDEN and CUSTOMER and answer (b) and (c) parts
of this question:
1. Give a suitable example of a table with sample data and illustrate Primary and
Alternate Keys in it.
2. Write SQL commands for the following statements:
• To display the names of all the silver coloured cars.
• To display names of car, make and capacity of cars in descending order of
their sitting capacity.
• To display the highest charges at which a vehicle can be hired from
CARDEN.
• To display the customer name and the corresponding name of the cars hired
by them.
3. Give the output of the following SQL queries:
• SELECT COUNT(DISTINCT Make) FROM CARDEN;
• SELECT MAX(Charges), MIN (Charges) FROM CARDEN;
• SELECT COUNTS), Make FROM CARDEN;
Answer:
Question 9:
Consider the following tables CABHUB and CUSTOMER and answer (b) and (c) parts
of this question :
1. Give a suitable example of a table with sample data and illustrate Primary and
Candidate Keys in it.
2. Write SQL commands for the following statements:
• To display the names of all the white coloured vehicles.
• To display name of vehicle name and capacity of vehicles in ascending
order of their sitting capacity.
• To display the highest charges at which a vehicle can be hired from
CABHUB.
• To display the customer name and the corresponding name of the vehicle
hired by them.
3. Give the output of the following SQL queries :
• SELECT COUNT(DISTINCT Make) FROM CABHUB;
• SELECT MAX(Charges), MIN(Charges)
• FROM CABHUB;
• SELECT COUNT (*) Make FROM CABHUB;
• SELECT Vehicle FROM CABHUB WHERE Capacity=4;
Answer:
1. Primary key of CABHUB = Vcode alternate key of CABHUB = Vehicle
Name. Primary key of Customer = Ccode Alternate Key of CUSTOMER = Cname.
2. (i) SELECT VehicleName FROM CABHUB
WHERE Colour = “WHITE”;
3. SELECT VehicleName, capacity From CABHUB ORDER BY Capacity
ASC;
4. SELECT MAX(Charges) FROM CABHUB;
5. SELECT Cname,VehicleName FROM CABHUB, CUSTOMER WHERE
CUSTOMER. Vcode=CABHUB. Vcode;
6. (i) 4
(ii) MAX(Charges) MIN (Charges)
35 12
(iii) 5
(iv) SX4
C Class
Question 10:
Consider the following tables EMPLOYEE and DEPARTMENT and answer (a) and (b)
parts of this question.
Answer:
(a)
Answer:
(a)
(b)
Question 12:
Consider the following tables EMPLOYEE and SALGRADE and answer (b) and (c)
parts of this question:
(a) What do you understand by Selection and Projection operations in relational
algebra ?
(b) Write SQL commands for the following statements :
Answer:
(b)
Question 13:
Consider the following tables GAMES and PLAYER and answer (b) and (c) parts of this
question :
(a)What do you understand by primary key and candidate keys ?
(b)Write SQL commands for the following statements:
Answer:
(a) An attribute or set of attributes which are used to identify a tuple uniquely is known
as a primary key. If a table has more than one such attributes which identify a tuple
uniquely than all such attributes are known as candidate keys.
(b)
(c)
1. 2
2. 19-Mar-2004 12-Dec-2003
3. Ravi Sahai Lawn Tennis
4. 101 108 103
Question 14:
Consider the following tables ACTIVITY and COACH and answer (a) and (b) parts of
this question :
1. To display the names of all activities with their Acodes in descending order.
2. To display sum of PrizeMoney for the Activities played in each of the Stadium
separately.
3. To display the coach’s name and acodes in ascending order of Acode from the
table Coach.
4. To display the content of the Activity table whose schedule date earlier than 01-
01-2004 in ascending order of Participants Num.
Answer:
(a)
1. SELECT Acodes, ActivityName FROM ACTIVITY ORDER BY ACode DESC;
2. SELECT SUM(PrizeMoney) FROM ACTIVITY GROUP BY Stadium;
3. SELECT Name, Acode FROM COACH ORDER BY Acode;
4. SELECT * FROM ACTIVITY WHERE SchduleDate < ’01-Jan-2004′ ORDER BY
ParticipantsNum;
(b)
1. 3
2. 12-Dec-2003 19-Mar-2004
3. Ravinder Discuss Throw
4. 1001
1008
1003
Question 15:
Consider the following tables RESORT and OWNEDBY and answer (a) and (b) parts of
this question:
Answer:
(a)
(b)
Question 16:
Consider the following tables STORE and SUPPLIERS and answer (a) and (b) parts of
this question:
1. To display details of all the items in the STORE table in ascending order of
LastBuy.
2. To display ItemNo and Item name of those items from STORE table whose Rate
is more than 15 Rupees.
3. To display the details of those items whose supplier code (Scode) is 22 or
Quantity in Store (Qty) is more than 110 from the table Store.
4. To display minimum Rate of items for each supplier individually as per Scode from
the table STORE.
Answer:
(a)
1. SELECT * FROM STORE ORDER BY LastBuy ASC;
2. SELECT ItemNo, Item FROM STORE WHERE Rate > 15;
3. SELECT * FROM STORE WHERE (Scode = ’22’ OR Qty >’110′);
4. SELECT Sname, MIN(Rate) FROM STORE, SUPPLIERS WHERE STORE.
Scode = [Link] GROUP BY Sname;
(b)
1. 3
2. 880
3. Item Sname
Gel Pen Classic Premium Stationers
4. 24-Feb-10
Question 17:
Consider the following tables STOCK and DEALERS and answer (a) and (b) parts of
this question:
1. To display the details of all Items in the STOCK table in ascending order of
StockDate.
2. To display ItemNo and Item name of those items from STOCK table whose
UnitPrice is more than Rupees 10.
3. To display the details of those items whose dealer code (Dcode) is 102 or quantity
in STOCK (Qty) is more than 100 from the table Stock.
4. To display maximum UnitPrice of items for each dealer individually as per Dcode
from the table STOCK.
Answer:
(a)
(b)
1. 3
2. 4400
3. Item Dname
Eraser Big Clear Deals
4. 01-Jan-09
REVISION – COMPUTER SCIECE – XII STD.
[Link]. 27 (2 MARKS)
MySQL COMMANDS AND DIFFERENCES
Points to Remember:
Sample Questions:
(2)
Answer:
(3)
Answer:
(4)
Answer:
DROP DELETE
Removes entire table or database, including data Removes one or more specific rows
and definition. from a table.
Answer:
Points to Remember:
• Identify the Table name and Column names.
• SELECT Command:
It helps to display the records as per our requirement.
NOTE: For displaying records not in the specified range, we have to use not between operator.
Relational Operators
To compare two values, a relational operator is used. The result of the comparison is true or false.
Relational Operators recognized by SQL: =, >, <, <=, >=, <> (not equal or !=)
Eg. Select * from employee where ecode <> 1001;
Above query will not display those employee details whose ecode column value is 1001.
GROUP BY Clause
GROUP BY clause is used in SELECT statements to display the table contents based on similar values
in a column into groups.
Eg: To calculate the number of employees in each grade, the query is:
SELECT grade, count(*) from employee group by grade;
HAVING clause :
The HAVING clause in MySQL is used to filter the results of a GROUP BY query based
on aggregate functions. It is necessary because the WHERE clause cannot be used with
aggregate functions (e.g., SUM(), COUNT(), AVG(), MIN(), MAX()).
Examples:
To find departments that have more than a certain number of employees ( 5 employees)
SELECT Department, COUNT(EmployeeID) AS num_employees
FROM Employee
GROUP BY Department
HAVING COUNT(EmployeeID) > 5;
To find customers whose total order amount exceeds a specific value (100) :
SELECT customer_id, SUM(price * quantity) AS total_revenue
FROM sales
GROUP BY customer_id
HAVING SUM(price * quantity) > 100;
Answer:
(4)
(5)
Answer:
(6)
Answer:
(7)
Answer:
REVISION – COMPUTER SCIECE – XII STD.
[Link]. 34 (4 MARKS)
MySQL JOINS – Two Tables
Points to Remember:
• Identify the common column name in both the tables.
• Use the same column names in SQL queries
• Use Natural Join or Where [Link]=[Link] for joining two tables
Example:SELECT * FROM FEE NATURAL JOIN CLASS WHERE [Link] > 5000;
(OR) SELECT * FROM FEE, CLASS WHERE [Link] = [Link] AND
[Link] > 5000;
• Any aggregate functions like AVG, SUM needs, use GROUP BY clause.
If you need to apply any aggregate condition use HAVING clause.
(Note: Having clause cannot be used without Group By)
Example:
select [Link], name, count(bno) from students s, bills b
where [Link]=[Link]
group by [Link] having count(bno)>1;
Sample Question:
(1)
(2)
(3)
(4)
(5)
(6)
(7)
REVISION – COMPUTER SCIECE – XII STD.
[Link]. 35 (4 MARKS)
Python-MySQL connectivity
Points to Remember:
Steps for creating Database connectivity:
[Link] the package mysql connector
syntax: import [Link]
[Link] a connection to a Database
Syntax:
ConnectionObject= [Link](host=“hostname",user=“username",
password=“Passwaord",database=“Databasename")
3. Create a Cursor
Syntax: CursorObject=[Link]()
4. Execute a Query:
Synatax: [Link](“Sql query”)
[Link] data from result set:
Syntax: [Link]()
[Link]()
[Link](n)
[Link]
[Link] up the Environment:
Syntax: [Link]()
[Link] the database:
[Link]()
Parameterized Query:
Sometimes we need to run queries which are based on some parameters or values that are provided
from outside, such queries are called parameterised queries.
Performing Queries :
“Insert into tablename values({},{})”.format(value1,value2)
“Update tablename set columnname={} where columnname={}”.format(newvalue, oldvalue)
“Delete from tablename where condition={}”.format(value)
Insert and Update queries make change to the data base unlike SELECT you must commit your
query after executing INSERT and UPDATE command.
Synatx: [Link]()
Sample Question:
(1)
(2)
(3)