Unit 2
Unit 2
INTRODUCTION:
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: A relation is usually represented as a table, organized into rows
and columns. A relationship consists of multiple records. For example:
student relation which contains tuples and attributes.
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.
Domain: It contains a set of atomic values that an attribute can take. It could be
accomplish explicitly by listing all possible values or specifying conditions that all
values in that domain must be confirmed. For example: the domain of gender
attributes is a set of data values "M" for male and "F" for female.
Attribute: The smallest unit of data in relational model is an attribute. It contains the
name of a column in a particular table. Each attribute Ai must have a domain,
dom(Ai)
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 predefined value scope, known as attribute
domain.
Properties of Relations
○ Each attribute in a relation has only one data value corresponding to it i.e. they
do not contain two or more values.
○ Keys on relation
KEYS:
➢ In relational model the Keys are important because they are used to ensure that each
row in a table is uniquely identifiable. These keys are also used to establish relationships
among tables and to ensure the integrity of the data.
➢ A key consists of one or more attributes that determines other attributes.
.
Alternate Key
The candidate key other than the primary key is called an alternate key .
● All the keys which are not primary keys are called alternate keys.
● It is a secondary key.
● It contains two or more fields to identify two or more records.
● These values are repeated.
Composite key
Primary Key
A primary key is used to ensure that data in the specific column is unique.
A column cannot have NULL values.
An entity can contain multiple keys, as we saw in the PERSON table.
The key which is most suitable from those lists becomes a primary key
SQL syntax:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY(ID,LastName)
);
Foreign Key
A foreign key is a column or group of columns in a relational database table that
provides a link between data in two tables. It is a column (or columns) that references a
Rename(ρ):
Rename operator is used to give another name to a relation.
• Syntax: ρ(Relation2, Relation1)
To rename STUDENT relation to STUDENT1,
• we can use rename operator like:
• ρ(STUDENT1, STUDENT)
Set operations:
Union Operation:
Union (U): UNION is symbolised by ∪ symbol. It includes all tuples that are in
tables A or in B. It also eliminates duplicate tuples.
column
column1 column2 column1
2
1 1 1 3
1 2 1 1
o/p: r1 U r2
column 1 column 2
1 1
1 2
1 3
Set Intersection:
Suppose there are two tuples R and S. The set intersection operation contains all
tuples that are in both R & S.
It is denoted by intersection ∩.
Notation: R ∩ S
Ex:
r1(table1) r2(table2)
Table r1– r2
column 1 column 2
1 1
Set Difference (-)
• – Symbol denotes it. The result of A – B, is a relation which includes all
tuples that are in A but not in B.
• Ex:
•
Table r1 – r2
column 1 column 2
1 2
detail
ROLLNO AGE
5 18
9 21
• STUDENT x DETAIL
SNO FNAME LNAME ROLLNO AGE
1 AB EF 5 18
1 AB EF 9 21
2 CD GH 5 18
2 CD GH 9 21
Joins in relational algebra
Join is an operation inDBMS that combines the row of two or more tables based on
related columns between them. The main purpose of Join is to retrieve the data from
multiple tables . It is denoted by ⨝.
TYPES:
Inner join—--Natural join,Theta join,Equi join
Outer join—--Left Outer Join,Right Outer Join,Full Outer Join
Inner Join
Natural Join:A natural join is the set of tuples of all combinations in R and S that are
equal on their common attribute names.It is denoted by ⋈.
A ⋈ column = column B
Outer Join
An Outer Join doesn’t require each record in the two join tables to have a
matching record. In this type of join, the table retains each record even if
no other matching record exists.
Three types of Outer Joins are:
Right Outer Join returns all the columns from the table on the right even if no matching
rows have been found in the table on the left. Where no matches have been found in the table
on the left, NULL is returned. RIGHT outer JOIN is the opposite of LEFT JOIN
SY: RELATION1 RELATION 2
EX: A B
In a Full Outer Join , all tuples from both relations are included in the result, irrespective of
the matching condition.
SY:SY: RELATION1 RELATION 2
EX:A B
TOPIC:Relational calculus
Relational calculus is a non-procedural query language, and instead of algebra, it uses
mathematical predicate calculus.
• The relational calculus is not the same as that of differential and integral calculus in
mathematics but takes its name from a branch of symbolic logic termed as predicate
calculus.
• When applied to databases, it is found in two forms. These are
• Tuple relational calculus(TRC)
• Domain relational calculus(DRC)
• 'ex:Find the staffNo, fName, lName, position, DOB, salary, and branchNo of all staff earning
more than £10,000’,
NOTE :To specify the range of a tuple variable S as the Staff relation
LOGICALLY AND ,OR NOT
{S | Staff(S) ∧ S.salary > 10000
where a1,a2,…an are the attributes of the relation and P is the condition.
Find the loan number, branch, and amount of loans greater than or equal
to 10000 amount.
{t.loan number,branch,amount| t ∈ loan ∧ t[amount]>=10000}
TOPIC:CONSTRAINT(key,domain,integrity,enti
ty constraints)
Constraints in SQL means we are applying certain conditions or restrictions on
the database
Constraints in SQL can be categorized into two :
1. Column Level Constraint:
Column Level Constraint is used to apply a constraint on a single column.
2. Table Level Constraint:
Table Level Constraint is used to apply a constraint on multiple columns.
The constraint is a mechanism used by oracle to prevent invalid data into the table
Domain Constraints
Domain Constraints are user-defined columns that help the user to enter
the value according to the data type.
Types:
1. NOT NULL:
we know that by default all the columns in a table allow null values. When aNOT
NULL constraint is enforced through either on a column or a set of columns in a
table, it will not allow null values.
Adding a constraint at the time of table creation:
sy:CREATE TABLE TableName (ColumnName1 datatype NOT NULL,
ColumnName2 datatype,…., ColumnNameN datatype);
ex:create table stu1(sno number(5) constraint nn1 not null, name char(10) not null,
address varchar2(10) not null);
2. Dropping a Constraint
ALTER TABLE stu1 DROP CONSTRAINT nn1;
2. CHECK:
The check constraint specifies condition that each row must satisfy. These rules are
formed by logical expressions or Boolean expression.
Sy:CREATE TABLE TableName (ColumnName1 datatype CHECK
(ColumnName1 Condition), ColumnName2 datatype,…., ColumnNameN
datatype);
3. DEFAULT:
When a row is inserted, it is not necessary that value for every column should not be
inserted. SQL offers the provision to specify default values for columns.
sy:CREATE TABLE TableName (ColumnName1 datatype DEFAULT Value,
ColumnName2 datatype,…., ColumnNameN datatype);
2. PRIMARY KEY:
Primary Key is a field which uniquely identifies each row in the table.
The primary key constraint avoids duplication of rows and does not allow null
values.
A table can have only one primary key.
If a primary key constraint is assigned to a combination of columns. It is said to be
a composite primary key which contains a maximum of 16 columns.
PRIMARY KEY Constraint is a combination of NOT NULL and Unique
constraints.
ex:create table stu3(sno number(5) constraint pk1 primary key, name char(10));
To add a constraint:
ALTER TABLE TableName ADD PRIMARY KEY (ColumnName);
ex:
alter table stu3 add primary key(name);
ex:1. CREATE TABLE employee (Emp_ID INT PRIMARY KEY, Emp_Name VARCHAR
(40), Emp_Salary VARCHAR (40));
Topic:Basic sql
Introduction to SQL, Advanced SQL
o SQL stands for Structured Query Language. It is used for storing and managing data
in relational database management system (RDMS). o It is a standard language for
Relational Database System. It enables a user to create, read, update and delete
relational databases and tables.
o All the RDBMS like MySQL, Informix, Oracle, MS Access and SQL Server use SQL
as their standard database language.
o SQL allows users to query the database in a number of ways, using English-like
statements.
Rules:
o Structure query language is not case sensitive. Generally, keywords of SQL are
written in uppercase. o Statements of SQL are dependent on text lines. We can use a
single SQL statement on one or multiple text line.
o Using the SQL statements, you can perform most of the actions in a database. o
SQL depends on tuple relational calculus and relational algebra.
SQL process:
o When an SQL command is executing for any RDBMS, then the system figure out the
best way to carry out the request and the SQL engine determines that how to interpret
the task.
o In the process, various components are included. These components can be
optimization Engine, Query engine, Query dispatcher, classic, etc.
o All the non-SQL queries are handled by the classic query engine, but SQL query
engine won't handle logical files.
Characteristics of SQL
systems. O
SQL can execute queries against the database. o SQL is used to describe
the data.
o SQL is used to define the data in the database and manipulate it when
needed.
where P;
Consider that we have a relation ‘instructor’ with the attributes instr_id, name,
dept_name, and salary. Now we want the names of all the instructors along with their
corresponding department names.
The SQL query we would structure to get a result relation with instructor’s names along
with their department name. select name from instructor;
The SQL queries often need to access multiple relations from the data set in order to get the
required result. Let us take an example we have two relations instructor and department.
Now, if you want to retrieve the names of all the instructors along with their department
names and the corresponding department building. We will get the instructor’s name and
department name in the instructor relation but building name in the department relation. So
the query would be:
select name, instructor.dept_name, building
Here department name of each tuple of instructor relation will be matched with the
department name of each tuple of department relation.
SYNTAX :
Removing column from existing table –
ALTER TABLE tableName DROP COLUMN columnName;
Example –
ALTER TABLE Student
It is a Data Manipulation
It is a Data Definition Language (DDL).
Language (DML).
***Topic:SQL COMMANDS
SQL contains different types of commands
DDL (Data Definition Language) Commands
DML(Data Manipulation Language) Commands
TCL(Transaction Control Language) Commands
DCL(Data Control Language) Commands
The Data Definition Languages (DDL) Commands are used to create a table structure,
modify the table structure and delete the table structure.
DDL changes the structure of the table like creating a table, deleting a table, altering a table,
etc.
All the command of DDL are auto-committed that means it permanently save all the changes
in the database.
I) DDL Commands:
1. CREATE TABLE
The CREATE TABLE command is used to create a new table
Syntax: CREATE TABLEtablename (column_name1 data_ type (size)
constraint, column_name2 data_ type (size) constraints, …);
Example:
create table student (sname varchar2(20) , rollno number(10) ,dob date );
create table student (sname varchar2(20) not null, rollno number(10) not null,dob date );
3. DROP:
This command is used to delete the structure of the table as well as
records in the relation.
Syntax :DROP TABLEtable_name;
Ex: drop table student;
4.RENAME
RENAME command is used to rename the table.
Rename old table name to new table name
EX: Rename student to student1;
6.TRUNCATING TABLE:
Truncate command will delete all the records permanently in a specified table but
structure of the table will not be deleted.
– Syntax: TRUNCATE TABLE TableName;
Eg:TRUNCATE TABLE student;
II COMMANDS IN DML:
○ DML commands are used to modify the database. It is responsible
for all form of changes in the database.
○ The command of DML is not auto-committed that means it can't
permanently save all the changes in the database. They can be
rollback.
DCL COMMANDS:
DCL commands are used to grant and take back authority from any
database user.
Two types of DCL commands are
1. Grant
2. Revoke
1. GRANT
SQL Grant command is used to grant a privileges on the database
objects to the users. The syntax for the GRANT command is:
GRANT privilege_name ON object_name TO user_name ;
Here, privilege_name: is the access right or privilege granted to the user.
object_name: is the name of the database object like table, view etc.,
user_name: is the name of the user
(a) GRANT SELECT ON employee TO user1 ;
This command grants a SELECT permission on employee table to user1.
(b) GRANTSELECT, INSERT, UPDATE, DELETEONemployee TOSCOTT;
The above statement will GRANT SELECT, INSERT, UPDATE and DELETE privileges to
SCOTT user on employee table.
2. REVOKE
The revoke command removes user privileges to the database objects.
• The syntax for the REVOKE command is:
REVOKE privilege_name ON object_name FROM User_name ;
For Example:
REVOKE SELECT ON employee FROM user1;
This command will revoke a SELECT privilege on employee table from user1.
Suppose we want to revoke SELECT, INSERT, UPDATE and DELETE privileges from
‘SCOTT’ user on employee table, then we have to execute the following statement;
REVOKE SELECT,INSERT,UPDATE,DELETE ON employee FROM SCOTT;
TCL COMMANDS
Transaction Control (TCL) statements are used to manage the changes made
by DML statements.
•1.COMMIT - To make the changes permanent in the database .The
COMMIT command saves all the transactions to the database since the
last COMMIT or ROLLBACK command.
Syntax:
COMMIT;
2. SAVEPOINT - saving point in a transaction to which you can later roll back .creates
points within the groups of transactions in which to ROLLBACK. A SAVEPOINT is
a point in a transaction in which you can roll the transaction back to a certain point
without rolling back the entire transaction.
SAVEPOINT SAVEPOINT_NAME;
3 ROLLBACK - Restore database to original since the last COMMIT.If any error occurs
with any of the SQL grouped statements, all changes need to be aborted. The process
of reversing changes is called rollback. This command can only be used to undo
transactions since the last COMMIT or ROLLBACK command was issued
sy:ROLLBACK;