DBMS
DBMS
MYSQL
It is freely available open source Relational Database Management System (RDBMS) that uses
Structured Query Language(SQL). In MySQL database, information is stored in Tables. A
single MySQL database can contain many tables at once and store thousands of individual
records.
➢ Reducing data redundancy – This ensures a consistent database and efficient use of
storage space.
➢ Aiding multiple views of the data: Database management system enables different users
to have a view of the data from their own perspective
➢ Implementation of data integrity The term data integrity refers to the accuracy and
consistency of data. When creating databases, attention needs to be given to data integrity
and how to maintain it.
➢ Data sharing and security – DBMS limits the accessibility of the data to the authorized
users only. This makes data sharing safer. Moreover shared data makes it possible to fulfill
data requirements with minimal modifications.
➢ Centralized data ensures a more effective backup and recovery process than the
conventional file processing systems.
➢ Program & Data independence: Programs and the data are not mutually dependent. If a
programmer wants to change the structure of the database then he/she can do so without
affecting the application programs that are using the database.
➢ Data Abstraction: It ensures that the users get an abstract view of the data without showing
implementation details and the physical storage of thedata.
160
2. Tuple: A row of a relation is generally referred to as a tuple.
6. Primary Key: This refers to a set of one or more attributes that can uniquely identify tuples
within the relation.
7. Candidate Key : All attribute combinations inside a relation that can serve as primary
key are candidate keys as these are candidates for primary key position.
8. Alternate Key: A candidate key that is not primary key, is called an alternate key.
9. 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.
REFERENTIAL INTEGRITY
A referential integrity is a system of rules that a DBMS uses to ensure that relationships
between records in related tables are valid, and that users don’t accidentally delete or
change related data. This integrity is ensured by foreign key.
CLASSIFICATION OF SQL STATEMENTS
SQL commands can be mainly divided into following categories:
DATA TYPES
Data types are means to identify the type of data and associated operations for handling it.
MySQL data types are divided into three categories:
➢ Numeric
➢ Date and time
➢ String types
Numeric Datatype
1. int– used for number without decimal.
161
2. decimal(m,d) – used for floating/real numbers. m denotes the total length of number
and d is number of decimal digits.
Date and Time Datatype
1. date–used to store date in YYYY-MM-DD format.
2. time–used to store time in HH:MM:SS format.
String Datatype
1. char(m)–used to store a fixed length string, m denotes max. number of characters.
2. varchar(m)–used to store a variable length string, m denotes max. no. of characters.
DATABASE COMMANDS
1. VIEW EXISTING DATABASE
To view existing database names, the command is: SHOW DATABASES;
162
Eg: insert into employee values(1001,‘Ravi’,‘M’,‘E4’,50000);
Or
Insert into employee(ecode,ename)values(1002,’Meena’);
The left out columns will be filled with null values.
Select Command:
e.g.To display ECODE,ENAME and GRADE of those employees whose salary is between 40000
and 50000,command is:
SELECT ECODE , ENAME ,GRADE FROM EMPLOYEE
WHERE GROSS BETWEEN 40000 AND 50000;
163
NOTE: For displaying records not in the specified range, we have to use not between operator.
CONDITION BASED ON A LIST
The in operator is used to display records based on a list of values.
Eg. To display details of employees who have scored A,B and C grades.
Select * from employee where grade in(‘A’,’B’,’C’);
Note: For displaying records that do not match in the list, we have to use not in operator.
LIKE operator is used for pattern matching in SQL. Patterns are described using two special
wildcard characters: % and _ (underscore)
1. percent(%)– The % character matches any substring.
2. underscore(_)– The _ character matches any single character.
e.g.To display names of employee whose name starts with R in EMPLOYEE table, the command is:
select ename from employee where ename like “R%”;
2) To list all the employees’ details having grades as ‘E4’ but with gross < 9000.
164
Select ecode, ename, grade, gross from employee where grade=‘E4’ and gross< 9000;
3) To list all the employees’ details whose grades are other than ‘G1’.
Select ecode, ename, grade, gross from employee where (NOT grade= ‘G1’);
Results of SQL query can be sorted in a specific order using ORDER BY clause.
The ORDER BY clause allows sorting of query results by one or more columns. The sorting can be
done either in ascending or descending order.
Examples:
Select avg(gross) from employee;
Select min(gross) from employee where deptno= 10;
Select count(*) from emp where gross> 10000;
Select count (DISTINCT gender) from employee;
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.
165
Eg: To calculate the number of employees in each grade, the query is:
SELECT grade, count(*) from employee group by grade;
❖ The HAVING clause places conditions on groups in contrast to WHERE clause that places
conditions on individual rows.
❖ WHERE conditions cannot include aggregate functions but HAVING conditions can do so.
Eg: SELECT avg(gross), sum(gross) from employee GROUP BY grade HAVING grade= ‘E4’ ;
DELETE Command
Eg: To remove all the contents of items table, the query is:
DELETE from items;
Eg: To remove the tuples from employee that have gross less than 20000 is :
DELETE from employee WHERE gross<20000;
UPDATE Command
Update Command allows to change some or all the values in an existing rows. Update command
specifies the rows to be changed using the WHERE clause and the new data using the SET
keyword.
Eg. UPDATE employee SET gross= 25000;
The above query sets the gross of all records as 25000.
ALTER TABLE
ALTER TABLE command is used to change the structure of the existing table. It can be used to add
or drop new columns or modify the existing columns of table.
Eg. 1. Alter table Employee Add comm int;
2. ALTER TABLE Emp MODIFY (ename varchar(60));
3. Alter table emp drop comm;
DROP TABLE:
DROP TABLE command allows to remove a table from database. Once the DROP command is
issued, the table will no longer be available in the database.
166
Eg. DROP TABLE employee;
INTEGRITY CONSTRAINTS
A constraint is a condition or check applicable on a field or set of fields.
Common types of constraints include:
ALTER TABLE statement can be used to add constraints to your existing table by using it in
following manner:
SQL JOINS
SQL Joins are essential to display data from more than one table. SQL JOIN clause is used to
combine rows from two or more tables, based on a common field between them. SQL provides
various types of joins:
1. Cartesian Product or Cross Join
2. Equi-Join
3. Natural Join.
Equi-Join
A join which is obtained by putting a condition of equality on cross join is called an 'equi join'.
We can extract meaningful information from the Cartesian product by placing some conditions in the
statement.
The join in which columns are compared for equality is called equi-join.
In this type of join we put * in the select list therefore the common column will appear twice in the
output.
Example: Consider the 2 tables emp and dept.
168
Note: We see that deptno column appears twice in output.
Natural Join
• The join in which only one of the identical columns exists is called natural join.
• It is similar to equi-join except that duplicate columns are eliminated in natural join that would
otherwise appear in equi-join.
Example:
Worksheet – L3
170
(a) Alternate key
(b) Foreign key
(c) Primary key
(d) Super Key
Q10.A non-key attribute, whose values are derived from primary key of some other
table.
(a) Alternate key
(b) Foreign key
(c) Primary key
(d) Super Key
Q21. How can you insert a new row into the “STORE” table.
(a) INSERT ROW(1,‟RAMSINGH‟)INTO STORE;
(b) INSERT VALUES(1,‟RAMSINGH‟)INTO STORE;
(c) INSERT INTO(1,‟RAMSINGH‟)STORE;
(d) INSERT INTO STORE VALUES(1,‟RAMSINGH‟);
Q24. The .................. key word eliminates duplicate rows from the result of a
SELECT statement.
(a) All
(b) Unique
(c) Distinct
(d) IN
Q25. Which operator defines a range of values that the column values must fall in?
(a) In
(b) Like
(c) Between
(d) Is
Q26. To specify a list of values ............... Operator is used.
(a) In
(b) Like
(c) Between
(d) Is
Q27. We use .................. operator with select for condition based on pattern matching.
(a) In
(b) Like
(c) Between
(d) Is
Q28. Which SQL statement will not generate any error message?
(a) SELECT*FROM EMP WHERE EMPNO LIKE(1,2,3,4);
(b) SELECT*FROM EMP WHERE SAL BETWEEN 3000 TO 15000;
(c) SELECT*FROM EMP WHERE COMM IS NOT NULL;
(d) All of the above
Q29.To display the detail of employee having ‘e’ in their name in descending order of
salary. The correct SQL statement is:
(a) SELECT*FROM emp WHERE ename LIKE “e%” ORDER BY SAL;
(b) SELECT*FROM emp ORDER BY SAL DESC WHERE ename LIKE
173
“%e%”;
(c) SELECT*FROM emp WHERE ename LIKE “%e%” ORDER BY DESC
SAL;
(d) SELECT*FROM emp WHERE ename LIKE “%e%” ORDER BY SAL
DESC;
174
Answers
Q.No. Answers
1 B
2 C
3 A
4 d
5 d
6 c
7 a
8 c
9 a
10 b
11 d
12 a
13 a
14 c
15 d
16 c
17 d
18 d
19 b
20 d
21 d
22 b
23 a
24 c
25 c
26 a
27 b
28 c
29 d
30 d
175
WORK SHEET -2
Q2. The clause which is used to group rows based on distinct values that exist
for specified column.
Q3. For conditionally retrieval of row from groups which clause is used?
(a) All
(b) Distinct
(c) Unique
(d) Diverse
Q6. Which option cause a group functions to consider all values including
all duplicated.
(a) All
(b) Distinct
(c) Unique
176
(d) Diverse
(a) AVG
(b) COUNT
(c) MAX
(d) MOD
Consider the relations/tables EMP and DEPT and give the correct answer of following
queries.
Relation: EMP
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 1980-12-17 800.00 NULL 20
7499 ALLEN SALESMAN 7698 1981-02-20 1600.00 300.00 30
7521 WARD SALESMAN 7698 1981-02-22 1250.00 500.00 30
7566 JONES MANAGER 7839 1981-04-02 2975.00 NULL 20
7654 MARTIN SALESMAN 7698 1981-09-28 1250.00 1400.00 30
7698 BLAKE MANAGER 7839 1981-05-01 2850.00 NULL 30
7782 CLARK MANAGER 7839 1981-06-09 2450.00 NULL 10
7788 SCOTT ANALYST 7566 1982-12-09 3000.00 NULL 20
7839 KING PRESIDENT NULL 1981-11-17 5000.00 NULL 10
7844 TURNER SALESMAN 7698 1981-09-08 1500.00 0.00 30
7876 ADAMS CLERK 7788 1983-01-12 1100.00 NULL 20
7900 JAMES CLERK 7698 1981-12-03 950.00 NULL 30
7902 FORD ANALYST 7566 1981-12-03 3000.00 NULL 20
7934 MILLER CLERK 7782 1982-01-23 1300.00 NULL 10
Relation: DEPT
DEPTNO DNAME LOC
10 ACCOUNTING NEWYORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
Q8. SELECT AVG(SAL) FROM EMP WHERE JOB=‘CLERK’;
(a)1037.5
(b)2073.21
(c)1040
(d)2074
(a) 14
(b) 3
(c) 4
(d) 5
177
Q10. SELECT COUNT(DISTINCT JOB) FROMEMP;
(a) 14
(b) 5
(c) 4
(d) 6
(a) 14
(b) 5
(c) 4
(d) 6
(a)2975
(b)5000
(c)3000
(d)2850
(a) 1980-12-17
(b) 1983-01-12
(c) 1982-12-09
(d)None
(a) 1980-12-17
(b) 1983-01-12
(c) 1982-12-09
(d)None
(a) Null
(b) 0
(c)2200
(d)1400
Q17. To display the jobs where the number of employees is less than 3.
(a) SELECT JOB,COUNT(*)FROM EMP WHERE COUNT(*)<3;
(b) SELECT JOB, COUNT(*) FROM EMP WHERE COUNT(*)<3
GROUP BY JOB;
(c) SELECT JOB, COUNT(*) FROM EMP GROUP BY JOB WHERE
COUNT(*)<3;
(d) SELECT JOB,COUNT(*)FROM EMP GROUP BY JOB HAVING COUNT(*)
<3;
Q18.Which join is used for display all possible concatenations are formed of all
rows of two or more tables.
Q19. How many rows are returned when we execute ‘SELECT*FROM EMP,DEPT’;
(a) 14
(b) 4
(c) 18
(d) 56
Q20.To display the name of employee & department name the MySQL statement
used:
(a) SELECT ENAME, DNAME FROM EMP,DEPT;
(b) SELECT ENAME, DNAME FROM EMP,DEPT
WHERE DEPTNO=DEPTNO;
(c) SELECT ENAME, DNAME FROM EMP,DEPT
WHERE EMP.DEPTNO=DEPT.DEPTNO;
(d) None of the above
179
Q22. The join in which only one identical column exists is called………
180
Answers
Q.No. Answers
1 A
2 C
3 C
4 A
5 C
6 C
7 D
8 D
9 B
10 C
11 B
12 B
13 D
14 A
15 B
16 D
17 B
18 A
19 D
20 A
21 B
22 B
23 A
24 A
25 a
INTERFACE PYTHON WITH MYSQL
Basically the process of transfer data between python programs and MySQL database is known as Python
Database Connectivity.
There few steps you have to follow to perform Python Database Connectivity. These steps are as follow:
1. Import the required packages
2. Establish a connection
3. Execute SQL command
4. Process as per the requirements
To perform the Python MySQL Database Connectivity you need to install mysql-connector-python package
using pip command.
pip install mysql connector python
After installation just write the import statement to import the package in python code.
import mysql.connector as msql
Establish a connection
To establish a connection you need to create a connection object in Python. Take a variable as a connection
object and use connect() function with MySQL database specification like host name, username,
passoword or passwd and database itself. For example cn. Observe the code:
Please ensure that you have provided appropriate username, password and database name available in your
MySQL interface.
After doing this, check for the errors if any. If your program runs without errors that means connection is
established. Although you can use is_connected() function to check whether the connection is established
or not! Observe this code:
182 | P a g e
cn=msql.connect(host='localhost',user='root',passwd='root',database='Student')
if cn.is_connected():
print("Connection Established")
else:
print("Connection Errors! Kindly check!!!")
The next step after the successful connection is to write SQL command and fetch rows. The SQL
commands are used to perform DML operations and fetch rows read data from table. So we will see them in
detail later.
You have to create a cursor object for executing SQL command and fetch rows. Cursor object is a special
kind of structure that processes the data row by row in database. You can create cursor object in the
following manner.
cur=cn.cursor()
To perform the DML operations like insert, update or delete follow these steps:
1. Create a cursor object
2. Write command as parameters for execute() function
3. Use commit() function to save the changes and reflect the data in the table.
insert command
update command
delete command
Select Command
As you know the select command is used retrieve records from the database. The result is available in the
resultset or dataset. You can store the select the command in cursor object in python. Then for resultset you
can use the fetch…() function. These are:
1. fetchall(): It will retrieve all data from a database table in form of record or tuple or a row.
2. fetchone(): It will retrieve one record from the resultset as a tuple or a list. It returns the records in a
specific order like first record, the next time next record and so on. If records are not available then
it will return None.
3. fetchmany(n): It will retrieve a number of records from the database. If records are not available
then it will return an empty tuple.
4. rowcount: It is one of the properties of cursor object that return number of rows fetched from the
cursor object.
184 | P a g e
d=cur.fetchone()
print(d)
time.sleep(3)
d=cur.fetchone()
print(d)
time.sleep(3)
d=cur.fetchone()
time.sleep(3)
print(d)
Parameterized Queries
Sometimes we need to access values as per the user’s input. The query result is based on the values user has
passed. So for that we have this option parameterized queries. There are two ways to use parameterized
queries:
1. with % formatting pattern
2. with {}.format pattern
This pattern takes the general form – f % v, where f is a format and v is the value. Consider the following
code:
import mysql.connector as msql
import time
cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb')
cur=cn.cursor()
185 | P a g e
cur=cn.cursor()
cur.execute("select * from students where marks >{}" .format(80))
d=cur.fetchall()
for r in d:
print(r)
cur.execute("select * from students where grade='{}'".format('B1'))
d=cur.fetchall()
for r in d:
print(r)
Finally, you have to close the established connect using close() function. It will help to clean up the
memory. Observe the following code:
con.close()
WORKSHEETS
1. A database _________ controls the connection to an actual database, established from within a
Python program.
(a) database object (b) connection object (c) fetch object (d) query object
186 | P a g e
Ans. (b)
2. The set of records retrieved after executing an SQL query over an established database connection is
called ___________ .
(a) table (b) sqlresult (c) result (d) resultset
Ans. (d)
3. A database _________ is a special control structure that facilitates the row by row processing of
records in the resultset.
(a) fetch (b) table (c) cursor (d) query
Ans. (c )
4. To obtain all the records retrieved, you may use the <cursor>. _______ method.
(a) fetchmany( ) (b) fetchall( ) (c) fetchone( ) (d) fetchmultiple( )
Ans. (b)
5. To reflect the changes made in the database permanently, you need to run <connection>. _______
method.
(a) done (b) reflect (c) commit (d) final
Ans. (c)
6. To run an SQL query within Python, you may use the <cursor>. _______ method.
(a) query (b) execute (c) run (d) None of the above
Ans. 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. What is a resultset?
Ans. A result set refers to a logical set of records that are fetched from the database by executing a
187 | P a g e
query and made available to the application program.
Ans. 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.
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
*************
189 | P a g e