Relational Model Concepts and SQL Operations
Relational Model Concepts and SQL Operations
1
Order of tuple can have a different sequence
Relational Algebra
Relational algebra is a procedural query language. It gives a step by step process to obtain the
result of the query. It uses operators to perform queries.
Types of Relational operation
1. Select Operation:
The select operation selects tuples that satisfy a given predicate.
It is denoted by sigma (σ).
Notation: σ p(r)
Where: σ is used for selection prediction
r is used for relation
p is used as a propositional logic formula which may use connectors like: AND OR and NOT.
These relational can use as relational operators like =, ≠, ≥, <, >, ≤.
Input:
2
σ BRANCH_NAME="perryride" (LOAN)
Output:
NAME CITY
Jones Harrison
Smith Rye
Hays Harrison
Curry Rye
Johnson Brooklyn
Brooks Brooklyn
3. Union Operation:
Suppose there are two tuples R and S. The union operation contains all the tuples that are
either in R or S or both in R & S.
3
It eliminates the duplicate tuples. It is denoted by ∪.
Notation: R ∪ S
A union operation must hold the following condition:
R and S must have the attribute of the same number.
Duplicate tuples are eliminated automatically.
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:
CUSTOMER_NAME
Johnson
Smith
Hayes
4
Turner
Jones
Lindsay
Jackson
Curry
Williams
Mayes
4. 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
Example: Using the above DEPOSITOR table and BORROW table
Input:
∏ CUSTOMER_NAME (BORROW) ∩ ∏ CUSTOMER_NAME (DEPOSITOR)
Output:
CUSTOMER_NAME
Smith
Jones
5. Set Difference:
Suppose there are two tuples R and S. The set intersection operation contains all tuples that are
in R but not in S. It is denoted by intersection minus (-).
Notation: R - S
Example: Using the above DEPOSITOR table and BORROW table
Input:
∏ CUSTOMER_NAME (BORROW) - ∏ CUSTOMER_NAME (DEPOSITOR)
Output:
CUSTOMER_NAME
Jackson
Hayes
Williams
Curry
5
6. Cartesian product
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. It is denoted by X.
Notation: E X D
Example:
EMPLOYEE
DEPARTMENT
DEPT_NO DEPT_NAME
A Marketing
B Sales
C Legal
Input:
EMPLOYEE X DEPARTMENT
Output:
6
Example: We can use the rename operator to rename STUDENT relation to STUDENT1.
ρ (STUDENT1, STUDENT)
8. Join Operations:
Example:
EMPLOYEE
EMP_CODE EMP_NAME
101 Stephan
102 Jack
103 Harry
SALARY
EMP_CODE SALARY
101 50000
102 30000
103 25000
7
1. Natural Join:
Example: Let's use the above EMPLOYEE table and SALARY table:
Output:
EMP_NAME SALARY
Stephan 50000
Jack 30000
Harry 25000
.
2. Outer Join:
The outer join operation is an extension of the join operation. It is used to deal with missing
information
Example:
EMPLOYEE
8
Shyam Park street Kolkata
Ravi M.G. Street Delhi
Hari Nehru nagar Hyderabad
FACT_WORKERS
Output:
Left outer join contains the set of tuples of all combinations in R and S that are equal on
their common attribute names.
It is denoted by ⟕.
In the left outer join, tuples in R have no matching tuples in S.
It is denoted by ⟖.
In right outer join, tuples in S have no matching tuples in R.
Example: Using the above EMPLOYEE table and FACT_WORKERS Relation
It is denoted by ⟗.
no matching tuples in R in their common attribute name.
Example:
Using the above EMPLOYEE table and FACT_WORKERS table
Output:
10
3. Equi join:
It is also known as an inner join. It is the most common join. It is based on matched data as per
the equality condition. The equi join uses the comparison operator (=).
Example:
CUSTOMER RELATION
CLASS_ID NAME
1 John
2 Harry
3 Jackson
PRODUCT
PRODUCT_ID CITY
1 Delhi
2 Mumbai
Output:
Relational Calculus
In contrast to Relational Algebra, Relational Calculus is a non-procedural query language, that is,
it tells what to do but never explains how to do it.
11
1. Tuple Relational Calculus (TRC)
It is a non-procedural query language which is based on finding a number of tuple variables also
known as range variable for which predicate holds true.
It describes the desired information without giving a specific procedure for obtaining that
information. The tuple relational calculus is specified to select the tuples in a relation.
In TRC, filtering variable uses the tuples of a relation. The result of the relation can have one or
more tuples.
Notation:
A Query in the tuple relational calculus is expressed as following notation
{T | P (T)} or {T | Condition (T)}
Where
T is the resulting tuples
P(T) is the condition used to fetch T.
For example:
{[Link] | Author(T) AND [Link] = 'database' }
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 (∀).
Universal Quantifiers: The universal quantifier denoted by ∀ is read as for all which means
that in a given set of tuples exactly all tuples satisfy a given condition.
12
Existential Quantifiers: The existential quantifier denoted by ∃ is read as for all which means
that in a given set of tuples there is at least one occurrences whose value satisfy a given
condition.
For example:
It uses Existential (∃) and Universal Quantifiers (∀) to bind the variable. The QBE or Query by
example is a query language related to domain relational calculus.
Notation: { a1, a2, a3, ..., an | P (a1, a2, a3, ... ,an)}
Where
a1, a2 are attributes
P stands for formula built by inner attributes
For example: {< article, page, subject > | ∈ javatpoint ∧ subject = 'database'}
Output: This query will yield the article, page, and subject from the relational javatpoint, where
the subject is a database.
CONSTRAINTS
Constraints enforce limits to the data or type of data that can be inserted/updated/deleted from a
table.
The whole purpose of constraints is to maintain the data integrity during an update/delete/insert
into a table.
Types of constraints
NOT NULL
UNIQUE
DEFAULT
CHECK
13
Key Constraints – PRIMARY KEY, FOREIGN KEY
Domain constraints
Mapping constraints
NOT NULL:
NOT NULL constraint makes sure that a column does not hold NULL value. When we don’t
provide value for a particular column while inserting a record into a table, it takes NULL value
by default.
By specifying NULL constraint, we can be sure that a particular column(s) cannot have NULL
values.
Example:
CREATE TABLE STUDENT (ROLL_NO INT NOT NULL, STU_NAME VARCHAR (35) NOT
NULL, STU_AGE INT NOT NULL, STU_ADDRESS VARCHAR (235), PRIMARY KEY
(ROLL_NO));
After this STU_ADDRESS column will not accept any null values.
UNIQUE:
UNIQUE Constraint enforces a column or set of columns to have unique values. If a column has
a unique constraint, it means that particular column cannot have duplicate values in a table.
CREATE TABLE STUDENT (ROLL_NO INT NOT NULL, STU_NAME VARCHAR (35) NOT
NULL UNIQUE, STU_AGE INT NOT NULL, STU_ADDRESS VARCHAR (35) UNIQUE,
MySQL:
CREATE TABLE STUDENTS (ROLL_NO INT NOT NULL, STU_NAME VARCHAR (35)
NOT NULL, STU_AGE INT NOT NULL, STU_ADDRESS VARCHAR (35),
UNIQUE(STU_NAME), PRIMARY KEY (ROLL_NO));
14
CREATE TABLE STUDENTS (ROLL_NO INT NOT NULL, STU_NAME VARCHAR (35) NOT
NULL, STU_AGE INT NOT NULL, STU_ADDRESS VARCHAR (35), CONSTRAINT stu_Info
UNIQUE (STU_NAME, STU_ADDRESS), PRIMARY KEY (ROLL_NO));
Syntax:
Example:
Syntax:
Example:
IN MySQL:
syntax:
Example:
Syntax:
15
ALTER TABLE <table_name>
Example:
DEFAULT:
The DEFAULT constraint provides a default value to a column when there is no value provided while
inserting a record into a table.
CREATE TABLE STUDENT (ROLL_NO INT NOT NULL, STU_NAME VARCHAR (35) NOT
NULL, STU_AGE INT NOT NULL, EXAM_FEE INT DEFAULT 10000, STU_ADDRESS
VARCHAR (35), PRIMARY KEY (ROLL_NO));
What if we want to set this constraint on an already existing table? For this we can ALTER Table
statement like this:
Syntax:
Example:
In the above sections, we have learnt the ways to set Constraint. Here we will see how to drop (delete) a
Constraint:
Syntax:
Example:
Let’s say we want to drop the constraint from STUDENTS table, which we have created in the above
sections. We can do it like this.
16
ALTER COLUMN EXAM_FEE DROP DEFAULT;
CHECK:
This constraint is used for specifying range of values for a particular column of a table. When this
constraint is being set on a column, it ensures that the specified column must have the value falling in the
specified range.
CREATE TABLE STUDENT (ROLL_NO INT NOT NULL CHECK (ROLL_NO >1000),
STU_NAME VARCHAR (35) NOT NULL, STU_AGE INT NOT NULL, EXAM_FEE INT
DEFAULT 10000, STU_ADDRESS VARCHAR (35), PRIMARY KEY (ROLL_NO));
In the above example we have set the check constraint on ROLL_NO column of STUDENT table. Now,
the ROLL_NO field must have the value greater than 1000.
KEY CONSTRAINTS:
PRIMARY KEY:
Primary key uniquely identifies each record in a table. It must have unique values and cannot contain
nulls. In the below example the ROLL_NO field is marked as primary key, that means the ROLL_NO
field cannot have duplicate and null values.
CREATE TABLE STUDENT (ROLL_NO INT NOT NULL, STU_NAME VARCHAR (35) NOT
NULL UNIQUE, STU_AGE INT NOT NULL, STU_ADDRESS VARCHAR (35) UNIQUE,
PRIMARY KEY (ROLL_NO));
FOREIGN KEY:
Foreign keys are the columns of a table that points to the primary key of another table. They act as a
cross-reference between tables.
17
1. Domain constraints
Domain constraints can be defined as the definition of a valid set of values for an attribute.
The data type of domain includes string, character, integer, time, date, currency, etc. The value
of the attribute must be available in the corresponding domain.
Example:
18
3. Referential Integrity Constraints
A referential integrity constraint is specified between two tables.
In the Referential integrity constraints, if a foreign key in Table 1 refers to the Primary Key of
Table 2, then every value of the Foreign Key in Table 1 must be null or be available in Table 2.
Example:
4. Key constraints
Keys are the entity set that is used to identify an entity within its entity set uniquely.
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:
19
SQL
SQL is the Structured Query Language used to store, manipulate, and retrieve data present in a
database server.
MySQL is a relational database management system. It supports large databases and is
customizable. This article will discuss the important commands in SQL.
SQL Commands
SQL commands are instructions that are used to communicate with the database. It is used to
perform specific tasks, work, and functions with data in the database.
Types of SQL Commands
There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.
20
Here are some SQL commands that come under DML:
INSERT
UPDATE
DELETE
1. INSERT
INSERT command is used to insert new rows or records in a table.
Syntax:
INSERT INTO TABLE_NAME (column1, column2, column3...columnN) VALUES (value1,
value2, value3...valueN);
Example:
INSERT INTO Employees (Emp_Id, Emp_Name) VALUES (04, “Sam Tully”);
2. UPDATE
This command is used to update or modify the value of a column in the table.
Syntax:
UPDATE table_name SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
Example:
UPDATE Employees
SET Salary = 1000
WHERE Emp_Id = 04;
The above code will modify the salary of the employee with Emp_ID= 04;
3. DELETE
DELETE is used for removing one or more rows from the table.
Syntax:
DELETE FROM TableName WHERE Condition;
Example:
DELETE FROM Employees WHERE Emp_Id = 04;
This will delete the record of the Employees whose Emp_ID is 4.
21
2.4 Data Definition Language
Data Definition Language helps you to define the database structure or schemas. DDL
commands are capable of creating, deleting, and modifying data.
some commands that come under DDL:
CREATE
ALTER
DROP
TRUNCATE
1. CREATE
It is used to create a new table in the database.
Syntax:
CREATE TABLE Table Name (Column1 datatype, Column2 datatype, Column3
datatype,ColumnN datatype);
Example:
CREATE TABLE Employees {
Emp_Id int(3), Emp_Name varchar (20) };
This will create a table Employees with Emp_ID and Emp_Name.
2. ALTER
Alter is used to alter the structure of the database.
Syntax:
ALTER TABLE TableName ADD ColumnName Datatype;
ALTER TABLE TableName DROP COLUMN ColumnName;
Example:
ALTER TABLE Employees ADD BloodGroup varchar (255);
This will add a column Blood Group to the existing table Employees.
ALTER TABLE Employees DROP BloodGroup varchar (255);
This will drop the column Blood Group from the existing table.
3. DROP
It is used to delete both the structure and record in the table.
22
Syntax:
DROP TABLE TableName;
Example:
DROP TABLE Employees;
This SQL command will remove the table structure along with its data from the database.
4. TRUNCATE
This truncate command is used to delete all the rows from the table and free the space.
Syntax:
TRUNCATE TABLE TableName;
Example:
TRUNCATE TABLE Employees;
23
a. Commit: Commit command is used to save all the transactions to the database.
Syntax:
COMMIT;
Example:
DELETE FROM CUSTOMERS
WHERE AGE = 25;
COMMIT;
b. Rollback: Rollback command is used to undo transactions that have not already been saved to
the database.
Syntax:
ROLLBACK;
Example:
DELETE FROM CUSTOMERS
WHERE AGE = 25;
ROLLBACK;
c. Save point: It is used to roll the transaction back to a certain point without rolling back the
entire transaction.
Syntax:
SAVEPOINT SAVEPOINT_NAME;
5. Data Query Language
DQL is used to fetch the data from the database.
It uses only one command:
SELECT
a. SELECT: This is the same as the projection operation of relational algebra. It is used to select
the attribute based on the condition described by WHERE clause.
Syntax:
SELECT expressions FROM TABLES WHERE conditions;
For example:
24
SELECT emp_name FROM employee WHERE age > 20;
SQL Operator
There are various types of SQL operator:
- It is used to subtract the right-hand operand from the left-hand a-b will give 10
operand.
* It is used to multiply the value of both operands. a*b will give 200
/ It is used to divide the left-hand operand by the right-hand a/b will give 2
operand.
% It is used to divide the left-hand operand by the right-hand a%b will give 0
operand and returns reminder.
SQL Comparison Operators:
Let's assume 'variable a' and 'variable b'. Here, 'a' contains 20 and 'b' contains 10.
= It checks if two operands values are equal or not, if the values are queal (a=b) is not
then condition becomes true. true
25
!= It checks if two operands values are equal or not, if values are not equal, (a!=b) is true
then condition becomes true.
<> It checks if two operands values are equal or not, if values are not equal (a<>b) is true
then condition becomes true.
> It checks if the left operand value is greater than right operand value, if yes (a>b) is not
then condition becomes true. true
< It checks if the left operand value is less than right operand value, if yes (a<b) is true
then condition becomes true.
>= It checks if the left operand value is greater than or equal to the right (a>=b) is not
operand value, if yes then condition becomes true. true
<= It checks if the left operand value is less than or equal to the right operand (a<=b) is true
value, if yes then condition becomes true.
!< It checks if the left operand value is not less than the right operand value, if (a!=b) is not
yes then condition becomes true. true
!> It checks if the left operand value is not greater than the right operand (a!>b) is true
value, if yes then condition becomes true.
Operator Description
BETWEEN It is used to search for values that are within a set of values.
26
LIKE It compares a value to similar values using wildcard operator.
27
Following is an example to create a view from the CUSTOMERS table. This view would be
used to have customer name and age from the CUSTOMERS table.
SQL > CREATE VIEW CUSTOMERS_VIEW AS
SELECT name, age FROM CUSTOMERS;
Now, you can query CUSTOMERS_VIEW in a similar way as you query an actual table.
Following is an example for the same.
SQL > SELECT * FROM CUSTOMERS_VIEW;
This would produce the following result.
NAME AGE
Ramesh 32
Khilan 25
kaushik 23
Chaitali 25
Hardik 27
Komal 22
Muffy 24
28
The SELECT clause may not contain the keyword DISTINCT.
The SELECT clause may not contain summary functions.
The SELECT clause may not contain set functions.
The SELECT clause may not contain set operators.
The SELECT clause may not contain an ORDER BY clause.
The FROM clause may not contain multiple tables.
The WHERE clause may not contain subqueries.
The query may not contain GROUP BY or HAVING.
Calculated columns may not be updated.
All NOT NULL columns from the base table must be included in the view in order for
the INSERT query to function.
So, if a view satisfies all the above-mentioned rules then you can update that view. The
following code block has an example to update the age of Ramesh.
SQL > UPDATE CUSTOMERS_VIEW SET AGE = 35 WHERE name = 'Ramesh';
This would ultimately update the base table CUSTOMERS and the same would reflect in the
view itself. Now, try to query the base table and the SELECT statement would produce the
following result.
6 Komal 22 MP 4500.00
29
Deleting Rows into a View
Rows of data can be deleted from a view. The same rules that apply to the UPDATE and
INSERT commands apply to the DELETE command.
Following is an example to delete a record having AGE = 22
SQL > DELETE FROM CUSTOMERS_VIEW WHERE age = 22;
This would ultimately delete a row from the base table CUSTOMERS and the same would
reflect in the view itself. Now, try to query the base table and the SELECT statement would
produce the following result.
Dropping Views
Obviously, where you have a view, you need a way to drop the view if it is no longer needed.
The syntax is very simple and is given below −
DROP VIEW view_name;
Following is an example to drop the CUSTOMERS_VIEW from the CUSTOMERS table.
DROP VIEW CUSTOMERS_VIEW;
30
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
What Can SQL do?
SQL can execute queries against a database
SQL can retrieve data from a database
SQL can insert records in a database
SQL can update records in a database
SQL can delete records from a database
SQL can create new databases
SQL can create new tables in a database
SQL can create stored procedures in a database
SQL can create views in a database
SQL can set permissions on tables, procedures, and views
SQL is a Standard - BUT....
Although SQL is an ANSI/ISO standard, there are different versions of the SQL language.
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.
Using SQL in Your Web Site
To build a web site that shows data from a database, you will need:
An RDBMS database program (i.e. MS Access, SQL Server, MySQL)
To use a server-side scripting language, like PHP or ASP
To use SQL to get the data you want
To use HTML / CSS to style the page
RDBMS
RDBMS stands for Relational Data Base 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.
The data in RDBMS is stored in database objects called tables. A table is a collection of related
data entries and it consists of columns and rows.
Example
31
SELECT * FROM Customers;
Every table is broken up into smaller entities called fields. The fields in the Customers table
consist of Customer ID, Customer Name, Contact Name, Address, City, Postal Code and
Country. A field is a column in a table that is designed to maintain specific information about
every record in the table.
A record, also called a row, is each individual entry that exists in a table. For example, there are
91 records in the above Customers table. A record is a horizontal entity in a table.
A column is a vertical entity in a table that contains all information associated with a specific
field in a table.
32