0% found this document useful (0 votes)
36 views

Relational Data Model and Language: Unit-3

The document provides an overview of key concepts in relational data modeling and the relational algebra language. It defines relational model concepts including relations, attributes, domains, tuples, and keys. It describes integrity constraints like domain constraints and referential integrity. Relational algebra operations covered include select, project, union, intersection, difference, cartesian product, and rename. Examples are provided to illustrate each concept and operation.

Uploaded by

Anuhya Anu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Relational Data Model and Language: Unit-3

The document provides an overview of key concepts in relational data modeling and the relational algebra language. It defines relational model concepts including relations, attributes, domains, tuples, and keys. It describes integrity constraints like domain constraints and referential integrity. Relational algebra operations covered include select, project, union, intersection, difference, cartesian product, and rename. Examples are provided to illustrate each concept and operation.

Uploaded by

Anuhya Anu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 119

Unit-3

Relational Data Model and Language


Contents to be covered…..
• Relational Data Model Concepts.

• Integrity Constraints- Entity, Referential, Key, Domain.

• Relational Algebra.

• Tables, Views and Indexes.

• Queries and Sub Queries.

• Aggregate Function.

• Insert, Update and Delete Operations.

• Joins, Unions, Intersection, Minus, cursors in SQL.


Relational Model concept

• Relational model can represent as a table with columns and rows.


• Each row is known as a tuple. Each table of the column has a name or attribute.

• Domain: It contains a set of atomic values that an attribute can take.

• 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

Ram 14795 7305758992 Noida 24

Shyam 12839 9026288936 Delhi 35

Laxman 33289 8583287182 Gurugram 20

Mahesh 27857 7086819134 Ghaziabad 27

Ganesh 17282 9028 9i3988 Delhi 40

•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 value of the attribute must be available in the corresponding domain.


Integrity Constraints
• Example:
Integrity Constraints
2. Entity integrity constraints

o The entity integrity constraint states that primary key value can't be null.

o This is because the primary key value is used to identify individual rows in relation and if the
primary key has a null value, then we can't identify those rows.

o A table can contain a null value other than the primary key field.
Integrity Constraints
• Example:
Integrity Constraints
3. Referential Integrity Constraints

o A referential integrity constraint is specified between two tables.

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

• 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.
Relational Algebra
• Types of Relational operation
Relational Algebra
• 1. Select Operation:
o The select operation selects tuples that satisfy a given predicate.
o 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 =, ≠, ≥, <, >, ≤.
Relational Algebra
• For example: LOAN Relation

BRANCH_NAME LOAN_NO AMOUNT

Downtown L-17 1000

Redwood L-23 2000

Perryride L-15 1500

Downtown L-14 1500

Mianus L-13 500

Roundhill L-11 900

Perryride L-16 1300


Relational Algebra
• Input:
• σ BRANCH_NAME="perryride" (LOAN)  
• Output:

BRANCH_NAME LOAN_NO AMOUNT

Perryride L-15 1500

Perryride L-16 1300


Relational Algebra
• 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 ∏.
• Notation: ∏ A1, A2, An (r)

• Where
• A1, A2, A3 is used as an attribute name of relation r.
   
Relational Algebra
• Example: CUSTOMER RELATION

NAME STREET CITY

Jones Main Harrison

Smith North Rye

Hays Main Harrison

Curry North Rye

Johnson Alma Brooklyn

Brooks Senator Brooklyn


Relational Algebra
• Input:
• ∏ NAME, CITY (CUSTOMER)  

• 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:

o Suppose there are two tuples R and S.


o The set intersection operation contains all tuples that are in both R & S.
o It is denoted by intersection ∩.
• Notation: R ∩ S   
Relational Algebra

• Example: Using the above DEPOSITOR table and BORROW table


• Input:
• ∏ CUSTOMER_NAME (BORROW) ∩ ∏ CUSTOMER_NAME (DEPOSITOR)  
• Output:

CUSTOMER_NAME

Smith

Jones
Relational Algebra
• 5. Set Difference:

o Suppose there are two tuples R and S.


o The set intersection operation contains all tuples that are in R but not in S.
o It is denoted by intersection minus (-).
• Notation: R - S  
Relational Algebra
• Example: Using the above DEPOSITOR table and BORROW table
• Input:
• ∏ CUSTOMER_NAME (BORROW) - ∏ CUSTOMER_NAME (DEPOSITOR)  
• Output:

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

EMP_ID EMP_NAME EMP_DEPT

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 is easy to learn.


• SQL is used to access data from relational database management systems.
• SQL can execute queries against the database.
• SQL is used to describe the data.
• SQL is used to define the data in the database and manipulate it when needed.
• SQL is used to create and drop the database and table.
• SQL is used to create a view, stored procedure, function in a database.
• 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.
SQL Datatype

• 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:

Data Type Description

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.
SQL Datatype
• 2. Approximate Numeric Datatype :
• The subtypes are given below:

Data type From To Description

float -1.79E + 308 1.79E + 308 It is used to specify a


floating-point value e.g.
6.2, 2.9 etc.

real -3.40e + 38 3.40E + 38 It specifies a single


precision floating point
number
SQL Datatype
• 3. Exact Numeric Datatype
• The subtypes are given below:

Data type Description

Int It is used to specify an integer value.

Smallint It is used to specify small integer value.

Bit It has the number of bits to store.

Decimal It specifies a numeric value that can have a decimal


number.

Numeric It is used to specify a numeric value.


SQL Datatype
• 4. Character String Datatype
• The subtypes are given below:

Data type Description

Char It has a maximum length of 8000 characters. It contains


Fixed-length non-unicode characters.

Varchar It has a maximum length of 8000 characters. It contains


variable-length non-unicode characters.

Text It has a maximum length of 2,147,483,647 characters. It


contains variable-length non-unicode characters.
SQL Datatype
• 5. Date and time Datatypes
• The subtypes are given below:

Datatype Description

Date It is used to store the year, month, and days value.

Time It is used to store the hour, minute, and second values.

Timestamp It stores the year, month, day, hour, minute, and the second value.
SQL Commands

o SQL commands are instructions.


o It is used to communicate with the database.
o 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.
SQL Commands
• Types of 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

• Here are some commands that come under DDL:


o CREATE
o ALTER
o DROP
o TRUNCATE
SQL Commands
• a. CREATE It is used to create a new table in the database.

• 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:

• To add a new column in the table


• ALTER TABLE table_name ADD column_name COLUMN-definition;    

• To modify existing column in the table:


• ALTER TABLE MODIFY(COLUMN DEFINITION....);  

• 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.

• Here are some commands that come under DML:


o INSERT
o UPDATE
o DELETE
SQL Commands
• a. INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of a table.

• 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.

• Here are some commands that come under DCL:


o Grant
o Revoke
SQL Commands
• a. Grant: It is used to give user access privileges to a database.

• Example
• GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;  

• b. Revoke: It is used to take back permissions from the 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.

• Here are some commands that come under TCL:


o COMMIT
o ROLLBACK
o SAVEPOINT
SQL Commands
• a. Commit: Commit command is used to save all the transactions to the database.

• 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

• DQL is used to fetch the data from the database.

• It uses only one command:


o SELECT
SQL Commands
• 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:
• 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 adds the value of both operands. a+b will give 30

- It is used to subtract the right-hand operand a-b will give 10


from the left-hand operand.

* It is used to multiply the value of both a*b will give 200


operands.

/ It is used to divide the left-hand operand by a/b will give 2


the right-hand operand.

% It is used to divide the left-hand operand by a%b will give 0


the right-hand operand and returns reminder.
SQL Operator
• SQL Comparison 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

ALL It compares a value to all values in another value set.

AND It allows the existence of multiple conditions in an SQL statement.

ANY It compares the values in the list according to the condition.

BETWEEN It is used to search for values that are within a set of values.

IN It compares a value to that specified list value.

NOT It reverses the meaning of any logical operator.

OR It combines multiple conditions in SQL statements.

EXISTS It is used to search for the presence of a row in a specified table.

LIKE It compares a value to similar values using wildcard operator.


SQL Table

o SQL Table is a collection of data which is organized in terms of rows and columns.

o In DBMS, the table is known as relation and row as a tuple.

o Table is a simple form of data storage.

o A table is also considered as a convenient representation of relations.


• Let's see an example of the EMPLOYEE table:

EMP_ID EMP_NAME CITY PHONE_NO

1 Kristen Washington 7289201223

2 Anna Franklin 9378282882

3 Jackson Bristol 9264783838

4 Kellan California 7254728346

5 Ashley Hawaii 9638482678

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

• SQL Create 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.
Views in SQL
o Views in SQL are considered as a virtual table.

o 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

STU_ID NAME ADDRESS

1 Stephan Delhi

2 Kathrin Noida

3 David Ghaziabad

4 Alina Gurugram
• Student_Marks

STU_ID NAME MARKS AGE

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:
• 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;  

• To display data of View MarksView:


• SELECT * FROM MarksView;  

NAME ADDRESS MARKS

Stephan Delhi 97

Kathrin Noida 86

David Ghaziabad 74

Alina Gurugram 90
• Deleting View

• A view can be deleted using the Drop View statement.

• Syntax

1. DROP VIEW view_name;  

• Example:

• If we want to delete the View MarksView, we can do this as:

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

• It is used to create an index on a table. It allows duplicate value.

• 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

• It is used to delete an index in a table.

• 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:

ID NAME AGE ADDRESS SALARY

1 John 20 US 2000.00

2 Stephan 26 Dubai 1500.00

3 David 27 Bangkok 2000.00

4 Alina 29 UK 6500.00

5 Kathrin 34 Bangalore 8500.00

6 Harry 42 China 4500.00

7 Jackson 25 Mizoram 10000.00


• The subquery with a SELECT statement will be:
1. SELECT *   
2.     FROM EMPLOYEE  

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

5 Kathrin 34 Bangalore 8500.00

7 Jackson 25 Mizoram 10000.00


• 2. Subqueries with the INSERT Statement

o SQL subquery can also be used with the Insert statement.


o In the insert statement, data returned from the subquery is used to insert into another table.
o In the subquery, the selected data can be modified with any of the character, date functions.

• Syntax:
1. INSERT INTO table_name (column1, column2, column3....)   
2. SELECT *  

3. FROM table_name  
4. WHERE VALUE OPERATOR  
• Example

• Consider a table EMPLOYEE_BKP with similar as EMPLOYEE.

• 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.

ID NAME AGE ADDRESS SALARY

1 John 20 US 2000.00

2 Stephan 26 Dubai 1500.00

3 David 27 Bangkok 2000.00

4 Alina 29 UK 1625.00

5 Kathrin 34 Bangalore 2125.00

6 Harry 42 China 1125.00

7 Jackson 25 Mizoram 10000.00


4. Subqueries with the DELETE Statement
• The subquery of SQL can be used in conjunction with the Delete statement just like any other statements
mentioned above.

• 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.

ID NAME AGE ADDRESS SALARY

1 John 20 US 2000.00

2 Stephan 26 Dubai 1500.00

3 David 27 Bangkok 2000.00

7 Jackson 25 Mizoram 10000.00


SQL Aggregate Functions
o SQL aggregation function is used to perform the calculations on multiple rows of a single column of a table.
o It returns a single value.
o It is also used to summarize the data.
• Types of SQL Aggregation Function
• 1. COUNT FUNCTION
o COUNT function is used to Count the number of rows in a database table.
o It can work on both numeric and non-numeric data types.
o COUNT function uses the COUNT(*) that returns the count of all the rows in a specified table.
o COUNT(*) considers duplicate and Null.

• Syntax
1. COUNT(*)  
2. or  

3. COUNT( [ALL|DISTINCT] expression )  
• Sample table:
• PRODUCT_MAST

PRODUCT COMPANY QTY RATE COST

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

Item7 Com1 5 30 150

Item8 Com1 3 10 30

Item9 Com2 2 25 50

Item10 Com3 4 30 120


Example: COUNT()
• SELECT COUNT(*)  
2. FROM PRODUCT_MAST;  

• Output: 10

• Example: COUNT with WHERE


• SELECT COUNT(*)  
2. FROM PRODUCT_MAST;  
• WHERE RATE>=20;  
• Output:7

• Example: COUNT() with DISTINCT


• SELECT COUNT(DISTINCT COMPANY)  
2. FROM PRODUCT_MAST;    

• 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 is used with the SQL SELECT statement.

o The GROUP BY statement follows the WHERE clause in a SELECT statement and precedes the ORDER
BY clause.

o The GROUP BY statement is used with aggregation function.

• Syntax
• SELECT column  
• FROM table_name  
• WHERE conditions   
• GROUP BY column  
• ORDER BY column  
• Sample table:
• PRODUCT_MAST

PRODUCT COMPANY QTY RATE COST

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

Item7 Com1 5 30 150

Item8 Com1 3 10 30

Item9 Com2 2 25 50

Item10 Com3 4 30 120


Example:
• SELECT COMPANY, COUNT(*)  

• FROM PRODUCT_MAST   

• GROUP BY COMPANY;  

• Output:
• Com1 5
• Com2 3
• Com3 2
HAVING

o HAVING clause is used to specify a search condition for a group or an aggregate.

o Having is used in a GROUP BY clause.

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.

o It sorts the records in ascending order by default.

o DESC keyword is used to sort the records in 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.

• DESC: It sorts the result set in descending order by expression.

• Example: Sorting Results in Ascending Order


• Table:
• CUSTOMER

CUSTOMER_ID NAME ADDRESS

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:

CUSTOMER_ID NAME ADDRESS

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:

CUSTOMER_ID NAME ADDRESS

12 Kathrin US

45 John UK

56 Harry US

23 David Bangkok

34 Alina Dubai

You might also like