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

Unit-III DMBS

The document discusses database concepts including the relational data model, structured query language, and database management systems. It defines key concepts like relations, attributes, tuples, keys, SQL, and database interfaces with Python. The summary of a database is provided as a collection of related data that describes organizational activities. Relational databases store information in tables with rows and columns, and keys help uniquely identify rows. SQL commands like SELECT, INSERT, and UPDATE are used to manipulate data.

Uploaded by

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

Unit-III DMBS

The document discusses database concepts including the relational data model, structured query language, and database management systems. It defines key concepts like relations, attributes, tuples, keys, SQL, and database interfaces with Python. The summary of a database is provided as a collection of related data that describes organizational activities. Relational databases store information in tables with rows and columns, and keys help uniquely identify rows. SQL commands like SELECT, INSERT, and UPDATE are used to manipulate data.

Uploaded by

Bikash Ray
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

UNIT-3

Database Management – 1

Database concepts: Introduction to database concepts and its need


 Relational data model: relation, attribute, tuple, domain, degree, cardinality, keys
(candidate key, primary key, alternate key, foreign key)
 Structured Query Language: introduction, Data Definition Language and Data
Manipulation Language, data type (char(n), varchar(n), int, float, date), constraints (not
null, unique, primary key), create database, use database, show databases, drop database,
show tables, create table, describe table, alter table (add and remove an attribute, add and
remove primary key), drop table, insert, delete, select, operators (mathematical, relational
and logical), aliasing, distinct clause, where clause, in, between, order by, meaning of null,
is null, is not null, like, update command, delete command.
 Aggregate functions (max, min, avg, sum, count), group by, having clause, joins : Cartesian
product on two tables, equi-join and natural join
 Interface of python with an SQL database: connecting SQL with Python, performing insert,
update, delete queries using cursor, display data by using fetchone(), fetchall(), rowcount,
creating database connectivity applications
Data: raw representation of unprocessed facts, figures, concepts or instruction. It can exist in any
form, usable or not. Data are facts presented without relation to other things. E.g. It is raining.

Information: information is data that has been given meaning by way of relational connection.
This "meaning" can be useful, but does not have to be. In computer parlance, a relational database
makes information from the data stored within it. Information embodies the understanding of some
sort. E.g. the temperature dropped to 15 degrees and then it started raining.

DATABASE: A database is a collection of data, typically describing the activities of one or more
related organizations. For example, a university database might contain information about the
following:
 Entities such as students, faculty, courses, and classrooms.
 Relationships between entities, such as students' enrollment in courses, faculty teaching
courses, and the use of rooms for courses.
Proper storage of data in a database will enhance efficient
 Data Management
 Data processing
 Data retrieval

Database System: It refers to an organization of components that define and regulate the
collection, storage, management from general management point of view, the DB system is
composed of-
 Hardware
 Software
 People – system administrators: database systems operations
o DB administrators: manage the DBMS and ensure the DB is functioning properly
o DB designers
o System analysts and programmers design and implement the application programs
o end user
 Procedures
 Data
DBMS: A database management system (DBMS) is a collection of programs that manages the
database structure and controls access to the data stored in the database. In a sense, a database
resembles a very well-organized electronic filing cabinet in which powerful software (the DBMS)
helps manage the cabinet’s contents.

ADVANTAGES OF A DBMS
Data independence: This is the technique that allow data to be changed without affecting the
applications that process it.
Efficient data access: A DBMS deploys sophisticated techniques to store and retrieve data
efficiently.
Data integrity control: The DBMS can enforce integrity constraints on the data. For example,
before inserting salary information for an employee, the DBMS can check that the department
budget is not exceeded.
Security Control: The DBMS can enforce access controls that govern what data is visible to
different classes of users. Users are only allowed to perform an operation he or she is allowed to
carry out on data.
Concurrent access and crash recovery: A DBMS schedules concurrent accesses to the data in
such a manner that users can think of the data as being accessed by only one user at a time. Further,
the DBMS protects users from the effects of system failures.
Reduced application development time: Clearly, the DBMS supports many important functions
that are common to many applications accessing data stored in the DBMS. This, in conjunction
with the high-level interface to the data, facilitates quick development of applications. Such
applications are also likely to be more robust than applications developed from scratch because
many important tasks are handled by the DBMS instead of being implemented by the application.

DBMS APPLICATIONS
 Banking: all transactions
 Airlines: reservations, schedules Universities: registration, grades
 Sales: customers, products, purchases Online retailers: order tracking, customized
recommendations
 Manufacturing: production, inventory, orders, supply chain
 Human Resources: employee records, salaries, tax deductions

RELATIONAL DATABASE
• The Relational Database is a collection of related relations/tables to represent both data and the
relationships among those data.
• Each table has multiple columns and rows.
• Each column has a unique name.
• Table is called as a Relation
• Column is called as an Attribute or Domain
• Row is called as a Tuple or Record

DBMS Vs RDBMS
DBMS RDBMS
It stores data as a file It stores data in the form of tables.
It supports single users It supports multiple users.
It does not support client-server architecture It supports client-server architecture.
It has low software and hardware requirements It has higher hardware and software
requirements.
In DBMS, data redundancy is common In RDBMS, keys and indexes do not allow
data redundancy.

DEGREE OF A TABLE
 The number of columns/fields is called as ‘degree’ of a Table.
 This is also called as ‘arity’.

CARDINALITY OF A TABLE
 The cardinality of a Table instance is the number of tuples/rows in it.

Example:
 Degree of the relation is 5
 Cardinality of the relation is 4.

KEYS IN A TABLE
 A DBMS key is a Column or set of Columns which helps you to identify a row(tuple) in
a relation(table).
 They also allow you to find the relation between two tables.
 Keys help you uniquely identify a row in a table by a combination of one or more
columns in that table.

CANDIDATE KEY
 A set of fields that uniquely identifies a tuple according to a key constraint is called as a
‘Candidate Key’ for the relation.
 This is also called as a ‘key’
 A relation may have more than key.
 Every relation must have a key.

PRIMARY KEY
 A column or group of columns in a table which helps us to uniquely identify every row in
that table is called a primary key.
 Rules for defining Primary key
o Unique Values: Two rows can't have the same Primary key field
o Not NULL: The primary key field cannot be NULL.
FOREIGN KEY
 A foreign key is a column which is added to create a relationship with another table.
 Foreign keys help us to maintain data integrity and also allows navigation between two
different instances of an entity.

STRUCTURED QUERY LANGUAGE (SQL)


 Data inside a database table can be manipulated using SQL commands/queries.
 SQL Commands for handling data inside database can be of 2 types:
o DDL – Data Definition Language
o DML- Data Manipulation Language

DBMS LANGUAGES
The workings of a DBMS is controlled by four different languages, they are:
 Data Definition Language (DDL): Used by the DBA and database designers to specify
the conceptual schema of a database. In many DBMSs, the DDL is also used to define
internal and external schemas (views). In some DBMSs, separate storage definition
language (SDL) and view definition language (VDL) are used to define internal and
external schemas. SDL is typically realized via DBMS commands provided to the DBA
and database designers. Some examples include:
o CREATE - to create objects in the database
o ALTER - alters the structure of the database
o DROP - delete objects from the database
o TRUNCATE - remove all records from a table, including all spaces allocated for
the records are removed
o COMMENT - add comments to the data dictionary
o RENAME - rename an object
 Data Manipulation Language (DML): These statements manage data within schema
objects. They specify database retrievals and updates. DML commands can be embedded
in a general-purpose programming language (host language), such as COBOL, C, C++, or
Java.
o A library of functions can also be provided to access the DBMS from a
programming language
o Alternatively, stand-alone DML commands can be applied directly (called a query
language). Some examples in SQL include:
 SELECT - Retrieve data from the a database
 INSERT - Insert data into a table
 UPDATE - Updates existing data within a table
 DELETE - deletes all records from a table, the space for the records remain
 MERGE - UPSERT operation (insert or update)
 CALL - Call a PL/SQL or Java subprogram
 EXPLAIN PLAN - explain access path to data
 LOCK TABLE - control concurrency

 Data Control Language (DCL): used for granting and revoking user access on a database
o To grant access to user – GRANT
o To revoke access from user – REVOKE
 Transaction Control (TCL): Statements are used to manage the changes made by DML
statements. It allows statements to be grouped together into logical transactions. Some
examples include:
o COMMIT - save work done
o SAVEPOINT - identify a point in a transaction to which you can later roll back
o ROLLBACK - restore database to original since the last COMMIT
o SET TRANSACTION - Change transaction options like isolation level and what
rollback segment to use in practical data definition language, data manipulation
language and data control languages are not separate language; rather they are the
parts of a single database language such as SQL.

SQL QUERY:
1. Create: It is a DDL SQL command used to create a table or a database in relational
database management system.
To create a database named “test_db” -
CREATE DATABASE test_db;

To create a table named “Student” -


CREATE TABLE Student( student_id INT, name VARCHAR(100), age INT );

2. DROP: It is a DDL Command that completely removes a table or a database. This


command will also destroy the table structure and the data stored in it.
E.g.:
DROP DATABASE test_db;
DROP TABLE Student;

3. INSERT: It is a DML command used to insert rows/ records into a table. One INSERT
Query can insert only one row in a table.
E.g.:
INSERT INTO Student VALUES(101, 'Adam', 15);

4. UPDATE: It is a DML Command used to update any row/record of data in a table.


E.g.:
UPDATE student SET age=18 WHERE student_id=102;
5. DELETE: It is a DML command used to delete rows from a table.
E.g.:
To delete all rows from Student table:
DELETE FROM student;

To delete only selected rows use WHERE clause:


DELETE FROM student WHERE s_id=103;

6. SELECT: It is a DML Command used to retrieve/fetch/view any row or column in a


table.
E.g.:
SELECT age FROM Student;  to view age column
SELECT s_id FROM Student;  to view Student ID column

The WHERE CLAUSE


 WHERE clause is used to filter records/rows at the time of SELECT, UPDATE or
DELETE Query.
 WHERE clause can be used to apply various comma separated condition in a table.
 We can specify multiple conditions using AND or OR operators.
E.g.:
SELECT s_id FROM Student WHERE age>15;
-- This query will retrieve id of students who have age greater than 15

The ORDER BY Clause


 ORDER BY clause in SELECT Query allows you to sort the records in the result set of
rows.
 The ORDER BY keyword sort the records in ascending order by default.
 If you want to sort the records in descending order, you can use the DESC keyword.
 It is also possible to order by more than one column.
E.g.:
SELECT * FROM Student ORDER BY age
-- All columns of Student table are retrieved with rows having minimum age as first row

The GROUP BY Clause


The GROUP BY clause combines all those records that have identical values in a particular field
or a group of fields.
We can group by a column name or with aggregate functions in which case the aggregate
produces a value for each group.
E.g.: SELECT City FROM CUSTOMERS GROUP BY City;

The HAVING Clause HAVING clause was added to SQL, because the WHERE keyword
could not be used with aggregate function.
E.g.:
SELECT * FROM CUSTOMERS GROUP BY City
HAVING BALANCE>10000;
The HAVING clause can contain either a simple boolean expression (i.e. a condition which
results into true or false) or use aggregate function in the having condition.
SQL AGGREGATE FUNCTIONS
 An aggregate function performs a calculation on a set of values, and returns a single
value.
 Except for COUNT , aggregate functions ignore null values.
 Aggregate functions are often used with the GROUP BY clause of the SELECT
statement.
 Commonly used Aggregate Functions are:
o AVG() – calculates the average of a set of values.
o COUNT () – counts rows in a specified table.
o MIN () – gets the minimum value in a set of values.
o MAX () – gets the maximum value in a set of values.
o SUM () – calculates the sum of values.

INTERFACE OF PYTHON WITH SQL


Introduction to Database Programming in Python
Interacting with a database is an important feature in many programming languages including
python. In comparison to storing data in flat files, it’s much easier to store, retrieve and modify
data in a database. We are going to learn the following concepts and programming skills.
 Creating a Database connection
 Creating a Database
 Create a Table
 Inserting into the table
 Retrieving data from Table
 Updating Records in a table
 Deleting Data in a table

Connecting to the database server


import mysql.connector
con = mysql.connector.connect(host="localhost", user="root", passwd="")
mycursor = con.cursor()
con.close()

Creating a Database
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root", passwd="")
mycursor = con.cursor()
mycursor.execute("DROP DATABASE IF EXISTS student")
mycursor.execute("CREATE DATABASE student")
mycursor.execute("USE student")
Creating the Table
mycursor.execute("DROP TABLE IF EXISTS studentinfo")
mycursor.execute("CREATE TABLE studentinfo (name VARCHAR(30), age INT(3), gender
CHAR(1))")

Inserting data into the table


sql = "INSERT INTO studentinfo(name, age, gender) VALUES('Ashok',17,'M')"
mycursor.execute(sql)
con.commit()

Inserting multiple rows simultaniously


Here we are going to use the executemany() function that accept two parameters as shpown below.
sql = "INSERT INTO studentinfo(name, age, gender) VALUES(%s, %s, %s)"
rows = [('Amit', 18,'M'),('Sudha', 17, 'F')]
mycursor.executemany(sql, rows)
con.commit()
con.close()

Reading from Database Table


 fetchone() − It fetches the next row of a query result set. A result set is an object that is
returned when a cursor object is used to query a table.
 fetchall() − It fetches all the rows in a result set. If some rows have already been extracted
from the result set, then it retrieves the remaining rows from the result set.
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root", passwd="", database="student")
mycursor = con.cursor()
sql = "SELECT * FROM studentinfo"
mycursor.execute(sql)
result = mycursor.fetchall()
for row in result:
name = row[0]
age = row[1]
gender = row[2]
print("Name=%s, Age=%d, Gender=%c" % (name,age,gender))
con.close()

Updating records in a Table


import mysql.connector
con = mysql.connector.connect(host="localhost", user="root", passwd="", database="student")
mycursor = con.cursor()
sql = "UPDATE studentinfo SET age=age-3 WHERE age='%d'" % (21)
mycursor.execute(sql)
sql = "SELECT * FROM studentinfo"
mycursor.execute(sql)
result = mycursor.fetchall()
for row in result:
name = row[0]
age = row[1]
gender = row[2]
print("Name=%s, Age=%d, Gender=%c" % (name,age,gender))
con.close()

Deleting Records from a Table


import mysql.connector
con = mysql.connector.connect(host="localhost", user="root", passwd="", database="student")
mycursor = con.cursor()
sql = "DELETE FROM studentinfo WHERE name='%s'" % ('Ashok')
mycursor.execute(sql)
sql = "SELECT * FROM studentinfo"
mycursor.execute(sql)
result = mycursor.fetchall()
for row in result:
name = row[0]
age = row[1]
gender = row[2]
print("Name=%s, Age=%d, Gender=%c" % (name,age,gender))
con.close()

fetchmany([size=cursor.arraysize])
Fetch the next set of rows of a query result, returning a list of tuples. An empty list is returned
when no more rows are available.
The number of rows to fetch per call is specified by the parameter. If it is not given, the cursor’s
arraysize determines the number of rows to be fetched. The method should try to fetch as many
rows as indicated by the size parameter. If this is not possible due to the specified number of rows
not being available, fewer rows may be returned:
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root", passwd="", database="student")
mycursor = con.cursor()
mycursor.execute("SELECT * FROM students;")
print(mycursor.fetchmany(3))
Differences between Char & Varchar

Char Varchar

It is an abbreviation for characters. It is an abbreviation for variable characters.

Char datatype is used to store character Varchar datatype is used to store character
strings of fixed length. strings of variable length.

It uses static memory location. It uses dynamic memory location.

Varchar take 1 byte for each character along


Char takes 1 byte space for each character. with some extra bytes to store length
information.

We can use char datatype when we know the We can use it when we are not sure of the
length of the string. length of the string.

Char datatype can be used when we expect Varchar datatype can be used when we expect
the data values in a column to be of same the data values in a column to be of variable
length. length.

You might also like