Relational Data Model and Language: Unit-3
Relational Data Model and Language: Unit-3
• Relational Algebra.
• Aggregate Function.
• Attribute: It contains the name of a column in a particular table. Each attribute Ai must have a
domain, dom(Ai).
• Relational instance: In the relational database system, the relational instance is represented by a
finite set of tuples. Relation instances do not have duplicate tuples.
Relational Model concept
• 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.
Relational Model concept
NAME ROLL_NO PHONE_NO ADDRESS AGE
•In the given table, NAME, ROLL_NO, PHONE_NO, ADDRESS, and AGE are the attributes.
•The instance of schema STUDENT has 5 tuples.
•t3 = <Laxman, 33289, 8583287182, Gurugram, 20>
Relational Model concept
• Properties of Relations
• Name of the relation is distinct from all other relations.
• Each relation cell contains exactly one atomic (single) value
• Each attribute contains a distinct name
• Attribute domain has no significance
• tuple has no duplicate value
• Order of tuple can have a different sequence
Integrity Constraints
o Integrity constraints are a set of rules. It is used to maintain the quality of information.
o Integrity constraints ensure that the data insertion, updating, and other processes have to be
performed in such a way that data integrity is not affected.
o Thus, integrity constraint is used to guard against accidental damage to the database.
Integrity Constraints
• Types of Integrity Constraint
Integrity Constraints
1. Domain constraints
o Domain constraints can be defined as the definition of a valid set of values for an attribute.
o The data type of domain includes string, character, integer, time, date, currency, etc.
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.
Integrity Constraints
• Example:
Integrity Constraints
3. Referential Integrity Constraints
o In the Referential integrity constraints, if a foreign key in Table 1 refers to the Primary Key of Table 2.
o Then every value of the Foreign Key in Table 1 must be null or be available in Table 2.
Integrity Constraints
• Example:
Integrity Constraints
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.
o A primary key can contain a unique and null value in the relational table.
Integrity Constraints
• Example
Relational Algebra
• 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 =, ≠, ≥, <, >, ≤.
Relational Algebra
• For example: LOAN Relation
• Where
• A1, A2, A3 is used as an attribute name of relation r.
Relational Algebra
• Example: CUSTOMER RELATION
• Output:
NAME CITY
Jones Harrison
Smith Rye
Hays Harrison
Curry Rye
Johnson Brooklyn
Brooks Brooklyn
Relational Algebra
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 ∪.
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.
Relational Algebra
• 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
Relational Algebra
• 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
Relational Algebra
• Input:
• ∏ CUSTOMER_NAME (BORROW) ∪ ∏ CUSTOMER_NAME (DEPOSITOR)
CUSTOMER_NAME
• Output: Johnson
Smith
Hayes
Turner
Jones
Lindsay
Jackson
Curry
Williams
Relational Algebra
• 4. Set Intersection:
CUSTOMER_NAME
Smith
Jones
Relational Algebra
• 5. Set Difference:
CUSTOMER_NAME
Jackson
Hayes
Willians
Curry
Relational Algebra
• 6. Cartesian product
o The Cartesian product is used to combine each row in one table with each row in the other
table.
o It is also known as a cross product.
o It is denoted by X.
• Notation: E X D
Relational Algebra
• Example:
• EMPLOYEE
1 Smith A
2 Harry C
3 John B
Relational Algebra
• DEPARTMENT
DEPT_NO DEPT_NAME
A Marketing
B Sales
C Legal
Relational Algebra
• Input:
• EMPLOYEE X DEPARTMENT
• Output:
EMP_ID EMP_NAME EMP_DEPT DEPT_NO DEPT_NAME
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
Relational Algebra
• 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.
• ρ(STUDENT1, STUDENT)
Characteristics of SQL
• SQL Datatype is used to define the values that a column can contain.
• Every column is required to have a name and data type in the database table.
SQL Datatype
• Datatype of SQL:
SQL Datatype
• 1. Binary Datatypes
• There are Three types of binary Datatypes which are given below:
Datatype Description
Timestamp It stores the year, month, day, hour, minute, and the second value.
SQL Commands
• There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.
SQL Commands
• 1. Data Definition Language (DDL)
o DDL changes the structure of the table like creating a table, deleting a table, altering a table, etc.
o All the command of DDL are auto-committed that means it permanently save all the changes in
the database.
SQL Commands
• Syntax:
• CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);
• Example:
• CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100), DOB DATE);
SQL Commands
• b. DROP: It is used to delete both the structure and record stored in the table.
• Syntax
• DROP TABLE ;
• Example
• DROP TABLE EMPLOYEE;
SQL Commands
• 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
• ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));
• ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));
SQL Commands
• d. TRUNCATE: It is used to delete all the rows from the table and free the space containing the
table.
• Syntax:
• TRUNCATE TABLE table_name;
• Example:
• TRUNCATE TABLE EMPLOYEE;
SQL Commands
• 2. Data Manipulation Language
o DML commands are used to modify the database.
o It is responsible for all form of changes in the database.
o 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.
• Syntax:
• INSERT INTO TABLE_NAME
• (col1, col2, col3,.... col N)
• VALUES (value1, value2, value3, .... valueN);
• Or
• INSERT INTO TABLE_NAME
• VALUES (value1, value2, value3, .... valueN);
• For example:
• INSERT INTO javatpoint (Author, Subject) VALUES ("Sonoo", "DBMS");
SQL Commands
• b. UPDATE: This command is used to update or modify the value of a column in the table.
• Syntax:
• UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [WHERE CONDITI
ON]
• For example:
• UPDATE students
• SET User_Name = 'Sonoo'
• WHERE Student_Id = '3'
SQL Commands
• c. DELETE: It is used to remove one or more row from a table.
• Syntax:
• DELETE FROM table_name [WHERE condition];
• For example:
• DELETE FROM javatpoint
• WHERE Author="Sonoo";
SQL Commands
• 3. Data Control Language
• DCL commands are used to grant and take back authority from any database user.
• Example
• GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;
• Example
• REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;
SQL Commands
• 4. Transaction Control Language
• 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.
• Syntax:
• COMMIT;
• Example:
• DELETE FROM CUSTOMERS
• WHERE AGE = 25;
• COMMIT;
SQL Commands
• 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;
SQL Commands
• c. SAVEPOINT: It is used to roll the transaction back to a certain point without rolling back the
entire transaction.
• Syntax:
• SAVEPOINT SAVEPOINT_NAME;
SQL Commands
• 5. Data Query Language
• Syntax:
• SELECT expressions
• FROM TABLES
• WHERE conditions;
• For example:
• SELECT emp_name
• FROM employee
• WHERE age > 20;
SQL Operator
• There are various types of SQL operator:
SQL Operator
• SQL Arithmetic Operators
• Let's assume 'variable a' and 'variable b'. Here, 'a' contains 20 and 'b' contains 10.
Operator Description Example
= It checks if two operands values are equal or not, if the values are queal then (a=b) is not true
condition becomes true.
!= It checks if two operands values are equal or not, if values are not equal, then (a!=b) is true
condition becomes true.
<> It checks if two operands values are equal or not, if values are not equal then (a<>b) is true
condition becomes true.
> It checks if the left operand value is greater than right operand value, if yes (a>b) is not true
then condition becomes true.
< It checks if the left operand value is less than right operand value, if yes then (a<b) is true
condition becomes true.
>= It checks if the left operand value is greater than or equal to the right operand (a>=b) is not true
value, if yes then condition becomes 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 true
yes then condition becomes true.
!> It checks if the left operand value is not greater than the right operand value, (a!>b) is true
if yes then condition becomes true.
SQL Operator
• SQL Logical Operators
• There is the list of logical operator used in SQL:
Operator Description
BETWEEN It is used to search for values that are within a set of values.
o SQL Table is a collection of data which is organized in terms of rows and columns.
In the above table, "EMPLOYEE" is the table name, "EMP_ID", "EMP_NAME", "CITY",
"PHONE_NO" are the column names. The combination of data of multiple columns forms
a row, e.g., 1, "Kristen", "Washington" and 7289201223 are the data of one row.
• Operation on Table
1. Create table
2. Drop table
3. Delete table
4. Rename table
• To define the table, you should define the name of the table and also define its columns and column's data
type.
Views in SQL
o Views in SQL are considered as a virtual table.
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
• Syntax:
• CREATE VIEW view_name AS
2. SELECT column1, column2.....
• FROM table_name
4. WHERE condition;
• 2. Creating View from a single table
• In this example, we create a View named DetailsView from the table Student_Detail.
• Query:
• CREATE VIEW DetailsView AS
2. SELECT NAME, ADDRESS
• FROM Student_Details
4. WHERE STU_ID < 4;
• Just like table query, we can query the view to view the data.
• SELECT * FROM DetailsView;
• 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:
• CREATE VIEW MarksView AS
2. SELECT Student_Detail.NAME, Student_Detail.ADDRESS, Student_Marks.MARKS
• FROM Student_Detail, Student_Mark
4. WHERE Student_Detail.NAME = Student_Marks.NAME;
Stephan Delhi 97
Kathrin Noida 86
David Ghaziabad 74
Alina Gurugram 90
• Deleting View
• Syntax
1. DROP VIEW view_name;
• Example:
1. DROP VIEW MarksView;
SQL Index
o Indexes are special lookup tables.
o It is used to retrieve data from the database very fast.
o An Index is used to speed up select queries and where clauses.
o But it shows down the data input with insert and update statements.
o Indexes can be created or dropped without affecting the data.
o An index in a database is just like an index in the back of a book.
o For example: When you reference all pages in a book that discusses a certain topic,
you first have to refer to the index, which alphabetically lists all the topics and then
referred to one or more specific page numbers.
• 1. Create Index statement
• Syntax
1. CREATE INDEX index_name
2. ON table_name (column1, column2, ...);
• Example
1. CREATE INDEX idx_name
2. ON Persons (LastName, FirstName);
• 2. Unique Index statement
• It is used to create a unique index on a table. It does not allow duplicate value.
• Syntax
1. CREATE UNIQUE INDEX index_name
2. ON table_name (column1, column2, ...);
• Example
1. CREATE UNIQUE INDEX websites_idx
2. ON websites (site_name);
• 3. Drop Index Statement
• Syntax
1. DROP INDEX index_name;
• Example
1. DROP INDEX websites_idx;
SQL Query & Sub Query
• A Subquery is a query within another SQL query and embedded within the WHERE clause.
• Important Rule:
o A subquery can be placed in a number of SQL clauses like WHERE clause, FROM clause, HAVING clause.
o You can use Subquery with SELECT, UPDATE, INSERT, DELETE statements along with the operators like
=, <, >, >=, <=, IN, BETWEEN, etc.
o A subquery is a query within another query. The outer query is known as the main query, and the inner query
is known as a subquery.
o Subqueries are on the right side of the comparison operator.
o A subquery is enclosed in parentheses.
o In the Subquery, ORDER BY command cannot be used. But GROUP BY command can be used to perform
the same function as ORDER BY command.
• 1. Subqueries with the Select Statement
• SQL subqueries are most frequently used with the Select statement.
• Syntax
1. SELECT column_name
2. FROM table_name
3. WHERE column_name expression operator
4. ( SELECT column_name from table_name WHERE ... );
• Example
• Consider the EMPLOYEE table have the following records:
1 John 20 US 2000.00
4 Alina 29 UK 6500.00
3. WHERE ID IN (SELECT ID
4. FROM EMPLOYEE
5. WHERE SALARY > 4500);
• This would produce the following result:
ID NAME AGE ADDRESS SALARY
4 Alina 29 UK 6500.00
• Syntax:
1. INSERT INTO table_name (column1, column2, column3....)
2. SELECT *
3. FROM table_name
4. WHERE VALUE OPERATOR
• Example
• Now use the following syntax to copy the complete EMPLOYEE table into the EMPLOYEE_BKP table.
1. INSERT INTO EMPLOYEE_BKP
2. SELECT * FROM EMPLOYEE
3. WHERE ID IN (SELECT ID
4. FROM EMPLOYEE);
• 3. Subqueries with the UPDATE Statement
• The subquery of SQL can be used in conjunction with the Update statement.
• When a subquery is used with the Update statement, then either single or multiple columns in a table can be
updated.
• Syntax
1. UPDATE table
2. SET column_name = new_value
3. WHERE VALUE OPERATOR
4. (SELECT COLUMN_NAME
5. FROM TABLE_NAME
6. WHERE condition);
• Example
• Let's assume we have an EMPLOYEE_BKP table available which is backup of EMPLOYEE table.
• The given example updates the SALARY by .25 times in the EMPLOYEE table for all employee whose AGE
is greater than or equal to 29.
1. UPDATE EMPLOYEE
2. SET SALARY = SALARY * 0.25
3. WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >= 29);
• This would impact three rows, and finally, the EMPLOYEE table would have the
following records.
1 John 20 US 2000.00
4 Alina 29 UK 1625.00
• Syntax
1. DELETE FROM TABLE_NAME
2. WHERE VALUE OPERATOR
3. (SELECT COLUMN_NAME
4. FROM TABLE_NAME WHERE condition);
Example
• Let's assume we have an EMPLOYEE_BKP table available which is backup of EMPLOYEE table.
• The given example deletes the records from the EMPLOYEE table for all EMPLOYEE whose AGE is greater
than or equal to 29.
1. DELETE FROM EMPLOYEE
2. WHERE AGE IN (SELECT AGE FROM EMPLOYEE_BKP WHERE AGE >= 29 );
• This would impact three rows, and finally, the EMPLOYEE table would have the
following records.
1 John 20 US 2000.00
• Syntax
1. COUNT(*)
2. or
3. COUNT( [ALL|DISTINCT] expression )
• Sample table:
• PRODUCT_MAST
Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Cpm1 3 25 75
Item8 Com1 3 10 30
Item9 Com2 2 25 50
• Output: 10
• Output:3
Example: COUNT() with GROUP BY
• SELECT COMPANY, COUNT(*)
2. FROM PRODUCT_MAST
• GROUP BY COMPANY;
• Output:
• Com1 5
• Com2 3
• Com3 2
• Example: COUNT() with HAVING
• SELECT COMPANY, COUNT(*)
2. FROM PRODUCT_MAST
• GROUP BY COMPANY
4. HAVING COUNT(*)>2;
• Output:
• Com1 5
• Com2 3
2. SUM Function
• Sum function is used to calculate the sum of all selected columns. It works on numeric fields only.
• Syntax
• SUM()
2. or
• SUM( [ALL|DISTINCT] expression )
• Example: SUM()
• SELECT SUM(COST)
2. FROM PRODUCT_MAST;
• Output:
• 670
Example: SUM() with WHERE
• SELECT SUM(COST)
2. FROM PRODUCT_MAST
• WHERE QTY>3;
• Output:
• 320
• Example: SUM() with GROUP BY
• SELECT SUM(COST)
2. FROM PRODUCT_MAST
• WHERE QTY>3
4. GROUP BY COMPANY;
• Output:
• Com1 150
• Com2 170
Example: SUM() with HAVING
• SELECT COMPANY, SUM(COST)
2. FROM PRODUCT_MAST
• GROUP BY COMPANY
4. HAVING SUM(COST)>=170;
• Output:
• Com1 335
• Com2 170
3. AVG function
• The AVG function is used to calculate the average value of the numeric type. AVG function returns the
average of all non-Null values.
• Syntax
• AVG()
2. or
• AVG( [ALL|DISTINCT] expression )
• Example:
• SELECT AVG(COST)
2. FROM PRODUCT_MAST;
• Output:
• 67.00
4. MAX Function
• MAX function is used to find the maximum value of a certain column. This function determines the largest
value of all selected values of a column.
• Syntax
• MAX()
2. or
• MAX( [ALL|DISTINCT] expression )
• Example:
• SELECT MAX(RATE)
2. FROM PRODUCT_MAST;
• 30
5. MIN Function
• MIN function is used to find the minimum value of a certain column. This function determines the smallest
value of all selected values of a column.
• Syntax
• MIN()
2. or
• MIN( [ALL|DISTINCT] expression )
• Example:
• SELECT MIN(RATE)
2. FROM PRODUCT_MAST;
• Output:
• 10
SQL Clauses
• The following are the various SQL clauses:
1. GROUP BY
o SQL GROUP BY statement is used to arrange identical data into groups.
o The GROUP BY statement follows the WHERE clause in a SELECT statement and precedes the ORDER
BY clause.
• Syntax
• SELECT column
• FROM table_name
• WHERE conditions
• GROUP BY column
• ORDER BY column
• Sample table:
• PRODUCT_MAST
Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Cpm1 3 25 75
Item8 Com1 3 10 30
Item9 Com2 2 25 50
• FROM PRODUCT_MAST
• GROUP BY COMPANY;
• Output:
• Com1 5
• Com2 3
• Com3 2
HAVING
o If you are not using GROUP BY clause then you can use HAVING function like a WHERE clause.
• Syntax:
• SELECT column1, column2
• FROM table_name
• WHERE conditions
• GROUP BY column1, column2
• HAVING conditions
• ORDER BY column1, column2;
Example:
• SELECT COMPANY, COUNT(*)
• FROM PRODUCT_MAST
• GROUP BY COMPANY
• HAVING COUNT(*)>2;
• Output:
• Com1 5
• Com2 3
3. ORDER BY
o The ORDER BY clause sorts the result-set in ascending or descending order.
• Syntax:
• SELECT column1, column2
• FROM table_name
• WHERE condition
• ORDER BY column1, column2... ASC|DESC;
Where
• ASC: It is used to sort the result set in ascending order by expression.
12 Kathrin US
23 David Bangkok
34 Alina Dubai
45 John UK
56 Harry US
Enter the following SQL statement:
• SELECT *
• FROM CUSTOMER
• ORDER BY NAME;
• Output:
34 Alina Dubai
23 David Bangkok
56 Harry US
45 John UK
12 Kathrin US
Example: Sorting Results in Descending Order
• Using the above CUSTOMER table
• SELECT *
• FROM CUSTOMER
• ORDER BY NAME DESC;
• Output:
12 Kathrin US
45 John UK
56 Harry US
23 David Bangkok
34 Alina Dubai