Databases Management class 12 Notes Computer Science
Databases Management class 12 Notes Computer Science
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.
SQL (Structured Query Language)
SQL is a language that enables you to create and operate on relational databases, which are sets of related
information stored in tables.
DIFFERENT DATA MODELS
A data model refers to a set of concepts to describe the structure of a database, and certain constraints
(restrictions) that the database should obey. The four data model that are used for database management are :
1.Relational data model : In this data model, the data is organized into tables (i.e. rows and columns). These tables
are called relations.
2. Hierarchical data model 3. Network data model 4. Object Oriented data model
RELATIONAL MODEL TERMINOLOGY
1. Relation : A table storing logically related data is called a Relation.
2. Tuple : A row of a relation is generally referred to as a tuple.
3. Attribute : A column of a relation is generally referred to as an attribute.
4. Degree : This refers to the number of attributes in a relation.
5. Cardinality : This refers to the number of tuples in a relation.
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:
1. Data Definition Language(DDL) Commands
Commands that allow you to perform task, related to data definition e.g;
Creating, altering and dropping.
Granting and revoking privileges and roles.
Maintenance commands.
2. Data Manipulation Language(DML) Commands
Commands that allow you to perform data manipulation e.g., retrieval, insertion, deletion and modification of
data stored in a database.
3. Transaction Control Language(TCL) Commands
Commands that allow you to manage and control the transactions e.g.,
Making changes to database, permanent
Undoing changes to database, permanent
Creating savepoints
Setting properties for current transactions.
MySQL ELEMENTS
1. Literals 2. Datatypes 3. Nulls 4. Comments
LITERALS
It refer to a fixed data value. This fixed data value may be of character type or numeric type. For example,
‘replay’ , ‘Raj’, ‘8’ , ‘306’ are all character literals.
Numbers not enclosed in quotation marks are numeric literals. E.g. 22 , 18 , 1997 are all numeric literals.
Numeric literals can either be integer literals i.e., without any decimal or be real literals i.e. with a decimal point.
e.g. 17 is an integer literal but 17.0 and 17.5 are real literals.
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 Data Type
1. int – used for number without decimal.
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 Data Type
1. date – used to store date in YYYY-MM-DD format.
2. time – used to store time in HH:MM:SS format.
String Data Types
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.
DIFFERENCE BETWEEN CHAR AND VARCHAR DATA TYPE
NULL VALUE
If a column in a row has no value, then column is said to be null , or to contain a null. You should use a null value
when the actual value is not known or when a value would not be meaningful.
DATABASE COMMNADS
1. VIEW EXISTING DATABASE
To view existing database names, the command is : SHOW DATABASES ;
2. CREATING DATABASE IN MYSQL
For creating the database in MySQL, we write the following
command : CREATE DATABASE <databasename> ;
e.g. In order to create a database Student, command is :
CREATE DATABASE Student ;
3. ACCESSING DATABASE
For accessing already existing database , we write :
USE <databasename> ;
e.g. to access a database named Student , we write command as :
USE Student ;
4. DELETING DATABASE
For deleting any existing database , the command is :
DROP DATABASE <databasename> ;
e.g. to delete a database , say student, we write command
as ; DROP DATABASE Student ;
5. VIEWING TABLE IN DATABASE
In order to view tables present in currently accessed database , command is : SHOW TABLES ;
CREATING TABLES IN MYSQL
- Tables are created with the CREATE TABLE command. When a table is created, its columns are named, data
types and sizes are supplied for each column.
Syntax of CREATE TABLE command
is : CREATE TABLE <table-name>
( <column name> <data type> ,
<column name> <data type> ,
……… ) ;
E.g. in order to create table EMPLOYEE given below :
In order to insert another row in EMPLOYEE table , we write again INSERT command :
INSERT INTO employee
VALUES(1002 , ‘Akash’ , ‘M’ , ‘A1’ , 35000);
A particular column from a table can be selected by specifying column-names with SELECT command. E.g. in
above table, if we want to select ECODE and ENAME column, then command is :
SELECT ECODE , ENAME FROM EMPLOYEE ;
E.g.2 in order to select only ENAME, GRADE and GROSS column, the command is :
SELECT ENAME , GRADE , GROSS FROM EMPLOYEE ;
SELECTING PARTICULAR ROWS
We can select particular rows from a table by specifying a condition through WHERE clause along with SELECT
statement. E.g. In employee table if we want to select rows where Gender is female, then command is :
SELECT * FROM EMPLOYEE
WHERE GENDER = ‘F’ ;
E.g.2. in order to select rows where salary is greater than 48000, then command is :
SELECT * FROM EMPLOYEE WHERE GROSS > 48000 ;
ELIMINATING REDUNDANT DATA
The DISTINCT keyword eliminates duplicate rows from the results of a SELECT statement. For example ,
SELECT GENDER FROM EMPLOYEE ;
- The NOT IN operator finds rows that do not match in the list. E.g.
SELECT * FROM EMPLOYEE
WHERE GRADE NOT IN (‘A1’ , ‘A2’);
Output will be :
to display the names of those students whose marks is NULL, we use the command :
SELECT Name
FROM EMPLOYEE
WHERE Marks IS NULL ;
Output will be :
SORTING RESULTS
Whenever the SELECT query is executed , the resulting rows appear in a predecided order.The ORDER BY clause
allow
sorting of query result. The sorting can be done either in ascending or descending order, the default is ascending.
The ORDER BY clause is used as :
SELECT <column name> , <column name>….
FROM <tablename>
WHERE <condition>
ORDER BY <column name> ;
e.g. to display the details of employees in EMPLOYEE table in alphabetical order, we use command :
SELECT *
FROM EMPLOYEE
ORDER BY ENAME ;
Output will be :
e.g. display list of employee in descending alphabetical order whose salary is greater than 40000.
SELECT ENAME
FROM EMPLOYEE
WHERE GROSS > 40000
ORDER BY ENAME desc ;
Output will be :
Now following commands are given for the table. Predict the table contents after each of the following
statements:
(i) ALTER TABLE testt ADD col3 INT ;
(ii) ALTER TABLE testt ADD col4 INT NOT NULL ;
(iii) ALTER TABLE testt ADD col5 CHAR(3) NOT NULL ;
(iv) ALTER TABLE testt ADD col6 VARCHAR(3);
MODIFYING COLUMNS
Column name and data type of column can be changed as per following syntax :
ALTER TABLE <table name>
CHANGE <old column name> <new column name> <new datatype>;
If Only data type of column need to be changed, then
ALTER TABLE <table name>
MODIFY <column name> <new datatype>;
e.g.1. In table EMPLOYEE, change the column GROSS to SALARY.
ALTER TABLE EMPLOYEE
CHANGE GROSS SALARY INTEGER;
e.g.2. In table EMPLOYEE , change the column ENAME to EM_NAME and data type from VARCHAR(20) to
VARCHAR(30).
ALTER TABLE EMPLOYEE
CHANGE ENAME EM_NAME VARCHAR(30);
e.g.3. In table EMPLOYEE , change the datatype of GRADE column from CHAR(2) to VARCHAR(2).
ALTER TABLE EMPLOYEE
MODIFY GRADE VARCHAR(2);
DELETING COLUMNS
To delete a column from a table, the ALTER TABLE command takes the following form :
ALTER TABLE <table name>
DROP <column name>;
e.g. to delete column GRADE from table EMPLOYEE, we will write :
ALTER TABLE EMPLOYEE
DROP GRADE ;
ADDING/REMOVING CONSTRAINTS TO A TABLE
ALTER TABLE statement can be used to add constraints to your existing table by using it in following manner:
TO ADD PRIMARY KEY CONSTRAINT
ALTER TABLE <table name>
ADD PRIMARY KEY (Column name);
e.g. to add PRIMARY KEY constraint on column ECODE of table EMPLOYEE , the command is :
ALTER TABLE EMPLOYEE
ADD PRIMARY KEY (ECODE) ;
TO ADD FOREIGN KEY CONSTRAINT
ALTER TABLE <table name>
ADD FOREIGN KEY (Column name) REFERENCES Parent Table (Primary key of Parent Table);
REMOVING CONSTRAINTS
- To remove primary key constraint from a table, we use ALTER TABLE command
as : ALTER TABLE <table name>
DROP PRIMARY KEY ;
- To remove foreign key constraint from a table, we use ALTER TABLE command
as : ALTER TABLE <table name>
DROP FOREIGN KEY ;
ENABLING/DISABLING CONSTRAINTS
Only foreign key can be disabled/enabled in MySQL.
To disable foreign keys : SET FOREIGN_KEY_CHECKS = 0 ;
To enable foreign keys : SET FOREIGN_KEY_CHECKS = 1 ;
INTEGRITY CONSTRAINTS/CONSTRAINTS
- A constraint is a condition or check applicable on a field(column) or set of fields(columns).
- Common types of constraints include :
NOT NULL CONSTRAINT
By default, a column can hold NULL. It you not want to allow NULL value in a column, then NOT NULL constraint
must be applied on that column. E.g.
CREATE TABLE Customer
( SID integer NOT NULL ,
Last_Name varchar(30)
First_Name varchar(30)
NOT NULL
);
,
Columns SID and Last_Name cannot include NULL, while First_Name can include NULL.
An attempt to execute the following SQL statement,
INSERT INTO Customer
VALUES (NULL , ‘Kumar’ , ‘Ajay’);
will result in an error because this will lead to column SID being NULL, which violates the NOT NULL constraint
on that column.
DEFAULT CONSTARINT
The DEFAULT constraint provides a default value to a column when the INSERT INTO statement does not
provide a specific value. E.g.
CREATE TABLE Student
( Student_ID integer ,
Name varchar(30) ,
Score integer DEFAULT 80);
When following SQL statement is executed on table created above:
Here column Roll_No is a foreign key in table SCORE(Child Table) and it is drawing its values from
Primary key (ROLL_NO) of STUDENT table.(Parent Key).
CREATE TABLE STUDENT
( ROLL_NO integer NOT NULL PRIMARY KEY ,
NAME VARCHAR(30) ,
CLASS VARCHAR(3) );
CREATE TABLE SCORE
( ROLL_NO integer ,
MARKS integer ,
FOREIGN KEY(ROLL_NO) REFERNCES STUDENT(ROLL_NO) ) ;
* Foreign key is always defined in the child table.
Syntax for using foreign key
FOREIGN KEY(column name) REFERENCES Parent_Table(PK of Parent Table);
REFERENCING ACTIONS
Referencing action with ON DELETE clause determines what to do in case of a DELETE occurs in the parent table.
Referencing action with ON UPDATE clause determines what to do in case of a UPDATE occurs in the parent table.
Actions:
1. CASCADE : This action states that if a DELETE or UPDATE operation affects a row from the parent table, then
automatically delete or update the matching rows in the child table i.e., cascade the action to child table.
2. SET NULL : This action states that if a DELETE or UPDATE operation affects a row from the parent table, then
set the foreign key column in the child table to NULL.
3. NO ACTION : Any attempt for DELETE or UPDATE in parent table is not allowed.
4. RESTRICT : This action rejects the DELETE or UPDATE operation for the parent table.
Q: Create two tables
Customer(customer_id, name)
Customer_sales(transaction_id, amount , customer_id)
Underlined columns indicate primary keys and bold column names indicate foreign key.
Make sure that no action should take place in case of a DELETE or UPDATE in the parent table.
Sol : CREATE TABLE Customer (
customer_id int Not Null Primary Key ,
name varchar(30) ) ;
CREATE TABLE Customer_sales (
transaction_id Not Null Primary Key ,
amount int ,
customer_id int ,
FOREIGN KEY(customer_id) REFERENCES Customer (customer_id)
ON DELETE NO ACTION
ON UPDATE NO ACTION );
Q: Distinguish between a Primary Key and a Unique key in a table.
1. AVG( )
This function computes the average of given
data. e.g. SELECT AVG(SAL)
FROM EMPL ;
Output
AVG(SAL)
6051.6
2. COUNT( )
This function counts the number of rows in a given column.
If you specify the COLUMN name in parenthesis of function, then this function returns rows where COLUMN
is not null.
If you specify the asterisk (*), this function returns all rows, including duplicates and nulls.
e.g. SELECT COUNT(*)
FROM EMPL ;
Output
COUNT(*)
5
e.g.2 SELECT COUNT(JOB)
FROM EMPL ;
Output
COUNT(JOB)
4
3. MAX( )
This function returns the maximum value from a given column or expression.
e.g. SELECT MAX(SAL)
FROM EMPL ;
Output
MAX(SAL)
9870
4. MIN( )
This function returns the minimum value from a given column or expression.
e.g. SELECT MIN(SAL)
FROM EMPL ;
Output
MIN(SAL)
2985
5. SUM( )
This function returns the sum of values in given column or expression.
e.g. SELECT SUM(SAL)
FROM EMPL ;
Output
SUM(SAL)
30258
GROUPING RESULT – GROUP BY
The GROUP BY clause combines all those records(row) that have identical values in a particular field(column) or a
group of fields(columns).
GROUPING can be done by a column name, or with aggregate functions in which case the aggregate produces a
value for each group.
DATABASE TRANSACTIONS
TRANSACTION: A Transaction is a logical unit of work that must succeed or fail in its entirety. This statement
means that a transaction may involve many sub steps, which should either all be carried out successfully or all be
ignored if some failure occurs. A Transaction is an atomic operation which may not be divided into smaller
operations.
Example of a Transaction