2. INTRODUCTION TO DATABASE SYSTEMS
• The word data is taken from "Datum", means raw facts. Datum is a
single piece of factual
• information of interest to us. Data, the plural of datum, is a collection
of information. Data is the name given to basic raw facts and entities
such as names, numbers and quantity. Data can be defined as a
collection of facts and records.
3. FILE SYSTEM
Now you must have noticed that maintaining such type of records manually
does not allow to correct, modify or delete the data in the register. Also
searching the details of the student is difficult. To overcome the hassles
faced in manual record keeping, this data can be stored in computer. The
student details are stored in computer in the form of separate file.
4. Limitations of a File System
• Difficulty in Access
• Data Redundancy
• Data Inconsistency
• Data Isolation
• Data Dependence
• Controlled Data Sharing
5. DATABASE MANAGEMENT SYSTEM
• Limitations faced in file system can be overcome by storing the data in
a database where data are logically related. A database management
systems (DBMSs) is used as an interface to manage databases.
• A database is an organized collection of data, generally stored and
accessed electronically from a computer system. It supports the
storage and manipulation of data. In other words, databases are used
by an organization as a method of storing, managing and retrieving
information.
6. Popular DBMS
DBMS Primary Database Model License
Oracle RDBMS Commercial (restricted free
version is available)
MySQL RDBMS Open Source
Microsoft SQL Server RDBMS Commercial (restricted free
version is available)
PostgreSQL RDBMS Open Source
MangoDB Document store Open Source
7. Application of the DBMS system
• Student Admission System, School Examination System, Library Management
System
• Payroll, HR, Sales & Personnel Management System
• Accounting System, Hotel Reservation System and Airline Reservation System
• It is used in the Banking system for Customer information, account activities,
Payments, deposits, loans etc.
• Insurance management system
• DBMS system also used by universities to keep all records
• Finance for storing information about stock, sales, and purchases of financial
instruments like stocks and bonds.
8. Advantages of DBMS system
• DBMS offers a variety of techniques to store & retrieve data.
• Uniform administration procedures for data storage and retrieval.
• Application programmers never exposed to details of data representation and
Storage.
• A DBMS uses various powerful functions to store and retrieve data efficiently.
• Offers Data independence , Data Integrity and Data Security and reduce data
• redundancy.
• The DBMS implies integrity constraints to get a high level of protection
against prohibited access to data.
• Reduced Application Development Time and occupy lesser space.
9. Disadvantages of the DBMS system
• Cost of Hardware and Software of a DBMS is quite high, which increases the budget
of your organization.
• Most database management systems are often complex systems, so the training for
users to use the DBMS is required.
• The use of the same program at a time by many users sometimes lead to the loss of
some data.
• DBMS can't perform sophisticated calculations
• Data-sets begins to grow large as it provides a more predictable query response time.
• It required a processor with the high speed of data processing.
• The database can fail because or power failure or the whole system stops.
• The cost of DBMS is depended on the environment, function, or recurrent annual
maintenance cost.
10. Key Concepts in DBMS
• Database schema - It consists of table with all attributes with their data types and
constraints if any.
• Data Constraint - Sometimes it is required to put certain restrictions or limitations on
the type of data to be inserted in the columns of a table.
• Meta-data or Data Dictionary - A meta-data is data about the data.
• Database Instance - When we define database structure or schema, state of
database is empty.
• Query - A query is a request to a database for obtaining information in a desired
way. Query can be made to get data from one table or from a combination of tables.
• Data Manipulation - Modification of database consists of three operations viz.
Insertion, Deletion or Updation.
• Database Engine - Database engine is the underlying component or set of programs
used by a DBMS to create database and handle various queries for data retrieval and
manipulation.
11. RELATIONAL DATA MODEL
A data model describes the structure of the database and represent
data. It defines and represents relationships among relations. In database
design, first the conceptual data model is designed for non-technical
users.
12. KEYS IN A RELATIONAL DATABASE
The tuples within a relation must be distinct. It means no two tuples in
a table should have same value for all attributes. That is, there should
be at least one attribute in which data are distinct (unique) and not
NULL.
• Candidate Key
A relation can have one or more attributes that takes distinct values.
Any of these attributes can be used to uniquely identify the tuples in
the relation. Such attributes are called candidate key.
13. KEYS IN A RELATIONAL DATABASE
• Primary Key
Out of one or more candidate keys, the attribute chosen by the database
designer to uniquely identify the tuples in a relation is called the primary
key of that relation.
• Composite Primary Key
If no single attribute in a relation is able to uniquely distinguish the tuples,
then more than one attributes are taken together as primary key. Such
primary key consisting of more than one attribute is called Composite
Primary key.
• Foreign Key
A foreign key is used to represent the relationship between two relations. A
foreign key is an attribute whose value is derived from the primary key of
another relation.
15. Structured Query Language (SQL)
In file system it is required to write programs to access data.
However in DBMS there exists a Structured Query Language (SQL), is a
special kind of query language used to access and manipulate data
from the database. SQL is the most popular query language used by
major relational database management systems (RDBMS), such as
MySQL, Oracle, Informix, PostGre SQL, SQL server, MS Access, and
Sybase.
16. Installing MySQL
MySQL is an open source RDBMS software which can be easily
downloaded from its official website ttps://dev.mysql.com/downloads.
After installing MySQL, start MySQL service. The appearance of mysql>
prompt as shown below. MySQL is ready to accept SQL statements on
this prompt.
17. Following are some important points to be kept in mind while using
SQL.
• SQL is not case sensitive. For example, the column names ‘salary’ and
‘SALARY’ are the same for SQL.
• SQL statements terminates with a semicolon (;). In multi-line SQL
statements, the “;” is not required after the first line. Just press the Enter
key to continue on the next line. The prompt mysql> then changes to “->”,
indicating that statement is continued to the next line. Only at the end of
SQL statement, put “;” and press Enter.
18. Data Types MySQL
• CHAR (n) - Specifies character type data of length n where n could be
any value from 0 to 255.
• VARCHAR (n) - Specifies character type data of length ‘n’ where n could
be any value from 0 to 65535. But unlike CHAR, VARCHAR is a variable-
length data type.
• INT - INT specifies an integer value. Each INT value occupies 4 bytes of
storage. The range of values allowed in integer type are -2147483648
to 2147483647.
• FLOAT - Holds numbers with decimal points. Each FLOAT value occupies
4 bytes.
• DATE - The DATE type is used for dates in 'YYYY-MM-DD' format. YYYY is
the 4 digits year, MM is the 2 digits month and DD is the 2 digits date.
19. Constraints MySQL
Constraint Description
NOT NULL Ensures that a column cannot have NULL values where NULL means missing/
unknown/not applicable value.
UNIQUE Ensures that all the values in a column are distinct/unique.
DEFAULT A default value specified for the column if no value is provided.
PRIMARY KEY The column which can uniquely identify each row or record in a table.
FOREIGN
KEY
The column which refers to value of an attribute defined as primary key in
another table.
20. Types of Structured Query Language (SQL)
• Data Definition Language (DDL)
• Data Manipulation Language (DML)
• Data Query Language (DQL)
• Transaction Control Language (TCL)
• Data Control Language (DCL)
21. SQL – Data Definition Language (DDL)
1. CREATE Database –
Syntax:
CREATE DATABASE databasename;
Eg. mysql> CREATE DATABASE SchoolRecord;
23. SQL – Data Definition Language (DDL)
2. CREATE Table
24. SQL – Data Definition Language (DDL)
3. DESCRIBE Table
Syntax:
DESCRIBE tablename;
25. SQL – Data Definition Language (DDL)
4. ALTER Table –
Syntax:
ALTER TABLE tablename ADD/Modify/DROP attribute1, attribute2,..
(a) Add primary key to a relation
26. SQL – Data Definition Language (DDL)
4. ALTER Table –
(b) Add foreign key to a relation
Syntax:
ALTER TABLE table_name ADD FOREIGN KEY (attribute name)
REFERENCES referenced_table_name (attribute name);
27. SQL – Data Definition Language (DDL)
4. ALTER Table –
c. Add constraint unique to an existing attribute
28. SQL – Data Definition Language (DDL)
d) Add an attribute to an existing table
Syntax:
ALTER TABLE table_name ADD attribute_name DATATYPE;
29. SQL – Data Definition Language (DDL)
e) Modify datatype of an attribute
Syntax:
ALTER TABLE table_name MODIFY attribute
DATATYPE;
f) Modify constraint of an attribute
30. SQL – Data Definition Language (DDL)
g) Add default value to an attribute
Syntax:
ALTER TABLE table_name MODIFY attribute
h) Remove an attribute
31. SQL – Data Definition Language (DDL)
i) Remove primary key from the table
32. SQL – Data Definition Language (DDL)
5. DROP TABLE Command
Syntax :
DROP TABLE table_name;
It is also possible to drop the entire database.
Syntax :
DROP DATABASE database_name;
33. SQL – Data Definition Language (DDL)
6. TRUNCATE TABLE Command
It is possible to remove all records form a table using TRUNCATE
command.
Syntax:
Truncate Table Table_Name;
34. SQL – Data Definition Language (DDL)
8. RENAME TABLE command –
Syntax:
RENAME TABLE old_table_name TO new_table_name;
eg.
mysql> RENAME TABLE NewStudentRecord TO StudentRecord1;
9. CREATE VIEW command
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2 ..... columnN
FROM table_name WHERE condition;
35. SQL – Data Definition Language (DDL)
9. CREATE VIEW command
36. SQL - DATA MANIPULATION LANGUAGE (DML)
1 INSERTION of Records –
Syntax:
INSERT INTO tablename VALUES (value 1, value 2,....);
37. 2 UPDATION of Records using UPDATE and DELETE Command
Syntax:
UPDATE table_name
SET attribute1 = value1, attribute2 = value2, …
WHERE condition;
SQL - DATA MANIPULATION LANGUAGE (DML)
38. 3 DELETION of Records using DELETE
Syntax:
DELETE FROM table_name WHERE condition;
SQL - DATA MANIPULATION LANGUAGE (DML)
39. SQL FOR DATA QUERY LANGUAGE (DQL)
The data stored in a database can be retrieved using a mechanism called as
Query. SQL provides efficient mechanisms to retrieve data stored in multiple tables
in MySQL database.
1 SELECT Statement –
Syntax:
SELECT attribute1, attribute2,... attribute N
FROM table_name
WHERE condition;
40. SQL FOR DATA QUERY LANGUAGE (DQL)
a) Retrieve selected columns
41. SQL FOR DATA QUERY LANGUAGE (DQL)
b) Renaming of columns
42. SQL FOR DATA QUERY LANGUAGE (DQL)
c) Distinct Clause
43. SQL FOR DATA QUERY LANGUAGE (DQL)
c) Distinct Clause
44. SQL FOR DATA QUERY LANGUAGE (DQL)
d) WHERE Clause
45. SQL FOR DATA QUERY LANGUAGE (DQL)
d) WHERE Clause
46. SQL FOR DATA QUERY LANGUAGE (DQL)
e) Membership operator IN
47. SQL FOR DATA QUERY LANGUAGE (DQL)
f) ORDER BY Clause
48. SQL FOR DATA QUERY LANGUAGE (DQL)
g) Handling NULL Values
49. SQL FOR DATA QUERY LANGUAGE (DQL)
h) Having clause
Syntax:
SELECT expression1, expression2, ... expression_n,
aggregate_function (expression)
FROM tables
[WHERE conditions]
GROUP BY expression1, expression2, ... expression_n
HAVING condition;
50. SQL FOR DATA QUERY LANGUAGE (DQL)
h) Having clause
Syntax:
SELECT expression1, expression2, ... expression_n,
aggregate_function (expression)
FROM tables
[WHERE conditions]
GROUP BY expression1, expression2, ... expression_n
HAVING condition;
51. SQL FOR DATA QUERY LANGUAGE (DQL)
i) Substring pattern matching
52. SQL FOR DATA CONTROL LANGUAGE (DCL)
Data Control Language is the part of SQL, which have commands to manage
users for their work permission. The user will be able to work as per the permissions
granted to them by DBA(Database Administrator).
GRANT statement –
The GRANT statement is used to give access privileges to a specific user to
work with any selected database only.
Syntax:
GRANT SELECT, UPDATE ON Test_Table TO NewUser1, NewUser2;
Example:
GRANT SELECT, UPDATE, DELETE ON carshowroom TO 'WebUser';
53. SQL FOR DATA CONTROL LANGUAGE (DCL)
REVOKE statement –
The REVOKE statement is used to withdraw privileges from a
specific user so that specific user could not use specific statement on
selected database. In other words it is useful to take back the given
permission/s from the user.
Syntax:
REVOKE Privilege_Name ON Object_Name FROM
User_Name.
Example:
REVOKE DELETE ON carshowroom FROM WebUser;
54. SQL FOR TRANSACTION CONTROL LANGUAGE (TCL)
Transaction control language (TCL) is the part of SQL commands that
allows to permanently change the databases or undo the databases transactions.
It is similar to save the database or undo the current changes. The COMMIT,
ROLLBACK and SAVEPOINT statements comes under this category.
1. COMMIT –
Commit command is used to save all the transactions to the database.
Syntax:
Commit;
Example:
DELETE FROM ClassStudents WHERE RollNo =25;
Commit;
55. SQL FOR TRANSACTION CONTROL LANGUAGE (TCL)
2. ROLLBACK –
ROLLBACK command allows to undo transactions that have not
already been saved to the database.
Syntax:
ROLLBACK;
56. Functions In SQL
There are various readily available functions in SQL that can be
used in queries. It includes single row functions, multiple row functions,
group records based on some criteria, and working on multiple tables
using SQL.
Single Row Functions
a. Math Functions –
1. POWER (X, Y) or POW (X, Y) – calculates X to the power Y.
2. ROUND (N, D) – Rounds off number N to D number of decimal
places. If D=0, then it rounds off the number to the nearest integer.
3. MOD (A, B) – Returns the remainder after dividing number A by
number B.
58. Functions In SQL
Single Row Functions
b. String Functions –
1. UCASE (string) OR UPPER (string) – converts string into uppercase.
59. Functions In SQL
Single Row Functions
b. String Functions –
2. LCASE (string) OR LOWER (string) – converts string into lowercase.
60. Functions In SQL
Single Row Functions
b. String Functions –
3. MID (string, pos, n) OR SUBSTRING (string, pos, n) OR SUBSTR (string,
pos, n) – Returns a substring of size n starting from the specified
position (pos) of the string.
61. Functions In SQL
Single Row Functions
b. String Functions –
4. LENGTH (string) – Return the number of characters in the specified
string.
62. Functions In SQL
Single Row Functions
b. String Functions –
5. LEFT (string, N) – Returns N number of characters from the left side
of the string.
6. RIGHT (string, N) – Returns N number of characters from the right
side of the string.
63. Functions In SQL
Single Row Functions
b. String Functions –
7. INSTR (string, substring) – Returns the position of the first occurrence
of the substring in the given string. Returns 0, if the substring is not
present in the string.
8. LTRIM (string) – Returns the given string after removing leading white
space characters.
64. Functions In SQL
Single Row Functions
b. String Functions –
9. RTRIM (string) – Returns the given string after removing trailing
white space characters.
10. TRIM (string) – Returns the given string after removing both leading
and trailing white space characters.
65. Functions In SQL
Single Row Functions
c. Date and Time Functions
1. NOW() – It returns the current system date and time.
2. DATE() – It returns the date part from the given date/time expression.
66. Functions In SQL
Single Row Functions
c. Date and Time Functions
3. MONTH(date) – It returns the month in numeric form from the date.
4. MONTHNAME(date) – It returns the month name from the specified date.
67. Functions In SQL
Single Row Functions
c. Date and Time Functions
5. YEAR(date) – It returns the year from the date.
6. DAY(date) – It returns the day part from the date.
68. Functions In SQL
Single Row Functions
c. Date and Time Functions
7. DAYNAME(date) – It returns the name of the day from the date.
69. Functions In SQL
Single Row Functions
d. Aggregate Functions
1. MAX (column) – Returns the largest value from the specified column.
2. MIN (column) – Returns the smallest value from the specified column.
70. Functions In SQL
Single Row Functions
d. Aggregate Functions
3. AVG (column) – Returns the average of the values in the specified column.
4. SUM (column) – Returns the sum of the values for the specified column.
71. Functions In SQL
Single Row Functions
d. Aggregate Functions
5. COUNT (*) – Returns number of records in a table. COUNT (*) is used with
WHERE clause to display the number of records that matches a particular
criteria in the table.
72. GROUP BY CLAUSE IN SQL
Sometimes it may require to fetch a group of rows on the basis of common values in a
column. GROUP BY clause is a special clause in SQL to do this. It groups the rows together that
contains the same values in a specified column. The aggregate functions (COUNT, MAX, MIN,
AVG and SUM) can be used with GROUP BY clause. HAVING Clause in SQL is used to specify
conditions on the rows with GROUP BY clause.
74. OPERATIONS ON RELATIONS
2 Intersect ( )
3 Minus (-)
This operation is used to get tuples/rows which are in the first
table but not in the second table.
4 Cartesian Product (×)
77. Python & MySQL Database Connectivity
Creating database connectivity application
Following are the steps to be followed for creating database connectivity in Python.
Step 1. Start Python.
Step 2. Install mysql-connector online with “pip install mysql-connector-python”.
Step 3. Import the package required for database programming (import mysql.connector).
Step 4. Open a connection to database (connect () is used for this purpose, it required following
parameters host, user, passwd, databasename).
Step 5. Create cursor (for this purpose used cursor ()) When you connect to a database from with
python program, then the query gets sent to the server, where it gets executed, and the resultset
is sent over the connection to you, in one burst of activity in one go. But you may want to access
the retrieved data, one row at a time. Cursor is used for handle the resultset.
Example: mycur=mydb.cursor()
78. Python & MySQL Database Connectivity
Step 6. Execute a query using execute () function by passing a query as
a parameter. For example:
cursor.excute (“select * from student”).
Step 7. Extract data from resultset: once the result of query is available
in the form of a resultset
stored in a cursor object, you can extract data from the resultset using
any of the following fetch ()
Function.
Step 8. Clean up the environment this is the final step we need to close
the connection by using
mycon.close()
79. Python & MySQL Database Connectivity
Simple program for database connectivity.