Database
Database
Database: is a collection of interrelated files containing collection of records, where each record of a file
is collection of logically related data items. Relational Database is a collection of related tables /
relations. The software required to handle or manipulate these tables or relations is known as Relational
Database Management System (RDBMS).
Table / Relation: A collection of rows and columns form a table. A relation among set of values (in each
column / attribute) is represented by a row of a table, hence the term relational database. The horizontal
subset of a Table (Relation) is known as a Row (Tuple). The vertical subset of a Table (Relation) is
known as a Column (Attribute).
A relation is a set, elements in set are not ordered, no ordering defined on rows of relation.
Domain is a set of values from which actual values of an attribute of a Table (Relation) (i.e. the column
of a relation obtains values from domain) are obtained.
An attribute having distinct values that can be used to identify a tuple (row) uniquely is called Key. A
relation may have more than one such keys. All the keys are known as Candidate Keys. Out of all the
possible Candidate keys, one is selected as Primary Key, and rest of the key(s) is(are) called Alternate
Key(s). Attributes or columns which are not Candidate Keys are known as Non-Key attributes.
Primary Key is an attribute (column) that contains distinct values which can be used to identify a tuple
(row) uniquely in a relation (table).
Non-Key Attribute is an attribute which not a Candidate Key (attribute not having distinct values).
Page 1 of 22
Database & SQL
Relation: Employee
ENO NAME DESIG DOJ SAL MOB
1045 ADITYA JAIN MANAGER 2010-07-02 80000 99456972
1072 ALEX JOHN MANAGER 2007-04-09 75000 55012016
1032 RITA GUPTA MANAGER 2010-07-02 80000 66442288
1012 NITU BHAT DIRECTOR 2008-10-15 95000 55123765
1049 ALOKA SINGH DIRECTOR 2007-04-09 90000 64192837
1025 RITA GUPTA DIRECTOR 2008-10-15 95000 55876534
1017 ADITYA JAIN MANAGER 2008-09-03 75000 98283761
Non-key Attributes
In the Employee relation, ENO and MOB are Key attributes. ENO is selected as Primary key, then
MOB is the Alternate key. Attributes NAME, DESIG, DOJ and SAL are non-key attributes. Generally,
in a table (relation), a column is a key but theatrically, a key can be a collections two or more columns. A
table may not have any key and hence no Primary key or Candidate key. A table with one Candidate key,
there will be one Primary key and no Alternate key. A table can have only one Primary key. A table may
have multiple Candidate keys, one will be the Primary key and the remaining Candidate key(s) will be the
Alternate key(s). To have an Alternate key(s) in the table, the table must have at least two Candidate keys.
Cartesian Product (Binary Operator): obtaining a new relation by pairing every row of one relation with
every row of the other relation. It operates on two or more relations and is denoted by X. Cartesian Product
of two relations R1 and R2 is represented by R1 X R2. The degree of the new relation is sum of degrees
of relation R1 and relation R2. The cardinality of the new relation is product of cardinality of relation R1
and cardinality of relation R2.
Example:
Relation: Student (R1) Relation: Teacher (R2)
ROLL SNAME CLASS TNAME SUBJECT
1 AKASH 12 MS. RITA GEOGRAPHY
5 DIPAK 11 MR. ANUP POLITICAL SC
31 STUTI 11
Page 2 of 22
Database & MySQL Class XII
Union (Binary Operator): Obtain a new relation by getting rows from both the relations. It operates on
two or more relations and is indicated by U. For example, R1 U R2 represents union operation between
two relations R1 and R2. The degree of the relation new relation (R1 U R2) is equal degree of relation R1
(or degree of relation R2). The cardinality of the new relation (R1 U R2) is sum of cardinality of relation
R1 and cardinality of relation R2. Two relations are compatible for union operation when:
a) Degree of relation R1 = Degree of relation R2
b) Corresponding attributes of the two relations (R1 and R2) must have a common domain
Example:
Relation: CS12A (R1) Relation: CS12B (R2) CS12A (R1) U CS12B (R2)
NAME MARKS GRADE NAME MARKS GRADE NAME MARKS GRADE
FATIMA 69.5 C1 ATUL 89.0 A2 FATIMA 69.5 C1
FARUQ 78.0 B2 EKTA 67.5 C2 FARUQ 78.0 B2
GAURI 95.5 A1 REKHA 88.5 B1 GAURI 95.5 A1
REKHA 89.0 A2
EKTA 67.5 C2
ATUL 88.5 B1
Example:
create table student(roll numeric(2), name char(25), fees numeric(8,2),
dob date);
Name of the table is student. The table student will have 4 columns (attributes). Column roll will
be integer type (maximum 2 digit), column name will be character type (maximum 25 characters), column
fees will be floating point type (8 significant digits, 6 places before decimal point and 2 places after the
decimal point), column dob will be date type.
Page 3 of 22
Database & MySQL Class XII
Inserting a new row in a table (DML)
Syntax:
i) Insert Into TableName Values (Value1, Value2, Value3, …);
ii) Insert Into TableName (Col1, Col2,…) Values (Value1, Value2,…);
Insert Into command adds (inserts) a new row (tuple) in a table (relation).
Syntax i) is used when values are available for all the columns of a row.
Syntax ii) is used when values are available for selected columns of a row and remaining columns in the
will have value NULL.
Examples:
i) Insert Into Student Values(21,'MANAS VERMA',7800,'1989-09-07');
Insert Into Student Values(7,'DHRUTI GUPTA',8800,'1988-02-28');
ii) Insert Into Student(Roll,Name,Fees) Values(16,'PRATAP RAO',7500);
Insert Into Student(Roll,Name,Fees) Values(2,'ANIL JAIN',8300);
Note: The column dob will have value NULL.
Examples:
Alter Table Student ADD Class Numeric(2);
Alter Table Student ADD Sec Char;
Note: The columns Class and Sec will have value NULL.
Example:
Update Student Set Class=12, Sec='A' Where Roll=16;
Update Student Set Fees=7800 Where Roll=16;
Update Student Set Dob='1989-04-18' Where Roll=31;
Update Student Set Sec='D' Where Sec='A';
Update Student Set Fees=1.1*Fees;
Examples:
Delete From Student Where Roll=13;
Delete From Student Where Name='SUSHIL JAIN';
Delete From Student Where Roll=12 Or Roll=17;
Page 4 of 22
Database & MySQL Class XII
Deleting a table (DDL)
Syntax:
Drop Table TableName;
Drop Table command deletes entire the contents of the table along with the structure of the table.
Examples:
Drop Table Student;
Drop Table Employee;
Examples:
Select * From Student;
Roll Name Fees Dob Class Sec
21 MANISH SINGH 7800 1989-09-07 12 B
17 DHRUTI GUPTA 8800 1988-02-28 12 C
24 SUNIT KUMAR 7500 1989-08-24 12 A
16 PUNEET ARORA 7500 1990-05-12 12 A
33 SUBHOJIT SAHA 6800 1989-01-31 12 C
13 ASIT BHARGAV 8500 1989-04-29 12 B
10 SUSHIL JAIN 6900 1988-03-13 12 A
14 ARPITA SHETTY 7200 1988-06-15 12 C
27 SUNILA DESAI 7000 1990-11-29 12 B
Page 6 of 22
Database & MySQL Class XII
33 SUBHOJIT SAHA 6800 1989-01-31 12 C
10 SUSHIL JAIN 6900 1988-03-13 12 A
14 ARPITA SHETTY 7200 1988-06-15 12 C
Select * From Student Where Fees Not Between 7000 And 9000;
Roll Name Fees Dob Class Sec
33 SUBHOJIT SAHA 6800 1989-01-31 12 C
10 SUSHIL JAIN 6900 1988-03-13 12 A
Examples:
Select * From Student Order By Roll;
Roll Name Fees Dob Class Sec
10 SUSHIL JAIN 6900 1988-03-13 12 A
13 ASIT BHARGAV 8500 1989-04-29 12 B
14 ARPITA SHETTY 7200 1988-06-15 12 C
16 PUNEET ARORA 7500 1990-05-12 12 A
17 DHRUTI GUPTA 8800 1988-02-28 12 C
21 MANISH SINGH 7800 1989-09-07 12 B
24 SUNIT KUMAR 7500 1989-08-24 12 A
27 SUNILA DESAI 7000 1990-11-29 12 B
33 SUBHOJIT SAHA 6800 1989-01-31 12 C
Select Name, Sec, Dob, From Student Where Sec='A' Or Sec='B' Order By
Sec, Name;
Name Sec Dob
PUNEET ARORA A 1990-05-12
SUNIT KUMAR A 1989-08-24
SUSHIL JAIN A 1988-03-13
ASIT BHARGAV B 1989-04-29
MANISH SINGH B 1989-09-07
SUNILA DESAI B 1990-11-29
Select Name, Sec, Dob, From Student Where Sec='A' Or Sec='B' Order By
Sec, Name Desc;
Name Sec Dob
SUSHIL JAIN A 1988-03-13
SUNIT KUMAR A 1989-08-24
Page 8 of 22
Database & MySQL Class XII
PUNEET ARORA A 1990-05-12
SUNILA DESAI B 1990-11-29
MANISH SINGH B 1989-09-07
ASIT BHARGAV B 1989-04-29
Select Name, Sec, Dob From Student Where Sec in ('A','B') Order By
Sec Desc, Name;
Name Sec Dob
ASIT BHARGAV B 1989-04-29
MANISH SINGH B 1989-09-07
SUNILA DESAI B 1990-11-29
PUNEET ARORA A 1990-05-12
SUNIT KUMAR A 1989-08-24
SUSHIL JAIN A 1988-03-13
SQL Union
Example of Union:
Table: Stu1 Table: Stu2
Adno Name Adno Name
20050014 FATIMA 20050017 REKHA
20050029 FARAZ 20050023 TUSHI
20050004 GAURI
Following rows are inserted into the item table. Last two rows are added with NULL value for the
column price.
insert into item values (1001,'INK PEN', 0.25);
insert into item values (1002,'GEL PEN', 0.35);
insert into item values (1003,'DOT PEN', 0.15);
insert into item values (1004,'RULER' , NULL);
insert into item values (1005,'ERASER' , NULL);
Write MySQL query to display the item details when price is NULL.
select * from item where price is NULL;
+------+---------+-------+
| code | prod | price |
+------+---------+-------+
| 1004 | RULER | NULL |
| 1005 | ERASER | NULL |
+------+---------+-------+
= (equal to) operator cannot be used with NULL (NULL does not support = operator).
Following query does not trigger any error but does not display any output. The query display
Empty Set.
select * from item where price=NULL;
Empty Set
Write MySQL query to display the item details when price is not NULL.
select * from item where price is not NULL;
Page 12 of 22
Database & MySQL Class XII
+------+---------+-------+
| code | prod | price |
+------+---------+-------+
| 1001 | INK PEN | 0.25 |
| 1002 | GEL PEN | 0.35 |
| 1003 | DOT PEN | 0.15 |
+------+---------+-------+
!= (not equal to) operator cannot be used with NULL (NULL does not support != operator).
Following query does not trigger any error but does not display any output. The query display
Empty Set.
select * from item where price!=NULL;
Empty Set
But to one would like to avoid NULL values in column(s). It can be done by adding NOT NULL
constraint to a column in a table. NOT NULL constraint is added in the following way:
create table item (code int not null, prod char(10), price float);
describe item;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| code | int | NO | | NULL | |
| prod | char(10) | YES | | NULL | |
| price | float | YES | | NULL | |
+-------+----------+------+-----+---------+-------+
By adding NOT NULL constraint for the column code, the column will not accept NULL value
either directly or indirectly. Following MySQL queries will trigger syntax error.
insert into item values (NULL, 'GEL PEN', 0.35);
insert into item (prod, price) values ('GEL PEN', 0.35);
describe item;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| code | int | YES | | NULL | |
| prod | char(10) | YES | | NULL | |
| price | float | YES | | NULL | |
+-------+----------+------+-----+---------+-------+
alter table item modify code int not null;
OR, alter table item modify column code int not null;
describe item;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| code | int | NO | | NULL | |
| prod | char(10) | YES | | NULL | |
| price | float | YES | | NULL | |
+-------+----------+------+-----+---------+-------+
Page 13 of 22
Database & MySQL Class XII
If column code contains NULL values, then the NOT NULL constraint cannot be added for the
column code.
describe item;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| code | int | YES | | NULL | |
| prod | char(10) | YES | | NULL | |
| price | float | YES | | NULL | |
+-------+----------+------+-----+---------+-------+
• Primary Key and Unique: As mentioned earlier, Primary key of table (relation) is a column
(attribute) that contains distinct values which can be used identify a row (tuple) uniquely. A table can
have only one Primary key. In MySQL, Primary key constrains will add a Primary key in a table. It
can be done in two ways:
➢ Adding Primary key and Unique constraints when while creating a table:
create table item (code int not null, prod char(10) not null, price
float, primary key(code), unique(prod));
OR, create table item (code int primary key, prod char(10) not
null unique, price float);
insert into item values (1001,'INK PEN', 0.25);
insert into item values (1002,'GEL PEN', 0.35);
insert into item values (1003,'DOT PEN', 0.15);
describe item;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| code | int | NO | PRI | NULL | |
| prod | char(10) | NO | UNI | NULL | |
| price | float | YES | | NULL | |
+-------+----------+------+-----+---------+-------+
In the item table, code is the Primary key and prod is the column containing distinct values,
hence it is a key. Since code is the Primary key, prod is the Alternate keys. Columns code and
prod are the Candidate keys. By adding Primary key constraint, NOT NULL constraint is added
by default. A Primary key does accept duplicate values or NULL values. By adding Unique
constraint, NOT NULL constraint is not added by default.
Page 14 of 22
Database & MySQL Class XII
NOT NULL constraint to be added along with Unique constraint, to ensure the column does not
accept NULL values.
describe item;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| code | int | YES | | NULL | |
| prod | char(10) | YES | | NULL | |
| price | float | YES | | NULL | |
+-------+----------+------+-----+---------+-------+
It is clear that the table item does not have any Primary key and any Unique constraint. Following
rows are added in the table item.
insert into item values (1001,'INK PEN', 0.25);
insert into item values (1002,'GEL PEN', 0.35);
insert into item values (1003,'DOT PEN', 0.15);
insert into item values (1004,'RULER' , 0.15);
insert into item values (1005,'ERASER' , 0.15);
Page 15 of 22
Database & MySQL Class XII
describe item;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| code | int | NO | PRI | NULL | |
| prod | char(10) | YES | UNI | NULL | |
| price | float | YES | | NULL | |
+-------+----------+------+-----+---------+-------+
describe item;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| code | int | NO | | NULL | |
| prod | char(10) | YES | | NULL | |
| price | float | YES | | NULL | |
+-------+----------+------+-----+---------+-------+
Primary key and Unique constraint are removed from the table item.
create table empdata (code int primary key, name char (10), mob
int unique);
insert into empdata values (199801, 'SUNIL', 93661430);
insert into empdata values (200305, 'REETA', 55789215);
insert into empdata values (202102, 'ANITHA', NULL);
describe empdata;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| code | int | NO | PRI | NULL | |
| name | char(10) | YES | | NULL | |
| mob | int | YES | UNI | NULL | |
+-------+----------+------+-----+---------+-------+
create table empdata (code int primary key, name char (10), mob
int);
insert into empdata values (199801, 'SUNIL', 93661430);
insert into empdata values (200305, 'REETA', 55789215);
insert into empdata values (202102, 'ANITHA', 98452301);
describe empdata;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| code | int | NO | PRI | NULL | |
| name | char(10) | YES | | NULL | |
| mob | int | YES | | NULL | |
+-------+----------+------+-----+---------+-------+
describe empsal;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| code | int | YES | MUL | NULL | |
| desig | char(20) | YES | | NULL | |
| bsal | float | YES | | NULL | |
+-------+----------+------+-----+---------+-------+
The column code in the empdata table is the Primary key while the code in the empsal table is
the Foreign key. To insert a row in the table empsal, the Foreign key code, must contain a value
from the Primary key code of the empdata table.
• Natural join
Two or more relations will be joined using a common column present in all the relations. The common
column must have same name and same data type in all the relations. Table produced through natural
join will have only one common col name. In Natural join, rows will be paired by matching the values
stored in the common column.
Page 18 of 22
Database & MySQL Class XII
select * from student natural join teacher;
+------+------+--------+------+-----------+
| cla | roll | sname | code | tname |
+------+------+--------+------+-----------+
| 12 | 14 | AKASH | 1201 | MS. SMITA |
| 12 | 15 | DEEPAK | 1201 | MS. SMITA |
| 11 | 16 | ROSHAN | 1102 | MR. VARUN |
| 11 | 17 | DEEPA | 1102 | MR. VARUN |
+------+------+--------+------+-----------+
• Equi-join
This is almost similar to Natural join but only difference is two or more tables can be joined using
column from the tables where the name of the columns in the table could be different. Also, the new
table contains repeated columns used to link the tables. Equi-join can be performed as:
select * from student, teacher where student.cla=teacher.cla;
OR, select * from student s, teacher t where s.cla=t.cla;
OR, select * from student as s, teacher as t where s.cla=t.cla;
OR, select * from student join teacher on student.cla=teacher.cla;
OR, select * from student s join teacher t on s.col=t.col;
OR, select * from student as s join teacher as t on s.col=t.col;
+------+--------+------+------+-----------+------+
| roll | sname | cla | code | tname | cla |
+------+--------+------+------+-----------+------+
| 14 | AKASH | 12 | 1201 | MS. SMITA | 12 |
| 15 | DEEPAK | 12 | 1201 | MS. SMITA | 12 |
| 16 | ROSHAN | 11 | 1102 | MR. VARUN | 11 |
| 17 | DEEPA | 11 | 1102 | MR. VARUN | 11 |
+------+--------+------+------+-----------+------+
Python's mysql.connector
Python can be linked with MySQL using several packages. One popular package used to connect Python
with MySQL is mysql.connector-python
A Python package named mysql.connector-python must be installed first before one can use
mysql.connector. A Python package can be installed by using pip install command. Before pip
command is executed, we have to start command line interface in the following way:
Windows Key+R and type CMD and hit <ENTER>
At the command prompt type pip install mysql.connector-python
After importing mysql.connector, we need to create a database connector object using connect()
method of mysql.connector. A database connector object is created as:
dcobj=mysql.connector.connect(host, user, password, [database]) will
connect Python to MySQL server and creates a connector object dcobj. This connect() function has
at least three parameters - host, user, passwd and optional database. By default, host is
localhost (current computer that is being used, instead of localhost, one can use 127.0.0.1), generally the
user is root but it could be anything else also, password is the password for the user and database
is the name of the MySQL database. The last parameter (database) is optional.
Page 19 of 22
Database & MySQL Class XII
After creating the connector object, one must create a cursor object using database connector object. A
cursor object is created as:
cobj=dcobj.cursor() will create cobj as a cursor object using database connector object
dcobj. All the MySQL commands will be executed through cursor object. Few important methods
(functions) of cursor object are listed below:
• cobj.execute() will execute SQL query as a string either single line or multi-line. Unlike
MYSQL, Python's SQL query string does not require terminating semi-colon(;).
• cobj.fetchall() will retrieve all the rows as a list containing tuples after a select query from
the current position of the file pointer. If a select query returns an empty set, then fetchall()
method will return an empty list. fetchall() method does not have any parameter.
• cobj.fetchone() will retrieve one row as a tuple after a select query from the current position
of the file pointer. fetchone() method does not have any parameter.
• cobj.fetchmany(n=1) will retrieve n rows as a nested tuple after a select query from the current
position of the file pointer even if n is greater than number rows in the table. For example, after the
select query, a table is generated with 10 rows, fetchmany(20) will still retrieve all the 10 rows of
the table without triggering any error. If fetchmany() method is called without any parameter, it
will retrieve one row as a list containing a tuple.
• dcobj.commit() is needed after a DML commands like INSERT INTO, DELETE FROM and
UPDATE to ensure that the table is correctly and physically updated. For INSERT INTO, row must
be physically inserted in the table. For DELETE FROM, row must be physically deleted from the
table. For UPDATE, row must be physically updated in the table. Without using dcobj.commit(),
it will display the table correctly using Python but when select command executed through MySQL
command line interface will not display the updated table correctly.
• dcobj.close()will disconnect the link between MySQL server and the Python created with the
connect() method. This statement (call to close() method) is optional.
• Example #1:
dcobj=mysql.connector.connect(host='localhost', user='root',
password='P@ssW0rd')
cobj=dcobj.cursor()
cobj.execute('use mydb')
host is localhost, user is root, password is P@ssW0rd and database name is mydb
Database is activated using use mydb command.
• Example #2:
dcobj=mysql.connector.connect(host='127.0.0.1', user='root',
password='P@ssw0rd',database='mydb')
host is 127.0.0.1, user is root, password is P@ssW0rd and database name is mydb
127.0.0.1 is the IP address of the localhost. Database is activated using database parameter of the
connect() function of mysql.connector.
While creating database connector object using connect() function of mysql.connector, one
must use keyword arguments (parameters). Without keyword argument (parameter), Python will
trigger run-time error.
Page 20 of 22
Database & MySQL Class XII
1. Write a menu driven Python program to do the following:
a) Create a table teacher in the database class12b with following columns:
CODE INT teacher's code
NAME CHAR (20) teacher's name
GENDER CHAR (6) gender of the teacher
DEPT CHAR (15) department
NOP INT number of periods per week
b) Add following rows in the teacher table:
CODE NAME GENDER DEPT NOP
2011 MR. JATIN MALE MATHEMATICS 27
2013 MR. PRANAV MALE CHEMISTRY 26
2015 MS. GEETA FEMALE PHYSICS 27
2017 MS. MARIA FEMALE CHEMISTRY 24
2019 MS. PARUL FEMALE MATHEMATICS 25
2012 MR. ADITYA MALE PHYSICS 24
2014 MS. ROOPA FEMALE PHYSICS 25
2016 MS. MALATI FALE MATHEMATICS 24
2018 MR. DEEPAK MALE CHEMISTRY 27
2020 MR. KUNAL MALE PHYSICS 27
Page 22 of 22