Unit 2
Unit 2
Digital Notes
[Department ofComputer Application]
Subject Name : Database Management System
ER model
For example, Suppose we design a school database. In this database, the student
will be an entity with attributes like address, name, id, age, etc. The address can be
another entity with attributes like city, street name, pin code, etc and there will be a
relationship between them.
Component of ER Diagram
1. Entity:
An entity may be any object, class, person or place. In the ER diagram, an entity
can be represented as rectangles.
a. Weak Entity
An entity that depends on another entity called a weak entity. The weak entity
doesn't contain any key attribute of its own. The weak entity is represented by a
double rectangle.
2. Attribute
For example, id, age, contact number, name, etc. can be attributes of a student.
a. Key Attribute
b. Composite Attribute
c. Multivalued Attribute
An attribute can have more than one value. These attributes are known as a
multivalued attribute. The double oval is used to represent multivalued attribute.
For example, a student can have more than one phone number.
d. Derived Attribute
For example, A person's age changes over time and can be derived from another
attribute like Date of birth.
3. Relationship
a. One-to-One Relationship
When only one instance of an entity is associated with the relationship, then it is
known as one to one relationship.
For example, A female can marry to one male, and a male can marry to one
female.
b. One-to-many relationship
When only one instance of the entity on the left, and more than one instance of an
entity on the right associates with the relationship then this is known as a one-to-
many relationship.
For example, Scientist can invent many inventions, but the invention is done by
the only specific scientist.
c. Many-to-one relationship
When more than one instance of the entity on the left, and only one instance of an
entity on the right associates with the relationship then it is known as a many-to-
one relationship.
For example, Student enrolls for only one course, but a course can have many
students.
d. Many-to-many relationship
When more than one instance of the entity on the left, and more than one instance
of an entity on the right associates with the relationship then it is known as a many-
to-many relationship.
For example, Employee can assign by many projects and project can have many
employees.
Notation of ER diagram
Mapping Constraints
One-to-many
Many-to-one
Many-to-many
Keys
For example: In Student table, ID is used as a key because it is unique for each
student. In PERSON table, passport_number, license_number, SSN are keys since
they are unique for each person.
Types of key:
1. Primary key
o It is the first key which is used to identify one and only one instance of an
entity uniquely. An entity can contain multiple keys as we saw in PERSON
table. The key which is most suitable from those lists become a primary key.
o In the EMPLOYEE table, ID can be primary key since it is unique for each
employee. In the EMPLOYEE table, we can even select License_Number
and Passport_Number as primary key since they are also unique.
o For each entity, selection of the primary key is based on requirement and
developers.
2. Candidate key
For example: In the EMPLOYEE table, id is best suited for the primary key. Rest
of the attributes like SSN, Passport_Number, and License_Number, etc. are
considered as a candidate key.
S.N
O Primary Key Candidate Key
5. Its confirmed that a primary key is a But Its not confirmed that a
candidate key. candidate key can be a primary
S.N
O Primary Key Candidate Key
key.
Creates non-clustered
Index Creates clustered index
index
We cannot change or
We can change unique
Modification delete values stored in
key values.
primary keys.
3. Super Key
Super key is a set of an attribute which can uniquely identify a tuple. Super key is a
superset of a candidate key.
4. Foreign key
o Foreign keys are the column of the table which is used to point to the
primary key of another table.
o In a company, every employee works in a specific department, and
employee and department are two different entities. So we can't store the
information of the department in the employee table. That's why we link
these two tables through the primary key of one table.
o We add the primary key of the DEPARTMENT table, Department_Id as a
new attribute in the EMPLOYEE table.
o Now in the EMPLOYEE table, Department_Id is the foreign key, and both
the tables are related.
Generalization
For example, Faculty and Student entities can be generalized and create a higher
level entity Person.
Specialization
For example: Center entity offers the Course entity act as a single entity in the
relationship which is in a relationship with another entity visitor. In the real world,
if a visitor visits a coaching center then he will never enquiry about the Course
only or just about the Center instead he will ask the enquiry about both.
Reduction of ER diagram to Table
The database can be represented using the notations, and these notations can be
reduced to a collection of tables.
In the database, every entity set or relationship set can be represented in tabular
form.
In the STUDENT table, Age is the derived attribute. It can be calculated at any
point of time by calculating the difference between current date and Date of Birth.
Using these rules, you can convert the ER diagram to tables and columns and
assign the mapping between the tables. Table structure for the given ER diagram is
as below:
Relationship of higher degree
1. One-to-one (1:1)
2. One-to-many (1:M)
3. Many-to-many (M:N)
1. One-to-one
2. One-to-many
3. Many-to-many
o In a many-to-many relationship, many occurrences in an entity relate to
many occurrences in another entity.
o Same as a one-to-one relationship, the many-to-many relationship rarely
exists in practice.
o For example: At the same time, an employee can work on several projects,
and a project has a team of many employees.
o Therefore, employee and project have a many-to-many relationship.
Relational Model concept
o Relational model can represent as a table with columns and rows. Each row
is known as a tuple. Each table of the column has a name or attribute.
Relational schema: A relational schema contains the name of the relation and
name of all columns or attributes.
Relational key: In the relational key, each row has one or more attributes. It can
identify the row in the relation uniquely.
1. Select Operation:
Notation: σ p(r)
Where:
Input:
σ BRANCH_NAME="perryride" (LOAN)
Output:
o This operation shows the list of those attributes that we wish to appear in the
result. Rest of the attributes are eliminated from the table.
o It is denoted by ∏.
Where
Input:
Output:
NAME CITY
Jones Harrison
Smith Rye
Hays Harrison
Curry Rye
Johnson Brooklyn
Brooks Brooklyn
3. Union Operation:
o Suppose there are two tuples R and S. The union operation contains all the
Notation: R ∪ S
Example:
DEPOSITOR RELATION
CUSTOMER_NAME ACCOUNT_NO
Johnson A-101
Smith A-121
Mayes A-321
Turner A-176
Johnson A-273
Jones A-472
Lindsay A-284
BORROW RELATION
CUSTOMER_NAME LOAN_NO
Jones L-17
Smith L-23
Hayes L-15
Jackson L-14
Curry L-93
Smith L-11
Williams L-17
Input:
Output:
CUSTOMER_NAME
Johnson
Smith
Hayes
Turner
Jones
Lindsay
Jackson
Curry
Williams
Mayes
4. Set Intersection:
o Suppose there are two tuples R and S. The set intersection operation
contains all tuples that are in both R & S.
o It is denoted by intersection ∩.
Notation: R ∩ S
Input:
Output:
CUSTOMER_NAME
Smith
Jones
5. Set Difference:
o Suppose there are two tuples R and S. The set intersection operation
contains all tuples that are in R but not in S.
o It is denoted by intersection minus (-).
Notation: R - S
Input:
Output:
CUSTOMER_NAME
Jackson
Hayes
Willians
Curry
6. Cartesian product
o The Cartesian product is used to combine each row in one table with each
row in the other table. It is also known as a cross product.
o It is denoted by X.
Notation: E X D
Example:
EMPLOYEE
1 Smith A
2 Harry C
3 John B
DEPARTMENT
DEPT_NO DEPT_NAME
A Marketing
B Sales
C Legal
Input:
EMPLOYEE X DEPARTMENT
Output:
1 Smith A A Marketing
1 Smith A B Sales
1 Smith A C Legal
2 Harry C A Marketing
2 Harry C B Sales
2 Harry C C Legal
3 John B A Marketing
3 John B B Sales
3 John B C Legal
7. Rename Operation:
ρ(STUDENT1, STUDENT)
Note: Apart from these common operations Relational algebra can be used in Join
operations.
Join Operations:
Example:
EMPLOYEE
EMP_CODE EMP_NAME
101 Stephan
102 Jack
103 Harry
SALARY
EMP_CODE SALARY
101 50000
102 30000
103 25000
Result:
1. Natural Join:
o A natural join is the set of tuples of all combinations in R and S that are
It is denoted by ⋈.
equal on their common attribute names.
o
Example: Let's use the above EMPLOYEE table and SALARY table:
Input:
Output:
EMP_NAME SALARY
Stephan 50000
Jack 30000
Harry 25000
SQL
2. Outer Join:
The outer join operation is an extension of the join operation. It is used to deal with
missing information.
Example:
EMPLOYEE
Input:
1. (EMPLOYEE ⋈ FACT_WORKERS)
Output:
o Left outer join contains the set of tuples of all combinations in R and S that
are equal on their common attribute names.
o In the left outer join, tuples in R have no matching tuples in S.
o It is denoted by ⟕.
Input:
1. EMPLOYEE ⟕ FACT_WORKERS
EMP_NAME STREET CITY BRANCH SALARY
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
o Right outer join contains the set of tuples of all combinations in R and S that
are equal on their common attribute names.
o In right outer join, tuples in S have no matching tuples in R.
o It is denoted by ⟖.
Input:
1. EMPLOYEE ⟖ FACT_WORKERS
Output:
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
o Full outer join is like a left or right join except that it contains all rows from
both tables.
o In full outer join, tuples in R that have no matching tuples in S and tuples in
S that have no matching tuples in R in their common attribute name.
o It is denoted by ⟗.
Input:
1. EMPLOYEE ⟗ FACT_WORKERS
Output:
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
3. Equi join:
Example:
CUSTOMER RELATION
CLASS_ID NAME
1 John
2 Harry
3 Jackson
PRODUCT
PRODUCT_I CITY
D
1 Delhi
2 Mumbai
3 Noida
Input:
1. CUSTOMER ⋈ PRODUCT
Output:
1 John 1 Delhi
2 Harry 2 Mumbai
3 Harry 3 Noida
Integrity Constraints
1. Domain constraints
o The entity integrity constraint states that primary key value can't be null.
o This is because the primary key value is used to identify individual rows in
relation and if the primary key has a null value, then we can't identify those
rows.
o A table can contain a null value other than the primary key field.
Example:
Example:
4. Key constraints
o Keys are the entity set that is used to identify an entity within its entity set
uniquely.
o An entity set can have multiple keys, but out of which one key will be the
primary key. A primary key can contain a unique and null value in the
relational table.
Example:
Relational Calculus
Notation:
Where
For example:
OUTPUT: This query selects the tuples from the AUTHOR relation. It returns a
tuple with 'name' from Author who has written an article on 'database'.
TRC (tuple relation calculus) can be quantified. In TRC, we can use Existential (∃)
and Universal Quantifiers (∀).
For example:
Output: This query will yield the same result as the previous one.
o It uses Existential (∃) and Universal Quantifiers (∀) to bind the variable.
Notation:
Where
a1, a2 are attributes
P stands for formula built by inner attributes
For example:
Output: This query will yield the article, page, and subject from the relational
javatpoint, where the subject is a database.
Introduction to SQL
SQL is a standard language for accessing and manipulating databases.
What is SQL?
SQL stands for Structured Query Language
SQL lets you access and manipulate databases
SQL became a standard of the American National Standards Institute
(ANSI) in 1986, and of the International Organization for Standardization
(ISO) in 1987
However, to be compliant with the ANSI standard, they all support at least the
major commands (such as SELECT, UPDATE, DELETE, INSERT, WHERE) in a
similar manner.
Note: Most of the SQL database programs also have their own proprietary
extensions in addition to the SQL standard!
RDBMS
RDBMS stands for Relational Database Management System.
RDBMS is the basis for SQL, and for all modern database systems such as MS
SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.
Example
SELECT * FROM Customers;
CHAR(size) It is used to store character data within the predefined length. It can
be stored up to 2000 bytes.
NCHAR(size) It is used to store national character data within the predefined length
It can be stored up to 2000 bytes.
VARCHAR2(size) It is used to store variable string data within the predefined length. It
can be stored up to 4000 byte.
NVARCHAR2(size) It is used to store Unicode string data within the predefined length. We
have to must specify the size of NVARCHAR2 data type. It can be
stored up to 4000 bytes.
NUMBER(p, s) It contains precision p and scale s. The precision p can range from 1 to
38, and the scale s can range from -84 to 127.
FLOAT(p) It is a subtype of the NUMBER data type. The precision p can range
from 1 to 126.
DATE It is used to store a valid date-time format with a fixed length. Its range
varies from January 1, 4712 BC to December 31, 9999 AD.
TIMESTAMP It is used to store the valid date in YYYY-MM-DD with time hh:mm:ss format.
BLOB It is used to specify unstructured binary data. Its range goes up to 2 32-1 bytes
or 4 GB.
BFILE It is used to store binary data in an external file. Its range goes up to 2 32-1
bytes or 4 GB.
CLOB It is used for single-byte character data. Its range goes up to 2 32-1 bytes or 4
GB.
NCLOB It is used to specify single byte or fixed length multibyte national character set
(NCHAR) data. Its range is up to 232-1 bytes or 4 GB.
RAW(size) It is used to specify variable length raw binary data. Its range is up to 2000
bytes per row. Its maximum size must be specified.
LONG It is used to specify variable length raw binary data. Its range up to 2 31-1 bytes
RAW or 2 GB, per row.
Syntax
CREATE DATABASE databasename;
CREATE DATABASE Example
The following SQL statement creates a database called "testDB":
Example
CREATE DATABASE testDB;
Syntax
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
The column parameters specify the names of the columns of the table.
The datatype parameter specifies the type of data the column can hold (e.g.
varchar, integer, date, etc.).
Tip: For an overview of the available data types, go to our complete Data Types
Reference.
Example
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
The new table gets the same column definitions. All columns or specific columns
can be selected.
If you create a new table using an existing table, the new table will be filled with
the existing values from the old table.
Syntax
CREATE TABLE new_table_name AS
SELECT column1, column2,...
FROM existing_table_name
WHERE ....;
The following SQL creates a new table called "TestTables" (which is a copy of
the "Customers" table):
Example
CREATE TABLE TestTable AS
SELECT customername, contactname
FROM customers;
Primary keys must contain UNIQUE values, and cannot contain NULL values.
A table can have only ONE primary key; and in the table, this primary key can
consist of single or multiple columns (fields).
MySQL:
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns, use the following SQL syntax:
A FOREIGN KEY is a field (or collection of fields) in one table that refers to the
PRIMARY KEY in another table.
The table containing the foreign key is called the child table, and the table
containing the candidate key is called the referenced or parent table.
Look at the following two tables:
"Persons" table:
1 Hansen Ola
2 Svendson Tove
3 Pettersen Kari
"Orders" table:
1 77895 3
2 44678 3
3 22456 2
4 24562 1
Notice that the "PersonID" column in the "Orders" table points to the "PersonID"
column in the "Persons" table.
The "PersonID" column in the "Persons" table is the PRIMARY KEY in the
"Persons" table.
The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders"
table.
The FOREIGN KEY constraint is used to prevent actions that would destroy links
between tables.
The FOREIGN KEY constraint also prevents invalid data from being inserted into
the foreign key column, because it has to be one of the values contained in the
table it points to.
MySQL:
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY
constraint on multiple columns, use the following SQL syntax:
MySQL:
ALTER TABLE Orders
DROP FOREIGN KEY FK_PersonOrder;
If you define a CHECK constraint on a single column it allows only certain values
for this column.
If you define a CHECK constraint on a table it can limit the values in certain
columns based on values in other columns in the row.
MySQL:
MySQL:
Example
INSERT INTO Customers (CustomerName, ContactName, Address, City,
PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen
21', 'Stavanger', '4006', 'Norway');
The selection from the "Customers" table will now look like this:
The following SQL statement will insert a new record, but only insert data in the
"CustomerName", "City", and "Country" columns (CustomerID will be updated
automatically):
Example
INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');
UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
UPDATE Table
The following SQL statement updates the first customer (CustomerID = 1) with a
new contact person and a new city.
Example
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
DELETE Syntax
DELETE FROM table_name WHERE condition;
Example
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
SELECT Syntax
SELECT column1, column2, ...
FROM table_name;
Example
SELECT CustomerName, City FROM Customers;
The WHERE clause is used to extract only those records that fulfill a specified
condition. WHERE Syntax
Example
SELECT * FROM Customers
WHERE Country='Mexico';
Order By
Order by keyword sort the result-set either in ascending or descending order. This clause
sorts the result set in ascending order by default. In order to sort the result-set in
descending order DESC keyword is used.
Syntax
FROM Table_Name
Query
It sorts the records automatically in ascending order if we want to show the records in
descending order then we use DESC.
Output
Group By
Group by statement is used to group the rows that have the same value. It is used with
aggregate functions for example AVG(), COUNT(), SUM()etc. One thing is to remember
about the group by clause that the tuples are grouped based on the similarity between the
attribute values of tuples.
Syntax
FROM Table_Name
WHERE condition
Query
The COUNT() function is used when we need to return the total number of rows that are
stored in the database.So the example for the COUNT() function is
Output
SQL | Subquery
n SQL a Subquery can be simply defined as a query within another query. In other words
we can say that a Subquery is a query that is embedded in WHERE clause of another SQL
query. Important rules for Subqueries:
In SQL a Subquery can be simply defined as a query within another query. In other
words we can say that a Subquery is a query that is embedded in WHERE clause of
another SQL query. Important rules for Subqueries:
A subquery is a query within another query. The outer query is called as main
query and inner query is called as subquery.
The subquery generally executes first when the subquery doesn’t have any co-
relation with the main query, when there is a co-relation the parser takes the
decision on the fly on which query to execute on precedence and uses the output of
the subquery accordingly.
Syntax: There is not any general syntax for Subqueries. However, Subqueries are
seen to be used most frequently with SELECT statement as shown below:
SELECT column_name
FROM table_name
A view contains rows and columns, just like a real table. The fields in a view are fields from
one or more real tables in the database.
The following SQL creates a view that shows all customers from Brazil:
3. Implicit Cursors: Implicit Cursors are also known as Default Cursors of SQL
SERVER. These Cursors are allocated by SQL SERVER when the user performs
DML operations.
4. Explicit Cursors: Explicit Cursors are Created by Users whenever the user requires
them. Explicit Cursors are used for Fetching data from Table in Row-By-Row
Manner.
5. DECLARE
6. total_rows number;
7. BEGIN
8. UPDATE Emp
9. SET Salary = Salary + 1500;
10.
11. total_rows := SQL%ROWCOUNT;
12.
13. dbms_output.put_line(total_rows || ' rows updated.');
14. END;
SQL Trigger
A trigger is a stored procedure in a database that 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 specific table columns are updated. In simple words, a trigger
is a collection of SQL statements with particular names that are stored in system memory.
It belongs to a specific class of stored procedures that are automatically invoked in
response to database server events. Every trigger has a table attached to it.
1. The following are the key differences between triggers and stored procedures:
4. Syntax:
6. [before | after]
10. [trigger_body]