DATABASE MANAGEMENT S YS T E M S
UNIT-II
1
DBMS LANGUAGES
⮚ SELECT Command
The SELECT command is used to retrieve data from one or more
tables in a database. The SELECT statement can be used in various
ways, such as selecting all data from a table, filtering records based
on conditions, or sorting the results.
Syntax
▪ SELECT * FROM Table_Name;
▪ SELECT * FROM Table_Name where clause;
⮚ INSERT Command
▪ The INSERT is used to add new records or rows to a table.
▪ This command can insert data into all columns or specific
columns of a table.
Syntax
▪ INSERT INTO Table_Name VALUES (Value 1, Value 2,Value 3);
▪ INSERT INTO Table_Name (Column 1, Column 2, Column 3)
VALUES (Value 1, Value 2, Value 3);
DBMS LANGUAGES
⮚ UPDATE Command
UPDATE is used to modify existing records in a table. This
command enables users to change the values of one or more
columns for specific rows based on a condition.
Syntax: UPDATE Table_Name SET Column_Name = 'New_Value'
WHERE Coulmn_Name = ‘Old_Value’;
EX: update orders set amount=150, customer_id=1 where
order_id=7;
⮚ DELETE Command
DELETE is used to remove one or more existing records from a
table in a database that meet certain conditions or criteria.
Syntax: DELETE FROM Table_Name WHERE Column = Value;
DBMS LANGUAGES
⮚ MERGE Command
MERGE is used to perform an operation which combines both UPDATE
and INSERT actions.
It allows you to insert new rows if they do not exist, or update existing
rows if they match a certain condition.
This command is particularly useful for synchronizing two tables by
inserting new records and updating existing ones in a single operation.
Syntax:
MERGE INTO target_table AS target
USING source_table AS source
ON (target.id = source.id)
WHEN MATCHED THEN
UPDATE SET target.name = source.name
WHEN NOT MATCHED THEN
INSERT (id, name) VALUES (source.id, source.name);
DBMS LANGUAGES
⮚ CALL Command
Stored procedures are sub routines, segment of SQL statements which are
stored in SQL catalog.
These procedures contain IN and OUT parameters, or both.
The call statement of MySQL is used to invoke/call a stored procedure.
1. Creating a table
CREATE TABLE Emp (id int, name VARCHAR(25), sal INT);
2. creating a stored procedure InsertData
Which accepts the id, name, sal values into the above emp table.
DELIMITER //
Create procedure insertdata (IN id int, IN name varchar(10), IN sal int)
BEGIN
INSERT INTO emp VALUES (3, 'krishna', 60000);
END //
DELIMITER ;
3. CALL user_defined_function(parameter 1, parameter 2);
EX: CALL insertdata(3, ‘krishna’, 60000);
DBMS LANGUAGES
⮚ EXPLAIN PLAN
EXPLAIN PLAN statement is to determine the execution plan of Oracle
Database follows to execute a specified SQL statement.
This statement inserts a row describing each step of the execution plan
into a specified table.
This statement also determines the cost of executing the statement.
⮚ LOCK Command
LOCK is used to lock the table for preventing access from others, ensuring
no other operations (like insertions, updates, or deletions) can be
performed on the table while it's locked. Useful for transactional
operations where consistency is important.
Syntax:
LOCK TABLE table_name IN EXCLUSIVE MODE;
DBMS LANGUAGES (DCL)
⮚ Data Control Language
It is used to control the access permissions of users to the database.
help grant or revoke privileges to users, determining who can perform
actions like reading or modifying data.
DCL commands can be rolled back if necessary.
The two main DCL commands are:
Grant: Gives user access to the database
Revoke: Removes access or permissions from the user
DBMS LANGUAGES (DCL)
⮚ Grant Command
It is used to provide specific permissions or privileges to users or roles.
Ensuring that only authorized users can perform certain actions, such as
selecting, inserting, updating, or deleting data.
Syntax:
GRANT privileges ON object TO user_or_role [WITH GRANT OPTION];
Ex:
GRANT SELECT, INSERT ON students TO user;
⮚ Revoke Command
Is used to remove previously granted permissions from users or roles.
This command is essential for managing access control.
Syntax:
REVOKE privileges ON object FROM user_or_role;
Ex:
REVOKE ALL PRIVILEGES ON students FROM user;
DBMS LANGUAGES (TCL)
⮚ Transaction Control Language
These commands are used to manage and control transactions in a
database, grouping them into logical units.
These commands help ensure the integrity of data and consistency
during complex operations.
Here are the commands in this category:
COMMIT
ROLLBACK
SAVEPOINT
AUTOCOMMIT
⮚ Commit
Is used to save the transaction to the database
Syntax:
COMMIT;
DBMS LANGUAGES (TCL)
⮚ Rollback
Is used to undo the recent transactions which have not yet been
committed.
Syntax:
ROLLBACK;
⮚ Savepoint
Is used to set a point within a transaction to which we can later rollback.
Syntax:
SAVEPOINT savepoint_name;
⮚ AUTOCOMMIT
In this the commit statement itself gets executed by the server after each
SQL statement.
Each SQL statement is treated as a different transaction.
An SQL statement executed in autocommit mode cannot be rolled back.
RELATIONAL MODEL
⮚ Relational model comes after Conceptual model of database in which
conceptual model is to be converted to tables (relation) which can be
implemented by RDBMS or ORACLE
⮚ Relational model is an abstract model used to organize and manage the
data stored in the database.
⮚ Relational model is stored in the form of rows and columns (relation or
table)
⮚ Ex:
RELATIONAL MODEL
BASIC TERMINOLOGY IN RM
1. Attribute: properties of entity (table columns)
2. Tuple: data values of rows
3. Relation: collection of rows and columns
4. Relation schema: name of the relation
5. Relation instance: a set of tuples of relation at a particular time
6. Degree: no.of columns/attributes of a relation
7. Co-ordinality no.of rows/tuples of a relation
8. Column: set of values for attributes
9. Null values: it is nothing / a blank space (not zero)
10. Domain: set of possible values
11. Key constraints: it is an attribute which is used for unique
identification of each row in table.
RELATIONAL MODEL
Key constraints: it is an attribute which is used for unique identification
of each row in table.
The different type of keys are
Primary key (The selected attribute from set of key attributes)
Composite key (can have multi values)
Foreign key (primary key of another table act as foreign key)
Super key (a set of attribute keys)
Candidate key (minimal set of attributes for unique identification)
alternative key (is any candidate key in a table that is not chosen as
the primary key)
CONSTRAINTS IN RELATIONAL MODEL
While designing the relational model we define some conditions which
must hold for data present in the database are called constraints or
conditions
These conditions will be checked before performing any operation.
Operation will be failed if any constraint is violated.
ADVANTAGES
It is simple and easy to use
FLEXIBLE: It is more flexible than any other model
SECURE: It is more secure
DATA ACCURACY: Data is more accurate in R.M
QUERY CAPABILITY: using SQL we can get data from DB easily
DATA INDEPENDENCE: we make changes easily without cganging
application
SCALABILITY: it is much scalable as per requirement.
CONSTRAINTS IN RELATIONAL MODEL
DISADVANTAGES
It is not suitable for large DATABASES
It becomes difficult to find the relation between fields in large DB
Response time is very high in complex databases
DATATYPE
Data types define the type of value a column can hold, such as numbers,
text, or dates.
Numeric Data Types (Bigint, Int, Smallint, Bit, Decimal, Numeric, money)
Character and String Data Types (Char, Varchar, Varchar(max), Text)
Date and Time Data Types (Date, Time, Datetime)
Binary Data Types (Binary, VarBinary, Image)
Boolean Data Types (True/False)
Special Data Types (XML, JSON…etc)
INTEGRITY CONSTRAINTS OVER RELATIONS
In DBMS there are certain set of rules which are used to maintain the
quality and consistency of data in DB
In DBMS integrity constraints are predefined set of rules or conditions
that are applied on table field.
It is classified into 4 types
INTEGRITY CONSTRAINTS OVER RELATIONS
⮚ Domain Constraints
Every domain must contain atomic values(smallest indivisible units)
which means composite and multi-valued attributes are not allowed.
Here we perform datatype & range checking.
EX: Rno Name Phone
1 HARI KRISHNA 123546789
987654321
2@ HARI 5432112345
INVALID
INTEGRITY CONSTRAINTS OVER RELATIONS
⮚ Key Constraints or Uniqueness Constraints
These are called uniqueness constraints since it ensures that every
tuple in the relation should be unique.
Repeat values are not allowed in the primary key.
EX:
Rno Name Phone
1 HARI KRISHNA 123546789
2 HARI 987654321
1 RAMESH 5432112345
INVALID
INTEGRITY CONSTRAINTS OVER RELATIONS
⮚ Entity Integrity Constraints
Entity Integrity constraints say that no primary key can take a NULL
value, since using the primary key we identify each tuple uniquely in a
relation
EX:
Rno Name Phone
1 HARI KRISHNA 123546789
2 HARI 987654321
NULL RAMESH 5432112345
INVALID
INTEGRITY CONSTRAINTS OVER RELATIONS
⮚ Referential Integrity Constraints
The Referential integrity constraint is specified between two relations
or tables.
This constraint is enforced through a foreign key.
The values of the foreign key in a tuple of relation table1 can take the
values of the primary key for some tuple in relation table2.
Emp_id Name D_id D_id Place
1 HARI KRISHNA 12 12 Hyd
2 HARI 22 32 Sec
4 RAMESH 32 42 Hyd
In the above tables, the D_id of Table 1 is the foreign key, and D_id in
Table 2 is the primary key.
D_id = 22 in the foreign key of Table 1 is not allowed because D_id = 22
is not defined in the primary key of table 2. Therefore.
Referential integrity constraints are violated here.
ENFORCING INTEGRITY CONSTRAINTS
⮚ Enforcing Integrity Constraints may be considered the
DATA TYPE
CHECK (RANGE)
PRIMARY KEY
NOT NULL
UNIQUE
DEFAULT
FOREIGN KEY
ENFORCING INTEGRITY CONSTRAINTS
⮚ DATA TYPE
Data type: will be checked and the matched value will be allowed
Range (CHECK): it will allow some certain range of values
Ex: Create a table std with 2 attributes of int type to perform data type
checking and range checking (checking age>16)
Create table std (rno int, age int check(age>16));
Insert into std values(1, 17); will be accepted
Insert into std values(‘ACE’, 17); Datatype error will arise
Insert into std values(1, 15);
Range check error will arise
ENFORCING INTEGRITY CONSTRAINTS
⮚ PRIMARY KEY
PRIMARY KEY: It will check the values for key attribute and not allows
duplicate data and null values
Ex: Create a table std with 2 or 3 attributes, among one attribute as
primary key.
Create table std (rno int primary key, name varchar(20), marks float);
insert into std values (1, ‘hari', 85.3); will be accepted
insert into std values (1, ‘krishna’, 89.9); shows the following error
ERROR 1062 (23000): Duplicate entry '1' for key 'std.PRIMARY'
ENFORCING INTEGRITY CONSTRAINTS
⮚ NOT NULL
NOT NULL: It will check the values for attribute and not allows null
values
Ex: Create a table std with 2 or 3 attributes, among one attribute as
NOT NULL constraint.
Create table std (rno int primary key, name varchar(20), marks float
not null);
insert into std values (1, ‘hari', 85.3); will be accepted
insert into std (rno, marks) values (2, 94.3); accepts null values for
column “name”
insert into std (rno, name) values (3, "krishna"); shows the error
ERROR 1364 (HY000): Field 'marks' doesn't have a default value
ENFORCING INTEGRITY CONSTRAINTS
⮚ UNIQUE, DEFAULT
UNIQUE: To have the unique values (Accepts NULL values).
DEFAULT: To have the default values.
Ex: Create a table std with 3 attributes, among one attribute as UNIQUE
and another attribute with DEFAULT value.
create table std (rno int unique, name varchar(20), college varchar(10)
default "ACE");
insert into std values (1, ‘hari’, “SKEC”); will be done
insert into std values(1, "krishna", "skit"); duplicate error
ERROR 1062 (23000): Duplicate entry '1' for key 'std.rno'
insert into std (rno, name) values (2, "krishna");default value is taken
ENFORCING INTEGRITY CONSTRAINTS
⮚ FOREIGN KEY
FOREIGN KEY: It is a primary of another table used to refer that table
from existing table.
For this purpose, we need to create two different tables with a
common attribute
Ex1: Create a table std with 3 attributes rno, name, dept_id in which
rno is a primary key and dept_id is a foreign key.
EX2: create a table dept with 3 attributes dept_id, name, strength.
NOTE: the referred table must be created first and dropped last.
T1: Create table dept(dept_id int primary key, name varchar(20),
strength int);
T2: Create table std (rno int primary key, name varchar(20), dept_id
int, foreign key(dept_id) references dept(dept_id));
ENFORCING INTEGRITY CONSTRAINTS
⮚ FOREIGN KEY
insert into dept values (01,"csd",64);
insert into std values (1,"hari",01); Both will be accepted
insert into std values(2,"krishna",01); It also be accepted
insert into std values(3,"krishna",02); Not accepted (dept_id.02
is not available in dept table)
drop table dept; Cannot drop table 'dept' referenced by a
foreign key constraint 'std_ibfk_1' on table 'std'.
drop table std; Both the table will be dropped
drop table dept; but only in the same order
QUERYING RELATIONAL DATA
⮚ A Relational database query is a question about data and the answer
as result.
⮚ A Database query is either a select query or action query
⮚ A Select query is one that retrieve the data from the DATABASE
⮚ An Action query is one that perform additional operation on data
such as insertion, updation, deletion etc.
⮚ Querying helps in retrieving meaningful information from database
tables that are related to each other.
QUERYING RELATIONAL DATA
⮚ Types of relational queries
⮚ Selection queries (selection on clauses)
⮚ Projection queries (selection of columns)
⮚ Join queries (combines data from multiple tables)
⮚ Aggregation queries (using athematic functions)
⮚ Grouping queries (to group categorized result)
⮚ Sorting queries ( using ORDER by clause for ascending or
descending)
⮚ Filtering queries (using HAVING clause to filter grouped
result)
⮚ Sub or nested queries (query within another query)
⮚ Modification queries (insert, update, delete ….)
QUERYING RELATIONAL DATA
⮚ CREATE TABLE STD WITH RNO, NAME, PERC, ATTENDANCE
⮚ Selection queries
⮚ Select is a keyword used to fetch the data from the database where
data will be fetched in the form of result table.
⮚ SYNTAX: select c1,c2,c3 from table_name;
⮚ Ex: select * from table_name;
⮚ Ex: select rno, name, marks from std;
⮚ Select with where clause
⮚ Select with where clause is used to select the data from database by
following some conditions in the name of where.
⮚ SYNTAX: select * from std where condition;
select c1,c2 from std where condition;
⮚ Ex: select * from std where marks>75;
select rno, name from std where rno=1
QUERYING RELATIONAL DATA
⮚ Select with where clause (Contd…)
⮚ This where clause can be used with many other operations like
BETWEEN, NOT BETWEEN, IN, NOT IN.
⮚ BETWEEN
⮚ It selects the record with in given range and includes both the values
SYNTAX:
select * from table_name where column_name between value1 and value2;
EX: Select * from std where rno between 1 and 3;
⮚ NOT BETWEEN
⮚ It selects the record from out of the given range and excludes both the
values
SYNTAX:
select * from table_name where column_name not between value1 and
value2;
EX: Select * from std where rno not between 1 and 3;
QUERYING RELATIONAL DATA
⮚ Select with where clause (Contd…)
⮚ IN
⮚ It selects the records which exactly matches with the given values
SYNTAX:
select * from table_name where column_name in (value1, value2 ….);
EX: Select * from std where rno in (1,3);
⮚ NOT IN
⮚ It selects the records which are not matches with the given values
SYNTAX:
select * from table_name where column_name not in (value1, value2…);
EX: Select * from std where rno in (1,3);
QUERYING RELATIONAL DATA
⮚ Select with where clause (Contd…)
⮚ LIKE Operator
⮚ It is a searching pattern technique with the help of where clause to
search for a specified pattern in a column.
⮚ Here we use two wild cards (%, _)
⮚ % represents multiple characters
⮚ _ represents single character
SYNTAX:
select * from table_name where column_name like pattern;
Display std names whose names starts with “BHANU”
Using % wild card: Select * from std where name like “Bhanu %”;
Using _ wild card: Select * from std where name like “sri sa_”;
QUERYING RELATIONAL DATA
⮚ Select with where clause (Contd…)
⮚ JOIN
⮚ The SQL JOIN statement is used to combine rows from two tables
based on a common column and selects records that have matching
values in these columns.
⮚ For these we need to have 2 different tables with a common column
values.
Ex:
select std.rno, std.name, std.d_id, dept.d_name from std join dept on
std.d_id=dept.d_id;
⮚ Agreagate functions
⮚ These aggregate functions will use the arithmetic functions like min,
max, sum, count, avg….
⮚ SYNTAX: select min(column_name) from table_name;
QUERYING RELATIONAL DATA
⮚ Agreagate functions
⮚ EX: select min(price) from market;
⮚ EX: select max(price) from market;
⮚ EX: select sum(price) from market;
⮚ EX: select count(*) from market;
⮚ EX: select avg(price) from market;
⮚ DISTINCT COUNT: select count(distinct column_name) from table_name;
⮚ Ex: select count(distinct s_id) from std;
ALIAS is a type of command where we can give our own name for any
particular column.
Syntax: select column_name as new_name from table_name;
Ex: select rno as roll_number from std;
ALIAS for TABLE name: we can give alias name for table
also
Syntax: select alias_table_name.column_name from
table_name as alias_table_name;
Ex: select s.rno from std as s;
Without alias: we can skip AS in RDBMS
Ex: select r.no roll_number from std;
Introduction to VIEWS
View is a kind of virtual table of content of data and constraints.
View is a table whose rows are not explicitly stored, it is a
virtual table based on the result set of SQL query.
A view can contain all rows or selected rows of from a table.
A view can be created from one or more tables depend on the
SQL query.
A view can be generated as per the user specific needs rather
than the complete information of a table.
Types of VIEWS
READ only views: allows only select operation.
Updatable views: allows select as well as insert, delete
operations.
DATA Introduction to VIEWS
Advantages of VIEWS
Using views we can join multiple tables into single table
View can hide data complexity
View takes less storage than the original table.
Disadvantages of VIEWS
View can not insert if the base table has any NOT NULL column that do
not appear in the view.
Multiple rows will be created at single insert operation if we create
view on multiple tables.
SYNTAX
Create view view_name as select * from table_name;
EX: create view std_info as select * from std;
EX: create view rno_above4 as select * from std where rno>4;
DATA Introduction to VIEWS
VIEWS on multiple tables
We can create view on multiple tables with the following syntax
SYNTAX:
create view multiple as select t1.c1, t1.c2, t1.c3, t2.c1 from t1, t2
where clause;
EX: create view multiple as select std.rno, std.name, std.d_id,
dept.dept_name from std, dept;
Listing all Views: We can list all the views by using “SHOW FULL
TABLES” statement.
Syntax: SHOW FULL TABLES WHERE table_type LIKE "%VIEW";
DATA Introduction to VIEWS
DELETE: It is used to delete a row from view
Syntax: delete from view_name where condition;
Ex: delete from v1 where rno>3;
DROP: It is used to delete the entire view permanently from the
database.
Syntax: drop view view_name;
Ex: drop view v1;
Formal Relational Query Languages
Two mathematical Query Languages form the basis for “real”
languages (e.g. SQL), and for implementation:
◦ Relational Algebra: More operational, very
useful for representing execution plans.
◦ Relational Calculus: Lets users describe what
they want, rather than how to compute it. (Non-
operational, declarative.)
41
Relational Algebra
• Basic operations:
– Selection ( ) Selects a subset of rows from relation.
– Projection ( ) Deletes unwanted columns from relation.
–
Cross-product ( ) Allows us to combine two relations.
( ) Tuples in reln. 1, but not in
–
Set-difference
reln. 2.
– ∪
Union ( ) Tuples in reln. 1 and in reln. 2.
• Additional operations:
– Intersection, join, division, renaming
42
Relational calculus
Before understanding Relational calculus in DBMS, we need to
understand Procedural Language and Declarative Language.
Procedural Language: Those Languages which clearly define how
to get the required results from the Database are called Procedural
Language. Relational algebra is a Procedural Language.
Declarative Language: Those Language that only cares about
What to get from the database without getting into how to get the
results are called Declarative Language.
Relational Calculus is a Declarative Language.
Relational Calculus is of Two Types:
Tuple Relational Calculus (TRC)
Domain Relational Calculus (DRC)
Tuple Relational calculus
Tuple Relational Calculus uses a tuple variable (t) that goes to each
row of the table and checks if the predicate is true or false for the
given row and returns the row by depending on the predicate.
Syntax: {t \| P(t)}
Where t is the tuple variable, and P(t) is the predicate logic.
P(t) may have various conditions logically combined with OR (∨),
AND (∧), NOT(¬).
It also uses quantifiers:
∃ t ∈ r (Q(t)) = ”there exists(∃)” a tuple in t in relation r such that
predicate Q(t) is true.
∀ t ∈ r (Q(t)) = Q(t) is true “for all(∀)” tuples in relation r.
Tuple Relational calculus
There are two types of tuple variables
Free Variables: Any tuple variable without any ‘For All’ or ‘there
exists’ condition is called Free Variable
Bounded Variables: Any tuple variable with the ‘For All’ or
‘there exists’ condition is called Bounded Variable
Ex: consider students table with name, age, course.
1. Create a TRC query to get data of all the students whose age>=18
{t | t ∈ students (t) ∧ t.age >= 18} or
{t | student(t) AND t.age > 18}
2. Create a TRC query to get names of all the students who are
enrolled in the course DBMS.
{t| ∃ s ∈ students(t.name = s.name ∧ t.course =”DBMS”)}
Domain Relational calculus
Domain Relational Calculus uses domain Variables to get the
column values required from the database based on the predicate
expression or condition.
Syntax: {<c1, c2, c3...>\| P(c1, c2, c3...)}
Where <c1, c2, c3...> are domain variables (columns) required and
P(c1, c2, c3...) is predicate expressions.
EX: DRC to find the name, course of the students whose age is < 18
{< name, course > \| ∈ students ∧ age < 18}
EX: DRC find the data of all the students whose course is DBMS
{<name,age,course> \| ∈ students ∧ course =‘DBMS’ }