0% found this document useful (0 votes)
7 views

Database

Uploaded by

Parth Takle
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Database

Uploaded by

Parth Takle
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Database & SQL

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).

Relation / Table / Database file


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

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.

Relation (Table): 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 Record /
1012 NITU BHAT DIRECTOR 2008-10-15 95000 55123765 Row /
1049 ALOKA SINGH DIRECTOR 2007-04-09 90000 64192837 Tuple
1025 RITA GUPTA DIRECTOR 2008-10-15 95000 55876534
1017 ADITYA JAIN MANAGER 2008-09-03 75000 98283761

Field / Column / Attribute


Degree Cardinality
Number of Columns in a Table (Relation) Number of Rows in a Table (Relation)

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

Primary Key Candidate Keys Alternate Key

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

Cartesian product of Student and Teacher: Student (R1) X Teacher (R2)


ROLL SNAME CLASS TNAME SUBJECT
1 AKASH 12 MS. RITA GEOGRAPHY
1 AKASH 12 MR. ANUP POLITICAL SC
5 DIPAK 11 MS. RITA GEOGRAPHY
5 DIPAK 11 MR. ANUP POLITICAL SC
31 STUTI 11 MS. RITA GEOGRAPHY
31 STUTI 11 MR. ANUP POLITICAL SC

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

SQL - Structured Query Language


DDL – Data Definition Language
DDL deals with structure of a table, which sets up, changes or removes data structures from the database.
A DDL command includes the word ‘table’ after the SQL command name.

DML – Data Manipulation Language


DML includes those commands, which deals data stored in a table. DML is a set of commands that enables
users to access or manipulate data.

Commonly used Data Types of SQL


1. CHAR : Used to store textual data (characters). Text (either single character or string of characters)
are to be enclosed within a pair of single quote (') or pair of double quote (").
2. NUMERIC: Used to store numeric data. Any number, either integer or floating point value (real
number) can be a numeric type.
3. DATE: Used to store date type data. A date type value is represented as YYYY-MM-DD. Date type
constant is enclosed with either pair single quote (') or pair of double quote ("). Delimiter for char
type and date are same

Creating a new table in a database (DDL)


Syntax:
Create Table TableName (Col1 DataType1, Col2 DataType2, …);
Create Table command creates a new table without any rows (tuples).

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.

Adding new column(s) in the table (DDL)


Syntax:
Alter Table TableName ADD Col DataType;
Alter Table command adds a new column to an existing table.

Examples:
Alter Table Student ADD Class Numeric(2);
Alter Table Student ADD Sec Char;
Note: The columns Class and Sec will have value NULL.

Insert Into Student Values(18,'MOHD ALI',6800,'1989-01-31',12,'C');


Insert Into Student Values(4,'ASIT GARG',6900,'1988-07-10',12,'A');

Modifying the existing content of the table (DML)


Syntax:
Update TableName Set Col1=Value1, Col2=Value2, … Where Condition;
• Operator =, when used in a condition, compares two values.
• Operator =, when used with SET will assign value to a column.

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;

Deleting a row/rows from a table (DML)


Syntax:
Delete From TableName Where Condition;

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;

Table Student used for Select commands given below.


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

Displaying the content from a table – SELECT (DML)


Syntax:
i) Select * From TableName Where Condition;
ii) Select Col1, Col2, Col3, … From TableName Where Condition;
Select commands retrieves data stored in a table. Columns could be an expression also. If Where
Condition is omitted then all the rows of a table are selected.

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

Select Name From Student;


Name
MANISH SINGH
DHRUTI GUPTA
SUNIT KUMAR
PUNEET ARORA
SUBHOJIT SAHA
ASIT BHARGAV
Page 5 of 22
Database & MySQL Class XII
SUSHIL JAIN
ARPITA SHETTY
SUNILA DESAI

Select Roll, Name, Class, Sec From Student;


Roll Name Class Sec
21 MANISH SINGH 12 B
17 DHRUTI GUPTA 12 C
24 SUNIT KUMAR 12 A
16 PUNEET ARORA 12 A
33 SUBHOJIT SAHA 12 C
13 ASIT BHARGAV 12 B
10 SUSHIL JAIN 12 A
14 ARPITA SHETTY 12 C
27 SUNILA DESAI 12 B

SELECT with WHERE clause (DML)


Select * From Student Where Roll>20;
Roll Name Fees Dob Class Sec
21 MANISH SINGH 7800 1989-09-07 12 B
24 SUNIT KUMAR 7500 1989-08-24 12 A
33 SUBHOJIT SAHA 6800 1989-01-31 12 C
27 SUNILA DESAI 7000 1990-11-29 12 B

Select * From Student Where Roll>=10 And Roll<=20;


Roll Name Fees Dob Class Sec
16 PUNEET ARORA 7500 1990-05-12 12 A
10 SUSHIL JAIN 6900 1988-03-13 12 A
17 DHRUTI GUPTA 8800 1988-02-28 12 C
13 ASIT BHARGAV 8500 1989-04-29 12 B
14 ARPITA SHETTY 7200 1988-06-15 12 C
Select Roll, Name, Sec From Student Where Sec='A' Or Sec='B';
Roll Name Sec
21 MANISH SINGH B
24 SUNIT KUMAR A
16 PUNEET ARORA A
13 ASIT BHARGAV B
10 SUSHIL JAIN A
27 SUNILA DESAI B

Select Roll, Name, Sec From Student Where Class!=12;


Empty Set.

Select * From Student Where Sec In ('A', 'C');


Roll Name Fees Dob Class Sec
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

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 Dob Between '1988-1-1' And '1988-12-31';


Roll Name Fees Dob Class Sec
17 DHRUTI GUPTA 8800 1988-02-28 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 Between 7000 And 9000;


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
13 ASIT BHARGAV 8500 1989-04-29 12 B
14 ARPITA SHETTY 7200 1988-06-15 12 C
27 SUNILA DESAI 7000 1990-11-29 12 B

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

Select Name From Student Where Name Like 'A%';


Name
ASIT BHARGAV
ARPITA SHETTY

Select Name From Student Where Name Like '%A';


Name
DHRUTI GUPTA
PUNEET ARORA
SUBHOJIT SAHA

Select Name From Student Where Name Like '%A%';


Name
MANISH SINGH
DHRUTI GUPTA
SUNIT KUMAR
PUNEET ARORA
SUBHOJIT SAHA
ASIT BHARGAV
SUSHIL JAIN
ARPITA SHETTY
SUNILA DESAI
Page 7 of 22
Database & MySQL Class XII
SELECT with ORDER BY clause (DML)
Syntax:
i) Select * From TableName
Order By Col1 [Asc/Desc], Col2 [Asc/Desc], …;
ii) Select * From TableName
Where Condition Order By Col1 [Asc/Desc], Col2 [Asc/Desc], …;
iii) Select Col1, Col2, Col3, … From TableName
Where Condition Order By Col1 [Asc/Desc], Col2 [Asc/Desc], …;

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 * From Student Where Sec='B' Order By Name;


Roll Name Fees Dob Class Sec
13 ASIT BHARGAV 8500 1989-04-29 12 B
21 MANISH SINGH 7800 1989-09-07 12 B
27 SUNILA DESAI 7000 1990-11-29 12 B

Select * From Student Where Fees>=7800 Order By Fees Desc;


Roll Name Fees Dob Class Sec
17 DHRUTI GUPTA 8800 1988-02-28 12 C
13 ASIT BHARGAV 8500 1989-04-29 12 B
21 MANISH SINGH 7800 1989-09-07 12 B

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

SELECT with Aggregate functions or SQL functions or Group functions (DML)


COUNT() Counts the number of rows
SUM() Finds the sum of values in the column (only applicable for Numeric type)
AVG() Finds the average of values in the column (only applicable for Numeric type)
MAX() Finds the maximum value in the column
MIN() Finds the minimum value in the column

Select Count(*) From Student;


Count(*)
9

Select Count(Rno) From Student;


Count(Rno)
9

Select Sum(Fees) From Student;


Sum(Fees)
68000.00

Select Avg(Fees) From Student;


Avg(Fees)
7555.56

Select Max(Fees), Min(Fees) From Student;


Max(Fees) Min(Fees)
8800 6800

Select Max(Dob), Min(Dob) From Student;


Max(Dob) Min(Dob)
1990-11-29 1988-02-27

Select Max(Name), Min(Name) From Student;


Max(Name) Min(Name)
SUSHIL JAIN AMOL SAHA
Page 9 of 22
Database & MySQL Class XII
Select Sec From Student;
Sec
B
C
A
A
C
B
A
C
B

Select Distinct Sec From Student;


Sec
A
B
C

Select Count(Sec), Count(Distinct Sec) From Student;


Count(Sec) Count(Distinct Sec)
9 3

SELECT with GROUP BY (DML)


Select Sec, Sum(Fees) From Student Group By Sec;
Sec Sum(Fees)
A 21900
B 23300
C 22800

Select Sec, Count(*) From Student Group By Sec;


Sec Count(*)
A 3
B 3
C 3

Select Sec, Max(Fees), Min(Fees) From Student Group By Sec;


Sec Max(Fees) Min(Fees)
A 7500 6900
B 8500 7000
C 8800 6800

Select Sec, Sum(Fees) From Student Group By Sec Having


Sum(Fees)>22000;
Sec Sum(Fees)
B 23300
C 22800

SQL Cartesian Product


Example of Cartesian Product:
Page 10 of 22
Database & MySQL Class XII
Table: Student Table: Teacher
Roll SName Class TCode Class TName
1 AKASH XII 102 XII MS. RINEE
4 DIBAKAR XII 309 XI MR. TANMOY
7 ROHINI XI
10 RISHI XI

Select Roll, SName, Class, TCode, TName From Student, Teacher;


Roll SName Class TCode TName
1 AKASH XII 102 MS. RINEE
1 AKASH XI 309 MR. TANMOY
4 DIBAKAR XII 102 MS. RINEE
4 DIBAKAR XI 309 MR. TANMOY
7 ROHINI XII 102 MS. RINEE
7 ROHINI XI 309 MR. TANMOY
10 RISHI XI 102 MS. RINEE
10 RISHI XII 270 MR. ALICE

Select Roll, SName, Class, TCode, TName From Student, Teacher


Where Student.Class=Teacher.Class;
Roll SName Class TCode TName
1 AKASH XII 309 MR. TANMOY
4 DIBAKAR XII 309 MR. TANMOY
7 ROHINI XI 270 MR. ALICE
10 RISHI XI 270 MR. ALICE

Select Roll, SName, Class, Teacher From Student S, Teacher T


Where S.Class=T.Class AND Class="XII";
Roll SName Class TCode TName
1 AKASH XII 309 MR. TANMOY
4 DIBAKAR XII 309 MR. TANMOY

SQL Union
Example of Union:
Table: Stu1 Table: Stu2
Adno Name Adno Name
20050014 FATIMA 20050017 REKHA
20050029 FARAZ 20050023 TUSHI
20050004 GAURI

Select * from Stu1 Union Select * From Stu2;


Adno Name
20050014 FATIMA
20050029 FARAZ
20050004 GAURI
20050017 REKHA
20050023 TUSHI
Page 11 of 22
Database & MySQL Class XII
MySQL Constraints
➢ NOT NULL
create table item (code int, prod char(10), price float);

describe item; MySQL command describe, displays the structure of a table


+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| code | int | YES | | NULL | |
| prod | char(10) | YES | | NULL | |
| price | float | YES | | NULL | |
+-------+----------+------+-----+---------+-------+
All the three columns of the table item will accept NULL values either directly or indirectly. When
creating a table in MySQL, by default every column will accept NULL value.

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);

select * from item;


+------+---------+-------+
| code | prod | price |
+------+---------+-------+
| 1001 | INK PEN | 0.25 |
| 1002 | GEL PEN | 0.35 |
| 1003 | DOT PEN | 0.15 |
| 1004 | RULER | NULL |
| 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);

How to add NOT NULL constraint after creating a table?


create table item (code int, prod char(10), price float);

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.

How to remove NOT NULL constraint from a column from a table?


alter table item modify code int;
OR, alter table item modify column code int;
Query removes NOT NULL constrains for the column code from the table item.

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.

insert into item values (1003,'RULER', 0.20);


Query will trigger syntax error since code is Primary key and cannot contain duplicate values.

insert into item values (1004,'DOT PEN', 0.15);


Query will trigger syntax error, since prod is Unique column and cannot contain duplicate values.
A field with Unique constraint, will not accept duplicate values but it will accept NULL values.

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.

select * from item;


+------+---------+-------+
| code | prod | price |
+------+---------+-------+
| 1001 | INK PEN | 0.25 |
| 1002 | GEL PEN | 0.35 |
| 1003 | DOT PEN | 0.15 |
+------+---------+-------+

➢ Adding Primary key and Unique constraints after creating a table:


create table item (code int, prod char(10), price float);
Creates a table item without any Primary key and without any Unique constraint.

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);

select * from item;


+------+---------+-------+
| code | prod | price |
+------+---------+-------+
| 1001 | INK PEN | 0.25 |
| 1002 | GEL PEN | 0.35 |
| 1003 | DOT PEN | 0.15 |
| 1004 | RULER | 0.15 |
| 1005 | ERASER | 0.15 |
+------+---------+-------+

alter table item add primary key (code);


Column code becomes the Primary key in the table item. Primary key constraint cannot be added
to a column, if the column contains either duplicate values or NULL values or both. Trying to add
Primary key constraint to a column containing duplicate values or NULL values will trigger a
syntax error.

alter table item add unique (prod);


Column prod becomes a key (Unique constraint added for the field prod) in the table item.

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 | |
+-------+----------+------+-----+---------+-------+

alter table item drop primary key;


Removes the Primary key code from the table item but the column code is still present in the
table item. By removing the Primary key constraint, does not remove NOT NULL constraint. NOT
NULL constraint needs to be removed separately.

alter table item drop index prod;


Removes the Unique constrains (key prod) from the table item but the column prod is still
present in the table item.

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 | |
+-------+----------+------+-----+---------+-------+

select * from empdata;


+--------+--------+----------+
| code | name | mob |
+--------+--------+----------+
| 199801 | SUNIL | 93661430 |
| 200305 | REETA | 55789215 |
| 202102 | ANITHA | NULL |
+--------+--------+----------+
Primary key cannot contain NULL but Unique key can contain NULL.
Page 16 of 22
Database & MySQL Class XII
➢ Foreign key constraint
A column in one table refer to a Primary key of another table. Or to put another way, a column
in table obtains its value from Primary key of another table. A foreign key is used to link two or
more tables.

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 | |
+-------+----------+------+-----+---------+-------+

select * from empdata;


+--------+--------+----------+
| code | name | mob |
+--------+--------+----------+
| 199801 | SUNIL | 93661430 |
| 200305 | REETA | 55789215 |
| 202102 | ANITHA | 98452301 |
+--------+--------+----------+

How to create a table with Foreign key?


create table empsal (code int, desig char(20), bsal float, foreign
key (code) references empdata (code));
A table empsal is created with Foreign key code. In this example, Primary key and Foreign key
have same name. But Primary key and Foreign key may have different names.

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.

insert into empsal values (200305, 'GEN MANAGER', 175000.0);


insert into empsal values (202102, 'DEP MANAGER', 155000.0);
insert into empsal values (199801, 'SNR MANAGER', 165000.0);
insert into empsal values (200123, 'AST MANAGER', 145000.0);
Page 17 of 22
Database & MySQL Class XII
The query will trigger a syntax error since the code=200123 does not exist in the Primary key
column of empdata table. Foreign key may contain duplicate values, but Primary key cannot
contain any duplicate value.

select * from empsal;


+--------+-------------+--------+
| code | desig | bsal |
+--------+-------------+--------+
| 200305 | GEN MANAGER | 175000 |
| 202102 | DEP MANAGER | 155000 |
| 199801 | SNR MANAGER | 165000 |
| 201010 | JNR MANAGER | 145000 |
+--------+-------------+--------+

Cartesian Product, Natural Join, Equi-Join


• Cartesian Product: Pairing every row of one table with every row of another table. New table's degree
is sum of degrees of the two tables. New table's cardinality is the product of the cardinalities of the
two tables. An example is given below.

create table student (roll int, sname char(10), cla int);


insert into student values (14, 'AKASH', 12);
insert into student values (15, 'DEEPAK', 12);
insert into student values (16, 'ROSHAN', 11);
insert into student values (17, 'DEEPA', 11);

create table teacher (code int, tname char(10), cla int);


insert into teacher values (1201, 'MS. SMITA', 12);
insert into teacher values (1102, 'MR. VARUN', 11);

Cartesian Product of student table and teacher table is


select * from student join teacher;
OR, select * from student, teacher;
+------+--------+------+------+-----------+------+
| roll | sname | cla | code | tname | cla |
+------+--------+------+------+-----------+------+
| 14 | AKASH | 12 | 1102 | MR. VARUN | 11 |
| 14 | AKASH | 12 | 1201 | MS. SMITA | 12 |
| 15 | DEEPAK | 12 | 1102 | MR. VARUN | 11 |
| 15 | DEEPAK | 12 | 1201 | MS. SMITA | 12 |
| 16 | ROSHAN | 11 | 1102 | MR. VARUN | 11 |
| 16 | ROSHAN | 11 | 1201 | MS. SMITA | 12 |
| 17 | DEEPA | 11 | 1102 | MR. VARUN | 11 |
| 17 | DEEPA | 11 | 1201 | MS. SMITA | 12 |
+------+--------+------+------+-----------+------+
All the columns including column common (cla) to both the tables will be displayed.

• 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

mysql.connector is an interface between Python and MySQL server. To use mysql.connector


in a Python script one has to use the following statement:
import mysql.connector as mysql #import mysql.connector
mysql is an alias for mysql.connector.

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

c) Write a Python function to execute following query (with menu):


i) Display the teacher table on the screen
ii) Display the teacher table sorted in descending order of NOP
iii) Input CODE and search for CODE in the teacher table. If inputted CODE does not exist, then
display an appropriate message.
iv) Input DEPT and displays all the teacher's details for the inputted DEPT. If inputted DEPT
does not exist, then display an appropriate message.
v) Display number teachers DEPT-wise
vi) Display number teachers GENDER-wise
d) Write a Python function to add following columns in the teacher table:
DESIG CHAR (3) DESIG Designation
BONUS FLOAT BONUS Diwali bonus
e) Write a Python function to edit column DESIG as:
CODE NAME DESIG
2011 MR. JATIN TGT
2013 MR. PRANAV TGT
2015 MS. GEETA PGT
2017 MS. MARIA HOD
2019 MS. PARUL PGT
2012 MR. ADITYA HOD
2014 MS. ROOPA PGT
2016 MS. MALATI HOD
2018 MR. DEEPAK TGT
2020 MR. KUNAL TGT
To edit column BONUS:
DESIG BONUS
HOD 2000
PGT 1750
TGT 1500
Page 21 of 22
Database & MySQL Class XII
f) Write a Python function to execute following query (with menu):
i) Input CODE and delete the row containing inputted CODE from the teacher table. If inputted
CODE does not exist, then display an appropriate message.
ii) Input NAME and delete the row containing inputted NAME from the teacher table. If inputted
NAME does not exist, then display an appropriate message.

Page 22 of 22

You might also like