Unit 2ND Notes (DBMS)
Unit 2ND Notes (DBMS)
Concepts
Tables − in relational data model, relations are saved in the format of Tables. This format stores the relation
among entities. A table has rows and columns, where rows represent records and columns represent the
attributes.
Tuple − A single row of a table, which contains a single record for that relation is called a tuple.
Relation instance − A finite set of tuples in the relational database system represents relation instance.
Relation instances do not have duplicate tuples.
Relation schema − A relation schema describes the relation name (table name), attributes, and their names.
Relation key − each row has one or more attributes, known as relation key, which can identify the row in
the relation (table) uniquely.
Attribute domain − every attribute has some pre-defined value scope, known as attribute domain.
Degree: The total number of attributes which in the relation is called the degree of the relation
Constraints
Every relation has some conditions that must hold for it to be a valid relation. These conditions are
called Relational Integrity Constraints. There are three main integrity constraints −
Key constraints
Domain constraints
Referential integrity constraints
Key Constraints
There must be at least one minimal subset of attributes in the relation, which can identify a tuple uniquely.
This minimal subset of attributes is called key for that relation. If there are more than one such minimal
subset, these are called candidate keys.
Key constraints force that −
In a relation with a key attribute, no two tuples can have identical values for key attributes.
A key attribute cannot have NULL values.
We perform data type check here, which means when we assign a data type to a column we limit the
values that it can contain. E.g. If we assign the data type of attribute age as int, we can’t give it values
other then int data type.Domain constraints are user defined data type and we can define them like
this:Domain Constraint = data type + Constraints (NOT NULL / UNIQUE / PRIMARY KEY / FOREIGN
KEY / CHECK / DEFAULT)
Referential integrity Constraints
Referential integrity constraints work on the concept of Foreign Keys. A foreign key is a key attribute of a
relation that can be referred in other relation.Referential integrity constraint states that if a relation refers to a
key attribute of a different or same relation, then that key element must exist.
Relational Algebra
Relational algebra is a procedural query language, which takes instances of relations as input and yields
instances of relations as output. It uses operators to perform queries. An operator can be
either unary or binary. They accept relations as their input and yield relations as their output. Relational
algebra is performed recursively on a relation and intermediate results are also considered relations.
The fundamental operations of relational algebra are as follows −
Select
Project
Union
Set different
Cartesian product
Rename
Tuple relational calculus which was originally proposed by Codd in the year 1972 and
Domain relational calculus which was proposed by Lacroix and Pirotte in the year 1977
For example −
{ R| ∃T ∈ Authors(T.article='database' AND R.name=T.name)}
Output − The above query will yield the same result as the previous one.
Domain Relational Calculus (DRC)
In DRC, the filtering variable uses the domain of attributes instead of entire tuple values (as done in TRC,
mentioned above).
Notation −
{ a1, a2, a3, ..., an | P (a1, a2, a3, ... ,an)}
Where a1, a2 are attributes and P stands for formulae built by inner attributes.
For example −
{< article, page, subject > | ∈ TutorialsPoint ∧ subject = 'database'}
Output − Yields Article, Page, and Subject from the relation TutorialsPoint, where subject is database.
Just like TRC, DRC can also be written using existential and universal quantifiers. DRC also involves
relational operators.
The expression power of Tuple Relation Calculus and Domain Relation Calculus is equivalent to Relational
Algebra.
Projection (π)
Projection is used to project required column data from a relation.
Example :
R
(A B C)
----------
1 2 4
2 2 3
3 2 3
4 3 4
π (BC)
B C
-----
2 4
2 3
3 4
Note: By Default projection removes duplicate data.
Selection (σ)
Selection is used to select required tuples of the relations.
for the above relation
σ (c>3)R
will select the tuples which have c more than 3.
Note: selection operator only selects the required tuples but does not display them. For displaying, data
projection operator is used.
For the above selected tuples, to display we need to use projection also.
π (σ (c>3)R ) will show following tuples.
A B C
-------
1 2 4
4 3 4
Union (U)
Union operation in relational algebra is same as union operation in set theory, only constraint is for union
of two relation both relation must have same set of Attributes.
Rename (ρ)
Rename is a unary operation used for renaming attributes of a relation.
ρ (a/b)R will rename the attribute ‘b’ of relation by ‘a’.
AXB
Name Age Sex Id Course
---------------------------------
Ram 14 M 1 DS
Ram 14 M 2 DBMS
Sona 15 F 1 DS
Sona 15 F 2 DBMS
Kim 20 M 1 DS
Kim 20 M 2 DBMS
Note: if A has ‘n’ tuples and B has ‘m’ tuples then A X B will have ‘n*m’ tuples.
Emp Dep
(Name Id Dept_name ) (Dept_name Manager)
------------------------ ---------------------
A 120 IT Sale Y
B 125 HR Prod Z
C 110 Sale IT A
D 111 IT
Emp ⋈ Dep
Conditional Join
Conditional join works similar to natural join. In natural join, by default condition is equal between
common attribute while in conditional join we can specify the any condition such as greater than, less
than, not equal
Characteristics of SQL
1. Easy to Learn: SQL is user-friendly, English like language that makes it easy to learn. Learning SQL
doesn’t require prior knowledge.
2. Portable language: SQL is a portable language, which means the software that supports SQL can be
moved to another machine without affecting the capability of SQL interacting with the database on new
machine.
3. Supports wide variety of commands: SQL supports various useful commands such as:
DDL (Data Definition Language) commands like CREATE, DROP, ALTER.
DML (Data Manipulation Language) commands like INSERT, DELETE, UPDATE.
DCL (Data Control Language) commands like GRANT, REVOKE.
TCL (Transaction Control Language) commands like COMMIT, ROLLBACK.
DQL (Data Query Language) commands like SELECT.
Reusability: SQL promotes reusability by supporting stored procedures. These stored procedures are
stored SQL statements that can be used to perform a specific task any number of times. This makes it
easier to write SQL statements for a re-occurring task and reusing the saved stored procedure to erform
the same task without rewriting the same SQL statements again.Supports JOIN: SQL supports join hich
is used to combine the data of two or more tables. This can be useful when we need to perform the
operation on multiple tables.Supports UNION: UNION command can be used to join two or more DQL
statement (SELECT statements).Integration: SQL allows integration to non-SQL database applications
as well.Performance: Better performance even if the database size if huge.SQL is scalable and flexible.
SQL is secure.
Advantages of SQL:
SQL has many advantages which makes it popular and highly demanded. It is a reliable and efficient
language used for communicating with the database. Some advantages of SQL are as follows:
Commonality. One of the main benefits of using SQL is the commonality of the language. ...
1. Simplicity. Another benefit of using SQL is the simplicity of the language. ...
2. Integration. ...
3. Speed. ...
4. Alter data within a table. ...
5. Create a table. ...
6. Retrieve data. ...
7. Change data structure.
Applications of SQL:
SQL is used by developers and DBAs (Database Administrators) in writing Data Integration Scripts.
It is used to deal with analytical queries to analyze the data and get instincts from it.
Retrieving Information
Modification/Manipulation of data and database table such as Insertion, Deletion and Updating.
DDL (Data Definition Language)
DDL or Data Definition Language actually consists of the SQL commands that can be used to define the
database schema. It simply deals with descriptions of the database schema and is used to create and modify
the structure of database objects in the database.DDL is a set of SQL commands used to create, modify, and
delete database structures but not data. These commands are normally not used by a general user, who
should be accessing the database via an application.
DQL statements are used for performing queries on the data within schema objects. The purpose of the
DQL Command is to get some schema relation based on the query passed to it. We can define DQL as
follows it is a component of SQL statement that allows getting data from the database and imposing order
upon it. It includes the SELECT statement. This command allows getting the data out of the database to
perform operations with it. When a SELECT is fired against a table or tables the result is compiled into a
further temporary table, which is displayed or perhaps received by the program i.e. a front-end.
List of DQL:
Though many resources claim there to be another category of SQL clauses TCL – Transaction Control
Language. So we will see in detail about TCL as well. TCL commands deal with the transaction within the
database.
Transaction Control Language (TCL) instructions are used in the database to manage transactions. This
command is used to handle the DML statements’ modifications. TCL allows you to combine your statements
into logical transactions.
CREATE
CREATE statements is used to define the database structure schema:
For example:
Drop object_type object_name;
Drop database university;
Drop table student;
ALTER
Alters command allows you to alter the structure of the database.
To add a new column in the table
ALTER TABLE table_name ADD column_name COLUMN-definition;
To modify an existing column in the table:
ALTER TABLE MODIFY(COLUMN DEFINITION....);
For example:
Alter table guru99 add subject varchar;
TRUNCATE:
This command used to delete all the rows from the table and free the space containing the table.
TRUNCATE TABLE table_name;
Example:
TRUNCATE table students;
INSERT:
This is a statement is a SQL query. This command is used to insert data into the row of a table.
INSERT INTO TABLE_NAME (col1, col2, col3,.... col N)
VALUES (value1, value2, value3, .... valueN);
Or
INSERT INTO TABLE_NAME
VALUES (value1, value2, value3, .... valueN);
For example:
INSERT INTO students (RollNo, FIrstName, LastName) VALUES ('60', 'Tom', Erichsen');
UPDATE:
This command is used to update or modify the value of a column in the table.
UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [WHERE CONDITION]
For example:
UPDATE students
SET FirstName = 'Jhon', LastName= 'Wick'
WHERE StudID = 3;
DELETE:
This command is used to remove one or more rows from a table.
DELETE FROM table_name [WHERE condition];
For example:
DELETE FROM students
WHERE FirstName = 'Jhon';
Grant
Revoke
Grant:
This command is use to give user access privileges to a database.
GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;
For example:
GRANT SELECT ON Users TO'Tom'@'localhost;
Revoke:
It is useful to back permissions from the user.
REVOKE privilege_nameON object_nameFROM {user_name |PUBLIC |role_name}
For example:
REVOKE SELECT, UPDATE ON student FROM BCA, MCA;
Example of TCL:
Commit
This command is used to save all the transactions to the database.
Commit;
For example:
DELETE FROM Students
WHERE RollNo =25;
COMMIT;
Rollback
Rollback command allows you to undo transactions that have not already been saved to the database.
ROLLBACK;
Example:
DELETE FROM Students
WHERE RollNo =25;
SAVEPOINT
This command helps you to sets a savepoint within a transaction.
SAVEPOINT SAVEPOINT_NAME;
Example:
SAVEPOINT RollNo;
SELECT expressions
FROM TABLES
WHERE conditions;
For example:
SELECT FirstName
FROM Student
WHERE RollNo > 15;
SQL Operators:
Generally, there are three types of operators that are used in SQL.
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
Now, let’s look at each one of them in detail.
Arithmetic operators are used to perform arithmetic operations such as addition, subtraction, division, and
multiplication. These operators usually accept numeric operands. Different operators that come under this
category are given below-
% Modulus Divides left-hand operand by right-hand operand and returns the remainder
= Equal to Checks if both operands have equal value, if yes, then returns TRUE
Checks if the value of the left-hand operand is greater than the right-hand
> Greater than
operand or not
Returns TRUE if the value of the left-hand operand is less than the value of the
< Less than
right-hand operand
Greater than or It checks if the value of the left-hand operand is greater than or equal to the
>=
equal to value of the right-hand operand, if yes, then returns TRUE
Less than or equal Examines if the value of the left-hand operator is less than or equal to the right-
<=
to hand operand
Checks if values on either side of the operator are equal or not. Returns TRUE
<> or != Not equal to
if values are not equal
Used to check if the left-hand operator’s value is not greater than or equal to
!> Not greater than
the right-hand operator’s value
Used to check if the left-hand operator’s value is not less than or equal to the
!< Not less than
right-hand operator’s value
3. Logical SQL Operators
Logical operators are those operators that take two expressions as operands and return TRUE or False as
output. While working with complex SQL statements and queries, comparison operators come in handy and
these operators work in the same way as logic gates do. Different logical operations available in SQL are
given in the below table.
Operator Description
AND Returns the records if all the conditions separated by AND are TRUE
LIKE It returns the rows for which the operand matches a specific pattern
BETWEEN Returns the rows for which the value lies between the mentioned range
OR Returns the records for which any of the conditions separated by OR is true
VIEW
A view can contain all rows of a table or select rows from a table. A view can be created from one or many
tables which depend on the written SQL query to create a view. A view is simply any SELECT query that has
been given a name and saved in the database. For this reason, a view is sometimes called a named query or
a stored query.
Views, which are a type of virtual tables, allow users to do the following −
Structure data in a way that users or classes of users find natural or intuitive.
Restrict access to the data in such a way that a user can see and (sometimes) modify exactly what they
need and no more.
Summarize data from various tables which can be used to generate reports.
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
INDEXES
An index helps to speed up SELECT queries and WHERE clauses, but it slows down data input, with
the UPDATE and the INSERT statements. Indexes can be created or dropped with no effect on the data
an index, as you would expect, is a data structure that the database uses to find records within a table more
quickly. Indexes are built on one or more columns of a table; each index maintains a list of values within that
field that are sorted in ascending or descending order. Rather than sorting records on the field or fields during
query execution, the system can simply access the rows in order of the index.
Syntax: As you would expect by now, the SQL to create an index is:
CREATE INDEX <indexname> ON <tablename> (<column>, <column>...);
To enforce unique values, add the UNIQUE keyword:
CREATE UNIQUE INDEX <indexname> ON <tablename> (<column>, <column>...);
To specify sort order, add the keyword ASC or DESC after each column name, just as you would do in an
ORDER BY clause.
To remove an index, simply enter:
DROP INDEX <indexname>;
SUBQUERY
A Subquery or Inner query or a Nested query is a query within another SQL query and embedded within the
WHERE clause.A subquery is used to return data that will be used in the main query as a condition to further
restrict the data to be retrieved.
SELECT column_name [, column_name ]
FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE])
AGGREGATE FUNCTION
An aggregate function in SQL returns one value after calculating multiple values of a column. We
often use aggregate functions with the GROUP BY and HAVING clauses of the SELECT
statement.Various types of SQL aggregate functions are:
Count()
Sum()
Avg()
Min()
Max()
INSERT
This is a statement is a SQL query. This command is used to insert data into the row of a table.
INSERT INTO TABLE_NAME (col1, col2, col3,.... col N)
VALUES (value1, value2, value3, .... valueN);
Or
INSERT INTO TABLE_NAME
VALUES (value1, value2, value3, .... valueN);
For example:
INSERT INTO students (RollNo, FIrstName, LastName) VALUES ('60', 'Tom', Erichsen');
UPDATE
This command is used to update or modify the value of a column in the table.
UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [WHERE CONDITION]
For example:
UPDATE students
SET FirstName = 'Jhon', LastName= 'Wick'
WHERE StudID = 3;
DELETE
This command is used to remove one or more rows from a table.
DELETE FROM table_name [WHERE condition];
For example:
DELETE FROM students
WHERE FirstName = 'Jhon';
JOIN
SQL Join statement is used to combine data or rows from two or more tables based on a common field
between them. Different types of Joins are as follows:
INNER JOIN
LEFT JOIN
RIGHT JOIN
FULL JOIN
A. INNER JOIN
The INNER JOIN keyword selects all rows from both the tables as long as the condition is satisfied. This
keyword will create the result-set by combining all rows from both the tables where the condition satisfies
i.e value of the common field will be the same.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;
B. LEFT JOIN
This join returns all the rows of the table on the left side of the join and matches rows for the table on the
right side of the join. For the rows for which there is no matching row on the right side, the result-set will
contain null. LEFT JOIN is also known as LEFT OUTER JOIN.
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;
C. RIGHT JOIN
RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of the table on the right side of the
join and matching rows for the table on the left side of the join. For the rows for which there is no
matching row on the left side, the result-set will contain null. RIGHT JOIN is also known as RIGHT
OUTER JOIN.
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;
D. FULL JOIN
FULL JOIN creates the result-set by combining results of both LEFT JOIN and RIGHT JOIN. The result-
set will contain all the rows from both tables. For the rows for which there is no matching, the result-set
will contain NULL values.
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;
CARTESIAN JOIN
The CARTESIAN JOIN is also known as CROSS JOIN. In a CARTESIAN JOIN there is a join for each
row of one table to every row of another table. This usually happens when the matching column or
WHERE condition is not specified.
In the absence of a WHERE condition the CARTESIAN JOIN will behave like a CARTESIAN
PRODUCT . i.e., the number of rows in the result-set is the product of the number of rows of the
two tables.
In the presence of WHERE condition this JOIN will function like a INNER JOIN.
Generally speaking, Cross join is similar to an inner join where the join-condition will always
evaluate to True
Syntax:
SELECT table1.column1 , table1.column2, table2.column1...
FROM table1
CROSS JOIN table2;
table1: First table.
table2: Second table
EXAMPLE
SELECT Student.NAME, Student.AGE, StudentCourse.COURSE_ID
FROM Student
CROSS JOIN StudentCourse;
SELF JOIN
As the name signifies, in SELF JOIN a table is joined to itself. That is, each row of the table is joined with
itself and all other rows depending on some conditions. In other words we can say that it is a join between
two copies of the same table.Syntax:
SELECT a.coulmn1 , b.column2
FROM table_name a, table_name b
WHERE some_condition;
EXAMPLE
SELECT a.ROLL_NO , b.NAME
FROM Student a, Student b
WHERE a.ROLL_NO < b.ROLL_NO;
UNION
The Union Clause is used to combine two separate select statements and produce the result set as a union
of both the select statements.
NOTE:
1. The fields to be used in both the select statements must be in same order, same number and same data
type.
2. The Union clause produces distinct values in the result set, to fetch the duplicate values too UNION
ALL must be used instead of just UNION.
Basic Syntax:
SELECT column_name(s) FROM table1 UNION SELECT column_name(s) FROM table2;
UNION ALL
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
UNION ALL
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
INTERSECT
The following statement combines the results with the INTERSECT operator, which returns only those
unique rows returned by both queries:
SELECT product_id FROM inventories
INTERSECT
SELECT product_id FROM order_items
ORDER BY product_id;
MINUS
The following statement combines results with the MINUS operator, which returns only unique rows returned
by the first query but not by the second:
SELECT product_id FROM inventories
MINUS
SELECT product_id FROM order_items
TRIGER
Triggers can be defined on the table, view, schema, or database with which the event is associated. A trigger
is a stored procedure in database which automatically invokes whenever a special event in the database
occurs. For example, a trigger can be invoked when a row is inserted into a specified table or when certain
table columns are being updated.
BEFORE and AFTER of Trigger:
BEFORE triggers run the trigger action before the triggering statement is run.
AFTER triggers run the trigger action after the triggering statement is run.
Operations in Triggers
We can perform many operations using triggers. Some may be simple and some may be a little complex, but
once if we go through the query its easy to understand.
DROP A Trigger
DROP TRIGGER trigger name;
Display A Trigger
The below code will display all the triggers that are present.
The below code will display all the triggers that are present in a particular database.
SHOW TRIGGERS
IN database_name;
Example:
SHOW TRIGGERS IN edureka;
In the above example, all the triggers that are present in the database named Edureka will be displayed.
We also look at some major variants of the triggers that are before insert and after insert. We have already
seen a trigger in the example. But with the help of the table let’s see how exactly this works.
As we have already understood how to create a trigger, now let’s understand the two variants of the trigger
those are before insert and after insert. In order to implement them, let’s create a student table with various
columns as shown below:
Before Insert
CREATE TRIGGER calculate
before INSERT
ON student
FOR EACH ROW
SET new.marks = new.marks+100;
After insert trigger
CREATE TRIGGER total_mark
after insert
ON student
FOR EACH ROW
insert into Final_mark values(new.marks);
Here when we insert data to the table, total_mark trigger will store the result in the Final_mark table.
That was all about the operation on triggers, lets now move ahead and look at its advantages and
disadvantages.
Advantages
Forcing security approvals on the table that are present in the database
Triggers provide another way to check the integrity of data
Counteracting invalid exchanges
Triggers handle errors from the database layer
Normally triggers can be useful for inspecting the data changes in tables
Triggers give an alternative way to run scheduled tasks. Using triggers, we don’t have to wait for the
scheduled events to run because the triggers are invoked automatically before or after a change is
made to the data in a table
PL SQL
.” PL/SQL is a database-oriented programming language that extends SQL with procedural
capabilities. It was developed by Oracle Corporation in the early 90s to boost the capabilities of SQL.
r. No. Key SQL PL/SQL
2 Variables SQL has no variables. PL/SQL has variables, data types etc.
3 Control SQL has no FOR loop, if control PL/SQL has FOR loop, while loop, if
Structures and similar structures. controls and other similar structures.
4 Operations SQL can execute a single operation PL/SQL can perform multiple operation at
at a time. a time.
6 Embedded SQL can be embedded in a PL/SQL PL/SQL can also be embedded in SQL
block. code.
6 Interaction SQL directly interacts with database PL/SQL does not directly interacts with
server. database server.
8 Objective SQL is used to write queries, create PL/SQL is used to write program blocks,
and execute DDL and DML functions, procedures, triggers and
statments. packages.