Notes
Notes
SCIENCE (083)
UNIT-III DATABASE MANAGEMENT SYSTEM
Pa
CHAPTER-9 DATABASE MANAGEMENT SYSTEM (DBMS)
9.1 INTRODUCTION:
DBMS is a collection of interrelated data in arranged form and set of programs used
to access those data.
Advantages of DBMS:
9.2DATA MODELS:
Data models describe the structure of the database. There are four data models
in DBMS:
1. Relational Data Model
2. Hierarchical Data Model
3. Network Model
4. Object Oriented Data Model
2. Hierarchical Data Model: In this model the data are represented by collection
and relationship between data are represented by links. In this model the
collection of data are organized as tree.
3. Network Data Model: This is same as the hierarchical model but in this model
the collection of data is organized as arbitrary graphs.
4. Object Oriented Data Model: In this model the data and its operations are
represented by objects.
Collection of attributes
9.3KEYS:
1. Primary Key
2. Candidate Key
3. Alternate Key
4. Foreign Key
1. Primary Key: A primary key is a set of one or more attributes that can
uniquely identify tuples within the relation. This key does not have duplicate
values in the relation. There must be any value for this key, it cannot be NULL.
Pa
Primary Key
Table: STUDENT
2. Candidate Key: All attributes combination inside a relation that can serve as
a primary key, is called candidate key.
3. Alternate Key: A candidate key that is not the primary key is called an
alternate key.
4. Foreign Key: A non-key attribute whose values are derived from the primary
key of some other table, is known as foreign key in its current table.
Primary key of parent table becomes the foreign key for the child table.
Pa
9.4 INTRODUCTION TO MySQL:
9.4.1 Introduction:
Pa
First you have to install MySQL on your system. Then click on
9.5 SQL:-
SQL MySQL
This is the language that used in
This is the open source database.
database.
Pa
9.6 SQL Elements:
1. Literal
2. Data Types
3. Nulls
4. Comments
1. Literal: A literal is a fixed data value. This fix value may be numeric or character.
Character Literal: All character literals are enclosed in single quotation mark or double
quotation marks.
For example :- ‘a’ , “yogesh” , ‘5’, “xyz5”
2. Data Types:- Data types are rules that define what data may be stored in a
column and how that data is actually stored. Data types used in MySQL
categorized into four categories:
(i)Numeric
(ii) String
(iii) Date and Time
(iv) Binary
Pa
(i) Numeric: This data type stores numbers.
Int Normal size integer that can be signed or unsigned.
Width
upto 11 digits.
TinyInt A very small integer that can be signed or unsigned.
Width
upto 4 digits.
SmallInt A small integer that can be signed or unsigned. Width
upto
5 digits.
MediumInt A medium size integer that can be signed or unsigned.
Width upto 9 digits.
BigInt A large integer that can be signed or unsigned.
Float(M,D) A floating point number.
M :- Length of total
number D :- Number of
decimals Ex.- Float(10,2)
10 is the total number of digits and 2 is the number of
decimals.
DOUBLE(M,D) A double precision floating point number.
Decimal(M,D) Floating point values with varying levels of precision.
(ii) String:
Char(M) A fix length string between 1 to 255 characters.
M :- Length
Varchar(M) A variable length string between 1 to 255 characters.
Enum Accepts one of a predefined set of strings.
Text Variable length text with a maximum size of 64 K.
TinyTEXT Same as text, but with a maximum size of 255 bytes.
MediumTEX Same as text, but with a maximum size of 16K.
T
LongTEXT Same as text, but with maximum size of 4GB.
Pa
(iv) Binary Data Type: Stores the data in binary objects, such as graphics,
images, multimedia etc.
BLOB Stands for Binary Large Objects.
Maximum Length=64K
TINYBLOB Maximum length=255 bytes.
MEDIUMBLOB Maximum Length= 16MB
LONGBLOB Maximum length= 4GB
3. NULL values: If a column in a row has no value, then column is said to be
null. NULLs can appear in a column if the column is not restricted by NOT
NULL or Primary Key. You should use a null value when the actual value is not
known. Null and Zero is not equivalent. Any arithmetic expression containing a
null always evaluates to null.
Example: 7 + null = null
7+0=7 Difference between null and zero.
4. Comments: Comment is a text that is not executed. There are two types of
comments that we use in MySQL.
(i) Single line Comment: Beginning with two hyphens (--) OR
beginning with # symbol.
(ii) Multi Line Comment:/*………………………………………..
…………………………………….*/
Char Varchar
1. Fixed length character string. Variable length character string.
2. When a column is given data
Each value that is stored in this
type as char(N). If a value is
column stores exactly as you
shorter than this length N
specify it. No blanks are added,
then blanks are added, but
if the length is shorter than
the size of value
maximum length N.
remains N byte.
3. Faster to access. Takes less disk space.
Pa
9.7 Classification of SQL commands:
(i)Data Definition Language (DDL): It consist the commands to create objects such as tables,
views, indexes etc. in the database.
COMMANDS: CREATE, ALTER, DROP, RENAME, TRUNCATE
(ii)Data Manipulation Language (DML): It is used for queries. It allows you to perform data
manipulation e.g. retrieval, insertion, deletion, modification of data stored in database.
COMMANDS: SELECT, INSERT, UPDATE, DELETE
(iii)Transaction Control Language (TCL): This language allows you to manage and control the
transaction.
COMMANDS: COMMIT, ROLLBACK
● NOTE:- Savepoint is also used in TCL.
(iv)Data Control Language (DCL): This language is used to control data and access to the
databases. It is used for protecting the data from unauthorized access. COMMANDS:
GRANT, REVOKE
In MySQL, to create new tables or query, the user must specify the database. This
database is called current database.
To check the available database in MySQL:-
SHOW databases;
Pa
A database has tables. Tables have rows and columns.
SHOW tables;
CREATING DATABASE: In MySQL we can create the databases using CREATE DATABASE
statement.
Syntax: CREATE DATABASE <database-name>;
OPENING DATABASE:
A table has rows and columns. The column name must be specified along the data
type. Each table must have at least one column.
Syntax:
Example:
Pa
CREATE TABLE EMPLOYEE(Ecode int(6), Ename varchar(30), Dept varchar(30), city
varchar(25), sex char(1), DOB Date, salary float(12,2) );
Fig. : EMPLOYEE
Viewing a table structure:
DESC EMPLOYEE;
Or we can write
DESCRIBE EMPLOYEE;
Syntax:
The into clause specifies the target table and the value clause specifies the
data to be added to the new row of the table.
While inserting data into tables, following points should be taken care of:
Pa
√ If no data is available for all the columns then the column list must be
included, following the table name. Example: INSERT INTO EMPLOYEE(Ecode,
Ename, salary) VALUES(1001, ‘Amit’, 20000.00);
9.9 CONSTRAINTS:
Pa
(v) PRIMARY KEY
(vi) FOREIGN KEY
(i) NOT NULL Constraint: This constraint ensures that a column cannot have NULL
value. By default, a column can hold NULL. If you add a NOT NULL constraint on a
column it cannot hold a NULL.
Pa
How to apply NOT NULL constraint:-
Example:-
Example:-
Example:-
Example:-
Pa
Example:-
(iv) CHECK constraint: - It make sure that all the values in a column
satisfy certain criteria.
How to apply check constraint:-
(v) Primary Key Constraint: - This is used to uniquely identify a row in a table.
Pa
(vi) Foreign Key Constraint:- Whenever two tables are related by a
common column, then the related column in the parent table should be either
declared a PRIMARY KEY or UNIQUE KEY and the related column in the child
table should have FOREIGN KEY constraint.
Syntax:-
Foreign key(<column-to-be-designated-as-foreign-key>) references parent-
table (<primary-key-of parent table>);
Primary key of parent table becomes the foreign key for the child table.
Pa
Dropping a constraint:-
DROP constraint<constraint-name>;
Example:
PRIMARY KEY;
To remove foreign key
constraint:-
Syntax:-
ALTER TABLE table-name
(i) To change the data-type and size of the column, we use the
MODIFY command.
(ii) To change the name of the column, we use the CHANGE command.
Pa
(i) To change the data-type and size of the column, we use the MODIFY
command:-
The syntax is:-
ALTER TABLE table-name
MODIFY(Col_name newdatatype(newsize));
Example:
(ii) To change the name of the column, we use the CHANGE command:-
ALTER TABLE <table-name>
Example:
9.12DROPPING A TABLE:
To remove the entire structure of the table completely, we use the DROP TABLE
command.
Syntax:
Example:
Pa
9.13 MANIPULATING DATA OF A TABLE:-
(iii) DELETE Command:- It means delete the information from the table. This
command is used to remove the rows from the table.
Specific rows are deleted when you specify the WHERE clause.
All rows in the table are deleted if you omit the WHERE clause. The
syntax is:
DELETE FROM <table-name>
WHERE <condition> ;
WHERE dept=’production’;
Example:- Delete all the records of EMPLOYEE table having salary less than 35000.
Solution: DELETE
Salary<35000;
(iv) UPDATE command:- Values of a single column or group of columns can
be updated.
The syntax is:- UPDATE table-name
SET column_name=value
WHERE condition;
Pa
Example:- Change the salary of Vikram to 36000.
SET salary=36000
WHERE Ename=’Vikram’;
Example:- Increase every employee salary by 10%.
SET salary=salary+(salary*0.1);
(i) SELECT:-
A SELECT command is used to retrieve information from a table.
● If you want to select the all columns from a table, then we use the
asterisk(*) in SELECT clause.
Example: - SELECT * FROM EMPLOYEE;
● To display specific columns of the table by specifying the column names,
separated by commas.
Example: - SELECT
Ecode, Ename, salary FROM
EMPLOYEE;
(ii) FROM:-
A FROM clause, specifies the table name that contains the columns.
(iii) WHERE:-
A WHERE clause, specifies the condition.
Pa
WHERE condition;
Pa
SOME IMPORTANAT POINTS:-
● Selecting All Columns:- To select all the columns, we use asterisk (*) in
SELECT statement.
Example:- SELECT *
FROM EMPLOYEE;
ALL keyword:-
SQL allows us to use the keyword ALL to specify explicitly that duplicates are not
removed.
FROM
EMPLOYEE;
Arithmetic Operations:-
The SELECT clause may also contain arithmetic expressions involving the operators +, -
, * and / operating on constants or attributes.
Pa
SELECT
Ename,salary,salary*0.25 FROM
EMPLOYEE;
Pa
COLUMN ALIAS:-You can change a column heading by using a column alias.
Examples of Queries:-
Pa
(ii) IN :-
Example:- Find the name of those employees who live in guwahati, surat or jaipur
city.
Solution:-
SELECT Ename, city
FROM EMPLOYEE
WHERE city IN(‘Guwahati’,’Surat’,’Jaipur’);
Pa
(iii) LIKE :-
% :- It represents any sequence of zero or more characters.
_ :- Represents any single character.
Example:- Display the name of those employees whose name starts with ‘M’.
Solution:-
SELECT
Ename FROM
EMPLOYEE
WHERE Ename LIKE ‘M%’;
Example:-Display the name of those employees whose department name ends with ‘a’.
Solution:-
SELECT
Ename FROM
EMPLOYEE
WHERE Dept LIKE ‘%a’;
Example:- List the name of employees whose name having ‘e’ as the second
character.
Solution:-
SELECT
Ename FROM
EMPLOYEE
WHERE Ename LIKE ‘_e%’;
(iv) IS NULL :-
Solution:-
SELECT
Ename FROM
EMPLOYEE
WHERE Dept IS NULL;
IFNULL( ) function:-
If you want to substitute null with a value in the output, you can use IFNULL( ) function.
Pa
Syntax:-
Pa
Example:-
EMPLOYEE;
Pa
9.16 ORDER BY clause:-
You can sort the result in a specific order using ORDER BY clause. The
sorting can be done either in ascending or descending order. The default order is
ascending.
Example:- Display the list of employees in descending order of employee code.
Solution:-
SELECT *
FROM
EMPLOYEE ORDER BY
ecode DESC;
Example:- Display the employee code, name in ascending order of salary.
Solution:-
SELECT Ecode,
Ename, salary FROM
EMPLOYEE
ORDER BY salary asc;
Suppose that we wish to list the entire EMPLOYEE relation in descending order of
salary. If several employees have the same salary, we order them in ascending order
by employee code. We express this query in SQL as follows:-
SELECT *
FROM EMPLOYEE
ORDER BY salary desc, Ecode asc;
Aggregate functions are functions that take a collection of values as input and return
a single value. SQL offers five types of aggregate functions:-
In some circumstance, we would like to apply the aggregate function not only to a
single set of tuples, but also to a group of sets of tuples. We specify this wish in
SQL using the group by clause.
The attributes given in the group by clause are used to form groups.
Pa
Q.5Find the total salary of those employees who work in Guwahati city.
Solution:-
SELECT sum(salary)
FROM EMPLOYEE
WHERE city=’Guwahati’;
Q.6Find the total salary of all employees in EMPLOYEE relation.
Solution:-
SELECT sum(salary)
FROM EMPLOYEE;
9.18 JOINS:
An SQL JOIN clause is used to combine rows from two or more tables, based on a
common field between them.
TABLE: CUSTOMER
CUST_ID CUST_NAME GENDER CITY
101 Rahul M DELHI
105 Sushil M GOA
206 Sunita F MUMBAI
517 Gaurav M VADODARA
TABLE: ORDERS
ORDER_ID CUST_ID ORDER_DATE AMOUNT
14578 105 10/04/2016 1850.50
25685 517 15/03/2015 8569.00
89632 222 01/01/2016 5362.20
Pa
78451 105 30/05/2015 450.00
Pa
Types of Joins:
1.Cartesian Product
2.Equi Join
3.Natural Join
a. INNER JOIN: Returns all rows when there is at least one match in BOTH
tables. This joining is known as simple join. You can use JOIN keyword also in
the place of INNER JOIN. Both will give same result.
Syntax:
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;
Example: OUTPUT
SELECT CUST_NAME, ORDER_ID FROM
CUST_NAME ORDER_ID
CUSTOMER
SHUSHIL 14578
INNER JOIN ORDERS SHUSHIL 78451
ON
GAURAV 25685
CUSTOMER.CUST_ID=ORDER.CUST_ID;
Pa
b.LEFT JOIN: Return all rows from the left table, and the matched rows from the right table
c.RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table
d.FULL JOIN: Return all rows when there is a match in ONE of the tables
** The equi join and Natural Join are equivalent except that duplicate columns are
eliminated in the Natural Join.
● Install python
● Install MySQL
● Install MySQL Driver using following command: (In Command Prompt):
pip install mysql-connector
Note: Make sure your computer is connected with internet.
If the command successfully runs (without any error), then the MySQL connector is
successfully installed.
● Now, open MySQL and check the current user, by typing the following
command in MySQL:
Pa
● Connect MySQL database with python. For this, open Python IDLE and write
the following code in python file.
CODE:
import mysql.connector
demodb=mysql.connector.connect(host="localhost",user="root",
passwd="computer") print(demodb)
If you get the following output, then the connection made successfully.
OUTPUT:
Pa
●
CODE:
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("CREATE TABLE STUDENT (admn_no int primary key,
sname varchar(30), gender char(1), DOB date, stream varchar(15), marks
Pa
To verify the table created or not, write the following code in python:
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor = demodb.cursor( )
democursor.execute ("show
tables") for i in democursor:
print(i)
OUTPUT:
Pa
democursor=demodb.cursor( )
democursor.execute("select * from
student") for i in democursor:
print(i)
OUTPUT:
Pa