Understanding Relational Database Models
Understanding Relational Database Models
STUDENT
4 SURESH DELHI 18
Attribute: Attributes are the properties that define a relation. e.g.; ROLL_NO, NAME
Relation Schema: A relation schema represents name of the relation with its attributes. e.g.;
STUDENT (ROLL_NO, NAME, ADDRESS, PHONE and AGE) is relation schema for
STUDENT. If a schema has more than 1 relation, it is called Relational Schema.
Tuple: Each row in the relation is known as tuple. The above relation contains 4 tuples, one of
which is shown as:
Relation Instance: The set of tuples of a relation at a particular instance of time is called as
relation instance. Table 1 shows the relation instance of STUDENT at a particular time. It can
change whenever there is insertion, deletion or updation in the database.
Degree: The number of attributes in the relation is known as degree of the relation.
The STUDENT relation defined above has degree 5.
Cardinality: The number of tuples in a relation is known as cardinality. The STUDENT relation
defined above has cardinality 4.
Column: Column represents the set of values for a particular attribute. The
column ROLL_NO is extracted from relation STUDENT.
NULL Values: The value which is not known or unavailable is called NULL value. It is
represented by blank space. e.g.; PHONE of STUDENT having ROLL_NO 4 is NULL.
Constraints in Relational Model
While designing Relational Model, we define some conditions which must hold for data present in
database are called Constraints. These constraints are checked before performing any operation
(insertion, deletion and updation) in database. If there is a violation in any of constrains, operation
will fail.
Domain Constraints: These are attribute level constraints. An attribute can only take values
which lie inside the domain range. e.g,; If a constrains AGE>0 is applied on STUDENT relation,
inserting negative value of AGE will result in failure.
Key Integrity: Every relation in the database should have atleast one set of attributes which
defines a tuple uniquely. Those set of attributes is called key. e.g.; ROLL_NO in STUDENT is a
key. No two students can have same roll number. So a key has two properties:
It should be unique for all tuples.
It can’t have NULL values.
Referential Integrity: When one attribute of a relation can only take values from other attribute of
same relation or any other relation, it is called referential integrity. Let us suppose we have 2
relations
STUDENT
4 SURESH DELHI 18 IT
BRANCH_CODE of STUDENT can only take the values which are present in BRANCH_CODE of
BRANCH which is called referential integrity constraint. The relation which is referencing to other
relation is called REFERENCING RELATION (STUDENT in this case) and the relation to which
other relations refer is called REFERENCED RELATION (BRANCH in this case).
ANOMALIES
An anomaly is an irregularity, or something which deviates from the expected or normal state.
When designing databases, we identify three types of anomalies: Insert, Update and Delete.
Insertion Anomaly in Referencing Relation:
We can’t insert a row in REFERENCING RELATION if referencing attribute’s value is not present
in referenced attribute value. e.g.; Insertion of a student with BRANCH_CODE ‘ME’ in STUDENT
relation will result in error because ‘ME’ is not present in BRANCH_CODE of BRANCH.
Deletion/ Updation Anomaly in Referenced Relation:
We can’t delete or update a row from REFERENCED RELATION if value of REFERENCED
ATTRIBUTE is used in value of REFERENCING ATTRIBUTE. e.g; if we try to delete tuple from
BRANCH having BRANCH_CODE ‘CS’, it will result in error because ‘CS’ is referenced by
BRANCH_CODE of STUDENT, but if we try to delete the row from BRANCH with
BRANCH_CODE CV, it will be deleted as the value is not been used by referencing relation. It can
be handled by following method:
ON DELETE CASCADE: It will delete the tuples from REFERENCING RELATION if value used
by REFERENCING ATTRIBUTE is deleted from REFERENCED RELATION. e.g;, if we delete a
row from BRANCH with BRANCH_CODE ‘CS’, the rows in STUDENT relation with
BRANCH_CODE CS (ROLL_NO 1 and 2 in this case) will be deleted.
ON UPDATE CASCADE: It will update the REFERENCING ATTRIBUTE in REFERENCING
RELATION if attribute value used by REFERENCING ATTRIBUTE is updated in REFERENCED
RELATION. e.g;, if we update a row from BRANCH with BRANCH_CODE ‘CS’ to ‘CSE’, the rows
in STUDENT relation with BRANCH_CODE CS (ROLL_NO 1 and 2 in this case) will be updated
with BRANCH_CODE ‘CSE’.
SUPER KEYS:
Any set of attributes that allows us to identify unique rows (tuples) in a given relation are known as
super keys. Out of these super keys we can always choose a proper subset among these which
can be used as a primary key. Such keys are known as Candidate keys. If there is a combination
of two or more attributes which is being used as the primary key then we call it as a Composite
key.
Properties of Relations
o Name of the relation is distinct from all other relations.
o Each relation cell contains exactly one atomic (single) value
o Each attribute contains a distinct name
o Attribute domain has no significance
o tuple has no duplicate value
o Order of tuple can have a different sequence
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
o SQL is easy to learn.
o SQL is used to access data from relational database management 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.
o SQL is used to create and drop the database and table.
o SQL is used to create a view, stored procedure, function in a database.
o SQL allows users to set permissions on tables, procedures, and views.
Advantages of SQL
There are the following advantages of SQL:
High speed
Using the SQL queries, the user can quickly and efficiently retrieve a large amount of records from a
database.
No coding needed
In the standard SQL, it is very easy to manage the database system. It doesn't require a substantial
amount of code to manage the database system.
Long established are used by the SQL databases that are being used by ISO and ANSI.
Portability
SQL can be used in laptop, PCs, server and even some mobile phones.
Interactive language
SQL is a domain language used to communicate with the database. It is also used to receive answers to
the complex questions in seconds.
Using the SQL language, the users can make different views of the database structure.
There are three types of binary Data types which are given below:
binary It has a maximum length of 8000 bytes. It contains fixed-length binary data.
varbinary It has a maximum length of 8000 bytes. It contains variable-length binary data.
image It has a maximum length of 2,147,483,647 bytes. It contains variable-length binary data.
float -1.79E + 308 1.79E + 308 It is used to specify a floating-point value e.g. 6.2, 2.9 etc.
Data Description
type
Datatype Description
timestamp It stores the year, month, day, hour, minute, and the second value.
SQL Commands
o SQL commands are instructions. It is used to communicate with the database. It is also used to
perform specific tasks, functions, and queries of data.
o SQL can perform various tasks like create a table, add data to tables, drop the table, modify the
table, set permission for users.
o CREATE
o ALTER
o DROP
o TRUNCATE
Syntax:
Example:
b. DROP: It is used to delete both the structure and record stored in the table.
Syntax
Example
c. ALTER: It is used to alter the structure of the database. This change could be either to modify the
characteristics of an existing attribute or probably to add a new attribute.
Syntax:
EXAMPLE
1. ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));
2. ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));
d. TRUNCATE: It is used to delete all the rows from the table and free the space containing the table.
Syntax:
Example:
o INSERT
o UPDATE
o DELETE
a. INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of a table.
Syntax:
Or
b. UPDATE: This command is used to update or modify the value of a column in the table.
Syntax:
For example:
1. UPDATE students
2. SET User_Name = 'Sonoo'
3. WHERE Student_Id = '3'
Syntax:
For example:
DCL commands are used to grant and take back authority from any database user.
o Grant
o Revoke
Example
Example
TCL commands can only use with DML commands like INSERT, DELETE and UPDATE only.
These operations are automatically committed in the database that's why they cannot be used while
creating tables or dropping them.
o COMMIT
o ROLLBACK
o SAVEPOINT
a. Commit: Commit command is used to save all the transactions to the database.
Syntax:
1. COMMIT;
Example:
b. Rollback: Rollback command is used to undo transactions that have not already been saved to the
database.
Syntax:
1. ROLLBACK;
Example:
c. SAVEPOINT: It is used to roll the transaction back to a certain point without rolling back the entire
transaction.
Syntax:
1. SAVEPOINT SAVEPOINT_NAME;
o 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:
1. SELECT expressions
2. FROM TABLES
3. WHERE conditions;
For example:
1. SELECT emp_name
2. FROM employee
3. WHERE age > 20;
SQL Operator
There are various types of SQL operator:
SQL Arithmetic Operators
Let's assume 'variable a' and 'variable b'. Here, 'a' contains 20 and 'b' contains 10.
- It is used to subtract the right-hand operand from the left-hand operand. a-b will give
10
/ It is used to divide the left-hand operand by the right-hand operand. a/b will give 2
% It is used to divide the left-hand operand by the right-hand operand and a%b will give 0
returns reminder.
= It checks if two operands values are equal or not, if the values are queal (a=b) is not
then condition becomes true. 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 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 (a>b) is not
yes 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 (a<=b) is true
operand value, if yes then condition becomes true.
!< It checks if the left operand value is not less than the right operand value, (a!=b) is not
if 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.
SQL Table
o SQL Table is a collection of data which is organized in terms of rows and columns. In DBMS, the
table is known as relation and row as a tuple.
o Table is a simple form of data storage. A table is also considered as a convenient representation
of relations.
Operation on Table
1. Create table
2. Drop table
3. Delete table
4. Rename table
SQL create table is used to create a table in the database. To define the table, you should define the name
of the table and also define its columns and column's data type.
Syntax
Example
If you create the table successfully, you can verify the table by looking at the message by the SQL server.
Else you can use DESC command as follows:
Now you have an EMPLOYEE table in the database, and you can use the stored information related to the
employees.
Drop table
A SQL drop table is used to delete a table definition and all the data from a table. When this command is
executed, all the information available in the table is lost forever, so you have to very careful while using
this command.
Syntax
Firstly, you need to verify the EMPLOYEE table using the following command:
This table shows that EMPLOYEE table is available in the database, so we can drop it as follows:
volume is
Now, we can check whether the table exists or not using the following command:
In SQL, DELETE statement is used to delete rows from a table. We can use WHERE condition to delete a
specific row from a table. If you want to delete all the records from the table, then you don't need to use
the WHERE clause.
Syntax
Example
If you don't specify the WHERE condition, it will remove all the rows from the table.
Syntax
1. SELECT column1, column2, ...
2. FROM table_name;
Here, the expression is the field name of the table that you want to select data from.
Use the following syntax to select all the fields available in the table:
Example:
EMPLOYEE
To fetch the EMP_ID of all the employees, use the following query:
Output
EMP_ID
2
3
EMP_NAME SALARY
Kristen 150000
Russell 200000
Angelina 600000
Robert 350000
Christian 260000
To fetch all the fields from the EMPLOYEE table, use the following query:
Output
Sample Table
EMPLOYEE
Syntax
Output: After executing this query, the EMPLOYEE table will look like:
Syntax
Query
1. INSERT INTO EMPLOYEE (EMP_ID, EMP_NAME, AGE) VALUES (7, 'Jack', 40);
Output: After executing this query, the table will look like:
Syntax
1. UPDATE table_name
2. SET column1 = value1, column2 = value2, ...
3. WHERE condition;
Sample Table
EMPLOYEE
Syntax
1. UPDATE table_name
2. SET column_name = value
3. WHERE condition;
Query
1. UPDATE EMPLOYEE
2. SET EMP_NAME = 'Emma'
3. WHERE SALARY = 500000;
Output: After executing this query, the EMPLOYEE table will look like:
Syntax
1. UPDATE table_name
2. SET column_name = value1, column_name2 = value2
3. WHERE condition;
Query
1. UPDATE EMPLOYEE
2. SET EMP_NAME = 'Kevin', City = 'Boston'
3. WHERE EMP_ID = 5;
Output
Syntax
1. UPDATE table_name
2. SET column_name = value1;
Query
1. UPDATE EMPLOYEE
2. SET EMP_NAME = 'Harry';
Output
Syntax
Sample Table
EMPLOYEE
EMP_ID EMP_NAME CITY SALARY AGE
Query
Output: After executing this query, the EMPLOYEE table will look like:
Query
Output: After executing this query, the EMPLOYEE table will look like:
Syntax
Query
Output: After executing this query, the EMPLOYEE table will look like:
EMP_ID EMP_NAME CITY SALARY AGE
Views in SQL
o Views in SQL are considered as a virtual table. A view also contains rows and columns.
o To create the view, we can select the fields from one or more tables present in the database.
o A view can either have specific rows based on certain condition or all the rows of a table.
Sample table:
Student_Detail
1 Stephan Delhi
2 Kathrin Noida
3 David Ghaziabad
4 Alina Gurugram
Student_Marks
1 Stephan 97 19
2 Kathrin 86 21
3 David 74 18
4 Alina 90 20
5 John 96 18
1. Creating view
A view can be created using the CREATE VIEW statement. We can create a view from a single table or
multiple tables.
Syntax:
Query:
Just like table query, we can query the view to view the data.
Output:
NAME ADDRESS
Stephan Delhi
Kathrin Noida
David Ghaziabad
3. Creating View from multiple tables
View from multiple tables can be created by simply include multiple tables in the SELECT statement.
In the given example, a view is created named MarksView from two tables Student_Detail and
Student_Marks.
Query:
Stephan Delhi 97
Kathrin Noida 86
David Ghaziabad 74
Alina Gurugram 90
4. Deleting View
A view can be deleted using the Drop View statement.
Syntax
Example:
Syntax
Example
Syntax
Example
Syntax
1. DROP INDEX index_name;
Example
SQL JOIN
As the name shows, JOIN means to combine something. In case of SQL, JOIN means "to combine two or
more tables".
In SQL, JOIN clause is used to combine the records from two or more tables in a database.
Sample Table
EMPLOYEE
66.1M
1.3K
101 1 Testing
102 2 Development
103 3 Designing
104 4 Development
1. INNER JOIN
In SQL, INNER JOIN selects records that have matching values in both tables as long as the condition is
satisfied. It returns the combination of all rows from both the tables where the condition satisfies.
Syntax
Query
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
2. LEFT JOIN
The SQL left join returns all the values from left table and the matching values from the right table. If there
is no matching join value, it will return NULL.
Syntax
Query
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Marry NULL
3. RIGHT JOIN
In SQL, RIGHT JOIN returns all the values from the values from the rows of right table and the matched
values from the left table. If there is no matching in both tables, it will return NULL.
Syntax
Query
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
4. FULL JOIN
In SQL, FULL JOIN is the result of a combination of both left and right outer join. Join tables have all the
records from both tables. It puts NULL on the place of matches not found.
Syntax
Query
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Marry NULL
Join operation in SQL is used to combine multiple tables together into a single table.
If we use the cross join to combine two different tables, then we will get the Cartesian product of the sets of rows from the joined
table. When each row of the first table is combined with each row from the second table, it is known as Cartesian join or cross join.
After performing the cross join operation, the total number of rows present in the final table will be equal to the product of the
number of rows present in table 1 and the number of rows present in table 2.
For example:
If there are two records in table 1 and three records in table 2, then after performing cross join operation, we will get six records in
the final table.
Let us take a look at the syntax of writing a query to perform the cross join operation in SQL.
1. SELECT TableName1.columnName1, TableName2.columnName2 FROM TableName1 CROSS JOIN TableName2 ON TableName1.Colu
mnName = TableName2.ColumnName;
Now let us see take a deeper dive into the cross join in SQL with the help of examples. All the queries in the examples will be written using the
MySQL database.
Table 1: MatchScore
Franklin 1 2
Alan 1 3
Priyanka 2 2
Rajesh 3 5
Table 2: Departments
Department_id Department_name
1 IT
2 HR
3 Marketing
Table 3: employee
Table 4: department
1 Production 1
2 Sales 3
3 Marketing 4
4 Accounts 5
Table 5: loan
1 B1 15000
2 B2 10000
3 B3 20000
4 B4 100000
Table 6: borrower
1 Sonakshi Dixit 1
2 Shital Garg 4
3 Swara Joshi 5
4 Isha Deshmukh 2
Table 7: customer
Table 8: orders
1 2012-01-20 2 3000
2 2012-05-18 2 2000
3 2012-06-28 3 4000
Example 1:
Write a query to perform the cross join operation considering the MatchScore table as the left table and the Departments table as the right table.
Query:
We have used the SELECT command with the asterisk to retrieve all the columns present in the MatchScore and Departments table. Then we
have used the CROSS JOIN keyword to perform the cross join operation on the MatchScore and Departments table. Since there are 4 records in
the MatchScore and 3 records in the Departments table, after performing the cross join operation, we will get 12 rows.
After executing this query, you will find the following result:
Franklin 1 2 1 IT
Alan 1 3 1 IT
Priyanka 2 2 1 IT
Rajesh 3 5 1 IT
Franklin 1 2 2 HR
Alan 1 3 2 HR
Priyanka 2 2 2 HR
Rajesh 3 5 2 HR
Franklin 1 2 3 Marketing
Alan 1 3 3 Marketing
Priyanka 2 2 3 Marketing
Rajesh 3 5 3 Marketing
Each row from the MatchScore table is combined with each row of the Departments table. Since there are four records in the MatchScore and
three records in the Departments table, we have got 12 rows in the final table after performing the cross join operation.
A column or columns is called primary key (PK) that uniquely identifies each row in the table.
If you want to create a primary key, you should define a PRIMARY KEY constraint when you create or modify a table.
When multiple columns are used as a primary key, it is known as composite primary key.
In designing the composite primary key, you should use as few columns as possible. It is good for storage and performance both, the more
columns you use for primary key the more storage space you require.
Inn terms of performance, less data means the database can process faster.
When we specify a primary key constraint for a table, database engine automatically creates a unique index for the primary key column.
In oracle, it is not allowed for a primary key to contain more than 32 columns.
The following SQL command creates a PRIMARY KEY on the "S_Id" column when the "students" table is created.
MySQL:
Note:you should note that in the above example there is only one PRIMARY KEY (pk_StudentID). However it is made up of two columns (S_Id
and LastName).
When table is already created and you want to create a PRIMARY KEY constraint on the "S_Id" column you should use the following SQL:
When you use ALTER TABLE statement to add a primary key, the primary key columns must not contain NULL values (when the table was first
created).
If you want to DROP (remove) a primary key constraint, you should use following syntax:
MySQL:
In the relational databases, a foreign key is a field or a column that is used to establish a link between two tables.
In simple words you can say that, a foreign key in one table used to point primary key in another table.
First table:
Second table:
Here you see that "S_Id" column in the "Orders" table points to the "S_Id" column in "Students" table.
The "S_Id" column in the "Students" table is the PRIMARY KEY in the "Students" table.
The "S_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
The foreign key constraint is generally prevents action that destroy links between tables.
To create a foreign key on the "S_Id" column when the "Orders" table is created:
MySQL:
If you want to drop a FOREIGN KEY constraint, use the following syntax:
MySQL:
These are some important difference between primary key and foreign key in SQL-
Primary key cannot be null on the other hand foreign key can be null.
Primary key uniquely identify a record in a table while foreign key is a field in a table that is primary key in another table.
There is only one primary key in the table on the other hand we can have more than one foreign key in the table.
By default primary key adds a clustered index on the other hand foreign key does not automatically create an index, clustered or non-clustered.
You must manually create an index for foreign key.
A composite key is a combination of two or more columns in a table that can be used to uniquely identify each row in the table when the columns
are combined uniqueness is guaranteed, but when it taken individually it does not guarantee uniqueness.
Sometimes more than one attributes are needed to uniquely identify an entity. A primary key that is made by the combination of more than one
attribute is known as a composite key.
Composite key is a key which is the combination of more than one field or column of a given table. It may be a candidate key or primary key.
Columns that make up the composite key can be of different data types.
MySQL:
MySQL:
Oracle:
SQL Server:
A unique key is a set of one or more than one fields/columns of a table that uniquely identify a record in a database table.
You can say that it is little like primary key but it can accept only one null value and it cannot have duplicate values.
The unique key and primary key both provide a guarantee for uniqueness for a column or a set of columns.
There is an automatically defined unique key constraint within a primary key constraint.
There may be many unique key constraints for one table, but only one PRIMARY KEY constraint for one table.
If you want to create a UNIQUE constraint on the "S_Id" column when the "students" table is created, use the following SQL syntax:
MySQL:
If you want to create a unique constraint on "S_Id" column when the table is already created, you should use the following SQL syntax:
If you want to drop a UNIQUE constraint, use the following SQL syntax:
MySQL:
Let's take an example of student it can contain NAME, ROLL NO., ID and CLASS.
Here ROLL NO. is primary key and rest of all columns like NAME, ID and CLASS are alternate keys.
If a table has more than one candidate key, one of them will become the primary key and rest of all are called alternate keys.
In simple words, you can say that any of the candidate key which is not part of primary key is called an alternate key. So when we talk about
alternate key, the column may not be primary key but still it is a unique key in the column.
There are a lot of databases used today in the industry. Some are SQL databases, some are NoSQL databases. The conventional database is SQL
database system that uses tabular relational model to represent data and their relationship. The NoSQL database is the newer one database that
provides a mechanism for storage and retrieval of data other than tabular relations model used in relational databases.
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.
1. Notation: σ p(r)
Where:
Input:
1. σ BRANCH_NAME="perryride" (LOAN)
Output:
2. Project Operation:
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.
It is denoted by ∏.
Where
Input:
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.
It eliminates the duplicate tuples. It is denoted by ∪.
1. 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:
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 ∩.
1. Notation: R ∩ S
Input:
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 (-).
1. Notation: R - S
Input:
Output:
CUSTOMER_NAME
Jackson
Hayes
Willians
Curry
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.
1. 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:
1. 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:
The rename operation is used to rename the output relation. It is denoted by rho (ρ).
Example: We can use the rename operator to rename STUDENT relation to STUDENT1.
1. ρ(STUDENT1, STUDENT)
Relational Calculus
There is an alternate way of formulating queries known as Relational Calculus. Relational calculus is a non-procedural query language. In the
non-procedural query language, the user is concerned with the details of how to obtain the end results. The relational calculus tells what to do but
never explains how to do. Most commercial relational languages are based on aspects of relational calculus including SQL-QBE and QUEL.
Why it is called Relational Calculus?
It is based on Predicate calculus, a name derived from branch of symbolic language. A predicate is a truth-valued function with arguments. On
substituting values for the arguments, the function result in an expression called a proposition. It can be either true or false. It is a tailored version
of a subset of the Predicate Calculus to communicate with the relational database.
Many of the calculus expressions involves the use of Quantifiers. There are two types of 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.
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.
Before using the concept of quantifiers in formulas, we need to know the concept of Free and Bound Variables.
A tuple variable t is bound if it is quantified which means that if it appears in any occurrences a variable that is not bound is said to be free.
Free and bound variables may be compared with global and local variable of programming languages.
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:
Where
For example:
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.
The second form of relation is known as Domain relational calculus. In domain relational calculus, filtering variable uses the domain of attributes.
Domain relational calculus uses the same operators as tuple calculus. It uses logical connectives ∧ (and), ∨ (or) and ┓ (not). 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:
Where
For example:
Output: This query will yield the article, page, and subject from the relational javatpoint, where the subject is a database.
Constraints in SQL
Constraints in SQL mean we are applying certain conditions or restrictions on the database. This further means that before inserting data into the
database, we are checking for some conditions. If the condition we have applied to the database holds true for the data which is to be inserted,
then only the data will be inserted into the database tables.
1. Every person has a unique email id. This is because while creating an email account for any user, the email providing services such as
Gmail, Yahoo or any other email providing service will always check for the availability of the email id that the user wants for
himself. If some other user already takes the email id that the user wants, then that id cannot be assigned to another user. This
simply means that no two users can have the same email ids on the same email providing service. So, here the email id is the
constraint on the database of email providing services.
2. Whenever we set a password for any system, there are certain constraints that are to be followed. These constraints may include
the following:
o There must be one uppercase character in the password.
o Password must be of at least eight characters in length.
o Password must contain at least one special symbol.
1. NOT NULL
2. UNIQUE
3. PRIMARY KEY
4. FOREIGN KEY
5. CHECK
6. DEFAULT
7. CREATE INDEX
Now let us try to understand the different constraints available in SQL in more detail with the help of examples. We will use MySQL database for
writing all the queries.
1. NOT NULL
NOTE: NULL does not mean zero. NULL means empty column, not even zero.
1. CREATE TABLE TableName (ColumnName1 datatype NOT NULL, ColumnName2 datatype,…., ColumnNameN datatype);
Example:
Create a student table and apply a NOT NULL constraint on one of the table's column while creating a table.
1. CREATE TABLE student(StudentID INT NOT NULL, Student_FirstName VARCHAR(20), Student_LastName VARCHAR(20), Student_Pho
neNumber VARCHAR(20), Student_Email_ID VARCHAR(40));
To verify that the not null constraint is applied to the table's column and the student table is created successfully, we will execute the following
query:
Example:
Consider we have an existing table student, without any constraints applied to it. Later, we decided to apply a NOT NULL constraint to one of the
table's column. Then we will execute the following query:
1. mysql> ALTER TABLE student CHANGE StudentID StudentID INT NOT NULL;
To verify that the not null constraint is applied to the student table's column, we will execute the following query:
2. UNIQUE
Duplicate values are not allowed in the columns to which the UNIQUE constraint is applied.
The column with the unique constraint will always contain a unique value.
This constraint can be applied to one or more than one column of a table, which means more than one unique constraint can exist
on a single table.
Using the UNIQUE constraint, you can also modify the already created tables.
1. CREATE TABLE TableName (ColumnName1 datatype UNIQUE, ColumnName2 datatype,…., ColumnNameN datatype);
Example:
Create a student table and apply a UNIQUE constraint on one of the table's column while creating a table.
1. mysql> CREATE TABLE student(StudentID INT UNIQUE, Student_FirstName VARCHAR(20), Student_LastName VARCHAR(20), Student
_PhoneNumber VARCHAR(20), Student_Email_ID VARCHAR(40));
To verify that the unique constraint is applied to the table's column and the student table is created successfully, we will execute the following
query:
1. CREATE TABLE TableName (ColumnName1 datatype, ColumnName2 datatype,…., ColumnNameN datatype, UNIQUE (ColumnName1,
ColumnName 2));
Example:
Create a student table and apply a UNIQUE constraint on more than one table's column while creating a table.
1. mysql> CREATE TABLE student(StudentID INT, Student_FirstName VARCHAR(20), Student_LastName VARCHAR(20), Student_PhoneN
umber VARCHAR(20), Student_Email_ID VARCHAR(40), UNIQUE(StudentID, Student_PhoneNumber));
To verify that the unique constraint is applied to more than one table's column and the student table is created successfully, we will execute the
following query:
Example:
Consider we have an existing table student, without any constraints applied to it. Later, we decided to apply a UNIQUE constraint to one of the
table's column. Then we will execute the following query:
3. PRIMARY KEY
1. CREATE TABLE TableName (ColumnName1 datatype PRIMARY KEY, ColumnName2 datatype,…., ColumnNameN datatype);
Example:
Create a student table and apply the PRIMARY KEY constraint while creating a table.
1. mysql> CREATE TABLE student(StudentID INT PRIMARY KEY, Student_FirstName VARCHAR(20), Student_LastName VARCHAR(20), St
udent_PhoneNumber VARCHAR(20), Student_Email_ID VARCHAR(40));
To verify that the primary key constraint is applied to the table's column and the student table is created successfully, we will execute the
following query:
Example:
Consider we have an existing table student, without any constraints applied to it. Later, we decided to apply the PRIMARY KEY constraint to the
table's column. Then we will execute the following query:
1. mysql> ALTER TABLE student ADD PRIMARY KEY (StudentID);
To verify that the primary key constraint is applied to the student table's column, we will execute the following query:
4. FOREIGN KEY
1. CREATE TABLE tablename(ColumnName1 Datatype(SIZE) PRIMARY KEY, ColumnNameN Datatype(SIZE), FOREIGN KEY( ColumnName
) REFERENCES PARENT_TABLE_NAME(Primary_Key_ColumnName));
Example:
Create an employee table and apply the FOREIGN KEY constraint while creating a table.
To create a foreign key on any table, first, we need to create a primary key on a table.
1. mysql> CREATE TABLE employee (Emp_ID INT NOT NULL PRIMARY KEY, Emp_Name VARCHAR (40), Emp_Salary VARCHAR (40));
To verify that the primary key constraint is applied to the employee table's column, we will execute the following query:
Now, we will write a query to apply a foreign key on the department table referring to the primary key of the employee table, i.e., Emp_ID.
1. mysql> CREATE TABLE department(Dept_ID INT NOT NULL PRIMARY KEY, Dept_Name VARCHAR(40), Emp_ID INT NOT NULL, FOREIG
N KEY(Emp_ID) REFERENCES employee(Emp_ID));
To verify that the foreign key constraint is applied to the department table's column, we will execute the following query:
1. CREATE TABLE tablename(ColumnName1 Datatype PRIMARY KEY, ColumnNameN Datatype(SIZE), CONSTRAINT ConstraintName FOR
EIGN KEY( ColumnName ) REFERENCES PARENT_TABLE_NAME(Primary_Key_ColumnName));
Example:
Create an employee table and apply the FOREIGN KEY constraint with a constraint name while creating a table.
To create a foreign key on any table, first, we need to create a primary key on a table.
1. mysql> CREATE TABLE employee (Emp_ID INT NOT NULL PRIMARY KEY, Emp_Name VARCHAR (40), Emp_Salary VARCHAR (40));
To verify that the primary key constraint is applied to the student table's column, we will execute the following query:
Now, we will write a query to apply a foreign key with a constraint name on the department table referring to the primary key of the employee
table, i.e., Emp_ID.
1. mysql> CREATE TABLE department(Dept_ID INT NOT NULL PRIMARY KEY, Dept_Name VARCHAR(40), Emp_ID INT NOT NULL, CONST
RAINT emp_id_fk FOREIGN KEY(Emp_ID) REFERENCES employee(Emp_ID));
To verify that the foreign key constraint is applied to the department table's column, we will execute the following query:
1. ALTER TABLE Parent_TableName ADD FOREIGN KEY (ColumnName) REFERENCES Child_TableName (ColumnName);
Example:
Consider we have an existing table employee and department. Later, we decided to apply a FOREIGN KEY constraint to the department table's
column. Then we will execute the following query:
1. mysql> ALTER TABLE department ADD FOREIGN KEY (Emp_ID) REFERENCES employee (Emp_ID);
To verify that the foreign key constraint is applied to the department table's column, we will execute the following query:
5. CHECK
Whenever a check constraint is applied to the table's column, and the user wants to insert the value in it, then the value will first be
checked for certain conditions before inserting the value into that column.
For example: if we have an age column in a table, then the user will insert any value of his choice. The user will also enter even a
negative value or any other invalid value. But, if the user has applied check constraint on the age column with the condition age
greater than 18. Then in such cases, even if a user tries to insert an invalid value such as zero or any other value less than 18, then
the age column will not accept that value and will not allow the user to insert it due to the application of check constraint on the age
column.
Syntax to apply check constraint on a single column:
1. CREATE TABLE TableName (ColumnName1 datatype CHECK (ColumnName1 Condition), ColumnName2 datatype,…., ColumnNameN
datatype);
Example:
Create a student table and apply CHECK constraint to check for the age less than or equal to 15 while creating a table.
1. mysql> CREATE TABLE student(StudentID INT, Student_FirstName VARCHAR(20), Student_LastName VARCHAR(20), Student_PhoneN
umber VARCHAR(20), Student_Email_ID VARCHAR(40), Age INT CHECK( Age <= 15));
To verify that the check constraint is applied to the student table's column, we will execute the following query:
1. CREATE TABLE TableName (ColumnName1 datatype, ColumnName2 datatype CHECK (ColumnName1 Condition AND ColumnName2
Condition),…., ColumnNameN datatype);
Example:
Create a student table and apply CHECK constraint to check for the age less than or equal to 15 and a percentage greater than 85 while creating a
table.
1. mysql> CREATE TABLE student(StudentID INT, Student_FirstName VARCHAR(20), Student_LastName VARCHAR(20), Student_PhoneN
umber VARCHAR(20), Student_Email_ID VARCHAR(40), Age INT, Percentage INT, CHECK( Age <= 15 AND Percentage > 85));
To verify that the check constraint is applied to the age and percentage column, we will execute the following query:
Example:
Consider we have an existing table student. Later, we decided to apply the CHECK constraint on the student table's column. Then we will execute
the following query:
To verify that the check constraint is applied to the student table's column, we will execute the following query:
6. DEFAULT
Whenever a default constraint is applied to the table's column, and the user has not specified the value to be inserted in it, then the default value
which was specified while applying the default constraint will be inserted into that particular column.
1. CREATE TABLE TableName (ColumnName1 datatype DEFAULT Value, ColumnName2 datatype,…., ColumnNameN datatype);
Example:
Create a student table and apply the default constraint while creating a table.
1. mysql> CREATE TABLE student(StudentID INT, Student_FirstName VARCHAR(20), Student_LastName VARCHAR(20), Student_PhoneN
umber VARCHAR(20), Student_Email_ID VARCHAR(40) DEFAULT "[email protected]");
To verify that the default constraint is applied to the student table's column, we will execute the following query:
Example:
Consider we have an existing table student. Later, we decided to apply the DEFAULT constraint on the student table's column. Then we will
execute the following query:
To verify that the default constraint is applied to the student table's column, we will execute the following query:
7. CREATE INDEX
CREATE INDEX constraint is used to create an index on the table. Indexes are not visible to the user, but they help the user to speed up the
searching speed or retrieval of data from the database.
Example:
Create an index on the student table and apply the default constraint while creating a table.
1. mysql> CREATE INDEX idx_StudentID ON student (StudentID);
To verify that the create index constraint is applied to the student table's column, we will execute the following query:
Example:
To verify that the create index constraint is applied to the student table's column, we will execute the following query:
Consider we have an existing table student. Later, we decided to apply the DEFAULT constraint on the student table's column. Then we will
execute the following query:
SQL | DIVISION
Division is typically required when you want to find out entities that are interacting with all
entities of a set of different type entities.
The division operator is used when we have to evaluate queries which contain the keyword ‘all’.
Some instances where division operator is used are:
Which person has account in all the banks of a particular city?
Which students have taken all the courses required to graduate?
In all these queries, the description after the keyword ‘all’ defines a set which contains some
elements and the final result contains those units who satisfy these requirements.
Important: Division is not supported by SQL implementations. However, it can be
represented using other operations.(like cross join, Except, In )
SQL Implementation of Division
Given two relations(tables): R(x,y) , S(y).
R and S : tables
x and y : column of R
y : column of S
R(x,y) div S(y) means gives all distinct values of x from R that are associated with all values of y
in S.
Computation of Division : R(x,y) div S(y)
Steps:
Find out all possible combinations of S(y) with R(x) by computing R(x) x(cross join) S(y), say r1
Subtract actual R(x,y) from r1, say r2
x in r2 are those that are not associated with every value in S(y); therefore R(x)-r2(x) gives us x
that are associated with all values in S
Queries
1. Implementation 1:
2. SELECT * FROM R
3. WHERE x not in ( SELECT x FROM (
4. (SELECT x , y FROM (select y from S ) as p cross join
5. (select distinct x from R) as sp)
6. EXCEPT
7. (SELECT x , y FROM R) ) AS r );
8.
9. Implementation 2 : Using correlated subquery
10. SELECT * FROM R as sx
11. WHERE NOT EXISTS (
12. (SELECT p.y FROM S as p )
13. EXCEPT
14. (SELECT sp.y FROM R as sp WHERE sp.x = sx.x ) );
15.
Relational algebra
Using steps which is mention above:
All possible combinations
r1 ← πx(R) x S
x values with “incomplete combinations”,
r2x ← πx(r1-R)
and
result ← πx(R)-r2x
Examples
Supply Schema