Introduction to Relational Data Model
UNIT I
Introduction: Database system, Characteristics (Database Vs File System), Database Users(Actors on
Scene, Workers behind the scene), Advantages of Database systems, Database applications. Brief
introduction of different Data Models; Concepts of Schema, Instance and data independence; Three
tier schema architecture for data independence; Database system structure, environment, Centralized
and Client Server architecture for the database.
UNIT II
Relational Model: Introduction to relational model, concepts of domain, attribute, tuple, relation,
importance of null values, constraints (Domain, Key constraints, integrity constraints) and their
importance BASIC SQL: Simple Database schema, data types, table definitions (create, alter),
different DML operations (insert, delete, update), basic SQL querying (select and project) using
where clause, arithmetic & logical operations, SQL functions(Date and Time, Numeric, String
conversion).
UNIT III
Entity Relationship Model: Introduction, Representation of entities, attributes, entity set, relationship,
relationship set, constraints, sub classes, super class, inheritance, specialization, generalization using
ER Diagrams. SQL: Creating tables with relationship, implementation of key and integrity
constraints, nested queries, sub queries, grouping, aggregation, ordering, implementation of different
types of joins, view(updatable and non-updatable), relational set operations.
UNIT IV
Schema Refinement (Normalization): Purpose of Normalization or schema refinement, concept of
functional dependency, normal forms based on functional dependency(1NF, 2NF and 3 NF), concept
of surrogate key, Boyce-codd normal form(BCNF), Lossless join and dependency preserving
decomposition, Fourth normal form(4NF), Fifth Normal Form (5NF).
UNIT V
Transaction Concept: Transaction State, Implementation of Atomicity and Durability, Concurrent Executions, Serializability,
Recoverability, Implementation of Isolation, Testing for Serializability,Failure Classification, Storage, Recovery and Atomicity,
Recovery algorithm.Indexing Techniques: B+ Trees: Search, Insert, Delete algorithms, File Organization and Indexing,
Cluster Indexes, Primary and Secondary Indexes , Index data Structures, Hash Based Indexing: Tree
base Indexing ,Comparison of File Organizations, Indexes and Performance Tuning
Text Books:
1) Database Management Systems, 3/e, Raghurama Krishnan, Johannes Gehrke, TMH
2) Database System Concepts,5/e, Silberschatz, Korth, TMH
Reference Books:
1) Introduction to Database Systems, 8/e C J Date, PEA.
2) Database Management System, 6/e Ramez Elmasri, Shamkant B. Navathe, PEA
3) Database Principles Fundamentals of Design Implementation and Management, Corlos
Coronel, Steven Morris, Peter Robb, Cengage Learning.
e-Resources:
1) https://nptel.ac.in/courses/106/105/106105175/
2) https://www.geeksforgeeks.org/introduction-to-nosql/
Slide 5- 19
Informal Terms | | Formal Terms |
Table | | Relation |
Column Header | | Attribute |
All possible Column Values | | Domain |
Row | | Tuple |
| | |
Table Definition | | Schema of a Relation |
Populated Table | | State of the Relation |
Example of a Relation
Slide 5- 20
Primary Key – A primary is a column or set of columns in a table that uniquely identifies tuples (rows) in that table.
Super Key – A super key is a set of one of more columns (attributes) to uniquely identify rows in a table.
Candidate Key – A super key with no redundant attribute is known as candidate key
Alternate Key – Out of all candidate keys, only one gets selected as primary key, remaining keys are known as alternate or secondary keys.
Composite Key – A key that consists of more than one attribute to uniquely identify rows (also known as records & tuples) in a table is called composite key.
Foreign Key – Foreign keys are the columns of a table that points to the primary key of another table. They act as a cross-reference between tables.
Relational algebra and relational calculus
Query Language�
In simple words, a Language which is used to store and retrieve data from database is known as query language. For example – SQL
There are two types of query language:�1.Procedural Query language�2.Non-procedural query language
1. Procedural Query language:
In procedural query language, user instructs the system to perform a series of operations to produce the desired results. Here users tells what data to be retrieved from database and how to retrieve it.
2. Non-procedural query language:
In Non-procedural query language, user instructs the system to produce the desired result without telling the step by step process. Here users tells what data to be retrieved from database but doesn’t tell how to retrieve it.
For example – You are asking your younger brother to make a cup of tea, if you are just telling him to make a tea and not telling the process then it is a non-procedural language, however if you are telling the step by step process like switch on the stove, boil the water, add milk etc. then it is a procedural language.
Relational Algebra:
Relational algebra is a conceptual procedural query language used on relational model.
Relational Calculus:
Relational calculus is a conceptual non-procedural query language used on relational model.
Types of operations in relational algebra
We have divided these operations in two categories:�1. Basic Operations�2. Derived Operations
Basic/Fundamental Operations:
1. Select (σ)�2. Project (∏)�3. Union (∪)�4. Set Difference (-)�5. Cartesian product (X)�6. Rename (ρ)
Derived Operations:
1. Natural Join (⋈)�2. Left, Right, Full outer join (⟕, ⟖, ⟗)�3. Intersection (∩)�4. Division (÷)
RELATIONAL ALGEBRA
Sailors(sid: integer, sname: string, rating: integer, age: real)
Boats( bid: integer, bname: string, color: string)
Reserves(sid: integer, bid: integer, day: date)
INSTANCE S1 OF SAILORS | |||
SID | NAME | RATING | AGE |
22 | DUSTIN | 7 | 45.0 |
31 | LUBBER | 8 | 55.5 |
58 | RUSTY | 10 | 35.0 |
INSTANCE S2 OF SAILORS | |||
SID | NAME | RATING | AGE |
28 | YUPPY | 9 | 35.0 |
31 | LUBBER | 8 | 55.5 |
44 | GUPPY | 5 | 35.0 |
58 | RUSTY | 10 | 35.0 |
INSTANCE R1 OF RESERVES | ||
SID | BID | DAY |
22 | 101 | 10-OCT-96 |
58 | 103 | 11-OCT-96 |
INSTANCE S2 OF SAILORS | |||
SID | NAME | RATING | AGE |
28 | YUPPY | 9 | 35.0 |
58 | RUSTY | 10 | 35.0 |
INSTANCE S2 OF SAILORS | |
YUPPY | 9 |
LUBBER | 8 |
GUPPY | 5 |
RUSTY | 10 |
Age |
35.0 |
55.5 |
NAME | AGE |
YUPPY | 35.0 |
LUBBER | 55.5 |
GUPPY | 35.0 |
RUSTY | 35.0 |
2. Set Operations
Consider the relation instances S1 and S2. S1 and S2 are union compatible . S1 and R1 are not union compatible.
S1US2
S1nS2
S1-S2
S1US2 | |||
SID | NAME | RATING | AGE |
22 | DUSTIN | 7 | 45.0 |
28 | YUPPY | 9 | 35.0 |
31 | LUBBER | 8 | 55.5 |
44 | GUPPY | 5 | 35.0 |
58 | RUSTY | 10 | 35.0 |
S1nS2 | |||
SID | NAME | RATING | AGE |
31 | LUBBER | 8 | 55.5 |
58 | RUSTY | 10 | 35.0 |
S1-S2 | |||
SID | NAME | RATING | AGE |
22 | DUSTIN | 7 | 45.0 |
iv) Cross-product:
S1XR1 | ||||||
SID | NAME | RATING | AGE | SID | BID | DAY |
22 | DUSTIN | 7 | 45.0 | 22 | 101 | 10-OCT-96 |
22 | DUSTIN | 7 | 45.0 | 58 | 103 | 11-OCT-96 |
31 | LUBBER | 8 | 55.5 | 22 | 101 | 10-OCT-96 |
31 | LUBBER | 8 | 55.5 | 58 | 103 | 11-OCT-96 |
58 | RUSTY | 10 | 35.0 | 22 | 101 | 10-OCT-96 |
58 | RUSTY | 10 | 35.0 | 58 | 103 | 11-OCT-96 |
3. Rename
we are talking about, in that case, we rename one of the tables and perform join operations on them.
Example: The expression ρ(C(1->SID1,5->SID2),S1XR1)
4. Joins
The join operation is one of the most useful operations in relational algebra and the most commonly used way to combine information from two or more relations.
Join operation denoted by ⋈.
It is used to combine tuples from two relations into single tuple.
R ⋈c S = σc (R X S)
II. Equi Join:
III. Natural Join
5. Division:
Examples of Division OPERATION
Outer Join Operations:
A set of operations called outer joins can be used when we want to keep all the tuples in R or all those in S or all those in both relations in the result of the JOIN, regardless of whether or not they have matching tuples in the other relation. The join operations where only matching tuples are kept in the result are called inner joins.
There are three types of outer joins:
Consider the relations:
SSN | FNAME | MINIT | LNAME | SALARY | DNO |
123456789 | JOHN | B | SMITH | 30000 | 5 |
333445555 | FRANKLIN | T | WONG | 40000 | 5 |
999887777 | ALICIA | J | ZELAYA | 25000 | 4 |
987654321 | JENNIFER | S | WALLACE | 43000 | 4 |
666884444 | RAMESH | K | NARAYAN | 38000 | 5 |
453453453 | JOYCE | A | ENGLISH | 25000 | 5 |
987987987 | AHMOD | V | JABBA | 25000 | 4 |
888665555 | JAMES | E | BORG | 55000 | 1 |
DNUMBER | DNAME | MGR_SSN |
5 | RESEARCH | 333445555 |
4 | ADMINISTRATION | 987654321 |
1 | HEAD QUARTERS | 888665555 |
The left outer join operation keeps every tuple in the first, or left relation R in R⟕S. If no matching tuple is found in S, then the attributes of S in the join result are filled or padded with the NULL values.
Example: Retrieve a list of all employee names and also the name of the departments they manage if they happen to manage a department, if they do not manage one, we can indicate it with a NULL value.
EMPLOYEE⟕SSN=MGR_SSNDEPARTMENT
FNAME | MINIT | LNAME | DNAME |
JOHN | B | SMITH | NULL |
FRANKLIN | T | WONG | RESEARCH |
ALICIA | J | ZELAYA | NULL |
JENNIFER | S | WALLACE | ADMINISTRATION |
RAMESH | K | NARAYAN | NULL |
JOYCE | A | ENGLISH | NULL |
AHMOD | V | JABBA | NULL |
JAMES | E | BORG | HEADQUARTERS |
SSN | FNAME | MINIT | LNAME | SALARY | DNO |
123456789 | JOHN | B | SMITH | 30000 | 5 |
333445555 | FRANKLIN | T | WONG | 40000 | 5 |
999887777 | ALICIA | J | ZELAYA | 25000 | 4 |
987654321 | JENNIFER | S | WALLACE | 43000 | 4 |
666884444 | RAMESH | K | NARAYAN | 38000 | 5 |
453453453 | JOYCE | A | ENGLISH | 25000 | 5 |
987987987 | AHMOD | V | JABBA | 25000 | 4 |
888665555 | JAMES | E | BORG | 55000 | 1 |
DNUMBER | DNAME | MGR_SSN |
5 | RESEARCH | 333445555 |
4 | ADMINISTRATION | 987654321 |
1 | HEAD QUARTERS | 888665555 |
R⟕S
2. Right Outer Join:
It is denoted by ⟖ keeps every tuple in the second or right relation S in the result of R⟖S.
EMPLOYEE ⟖ SSN=MGR_SSNDEPARTMENT
3. Full Outer Join:
It is denoted by ⟗ keeps all tuples in both are left and the right relations when no matching tuples are found, padding them with NULL values are needed.
EMPLOYEE ⟗ SSN=MGR_SSNDEPARTMENT
FNAME | MINIT | LNAME | DNAME |
FRANKLIN | T | WONG | RESEARCH |
JENNIFER | S | WALLACE | ADMINISTRATION |
JAMES | E | BORG | HEAD QUARTERS |
NULL | NULL | NULL | CSE |
SSN | FNAME | MINIT | LNAME | SALARY | DNO | DNUMBER | DNAME | MGR_SSN |
123456789 | JOHN | B | SMITH | 30000 | 5 | NULL | NULL | NULL |
333445555 | FRANKLIN | T | WONG | 40000 | 5 | 5 | RESEARCH | 333445555 |
999887777 | ALICIA | J | ZELAYA | 25000 | 4 | NULL | NULL | NULL |
987654321 | JENNIFER | S | WALLACE | 43000 | 4 | 4 | ADMINISTRATION | 987654321 |
666884444 | RAMESH | K | NARAYAN | 38000 | 5 | NULL | NULL | NULL |
453453453 | JOYCE | A | ENGLISH | 25000 | 5 | NULL | NULL | NULL |
987987987 | AHMOD | V | JABBA | 25000 | 4 | NULL | NULL | NULL |
888665555 | JAMES | E | BORG | 55000 | 1 | 1 | HEAD QUARTERS | 888665555 |
NULL | NULL | NULL | NULL | NULL | NULL | 3 | CSE | 1236784444 |
SNO | RELATIONAL ALGEBRA | RELATIONAL CALCULUS |
1. | It is a Procedural language i.e., step-by-step process for solving a problem. | While Relational Calculus is Declarative language (non-procedural) i.e., it focus only on the output of the programming. |
2. | Relational Algebra means how to obtain the result. | While Relational Calculus means what result we have to obtain. |
3. | In Relational Algebra, the order is specified in which the operations have to be performed. | While in Relational Calculus, The order is not specified. |
4. | Relational Algebra is independent on domain. | While Relation Calculus can be a domain dependent. |
5. | Relational Algebra is nearer to a programming language. | While Relational Calculus is not nearer to programming language. |
DIFFERENCES BETWEEN RELATIONAL ALGEBRA & RELATIONAL CALCULUS
RELATIONAL CALCULUS:
Relational calculus is a non-procedural query language that tells the system what data to be retrieved but doesn’t tell how to retrieve it.
Tuple relational calculus is used for selecting those tuples that satisfy the given condition.
In domain relational calculus the records are filtered based on the domains.
Tuple Relational Calculus
{t| P(t)}
where t = resulting tuples,� P(t) = known as Predicate and these are the conditions that are used to fetch t
P(t) Conditions:
Example:
FNAME | LNAME | AGE |
AJEET | SINGH | 30 |
CHAITANYA | SINGH | 31 |
RAJEEV | BHATIA | 27 |
CARL | PRATAP | 28 |
Table-1 Student
Example-1: Query to display the last name of those students where age is greater than 30
{ t.Last_Name | Student(t) AND t.age > 30 }
Output:
Last_Name
----------------
Singh
Example-2: Query to display all the details of students where Last name is ‘Singh’
{ t | Student(t) AND t.Last_Name = 'Singh' }
Output:
First_Name Last_Name Age
-----------------------------------------------------------
Ajeet Singh 30
Chaitanya Singh 31
Table-1: Customer
CUSTOMER NAME | STREET | CITY |
Saurabh | A7 | Patiala |
Mehak | B6 | Jalandhar |
Sumiti | D9 | Ludhiana |
Ria | A5 | Patiala |
Table-2: Branch
BRANCH NAME | BRANCH CITY |
ABC | Patiala |
DEF | Ludhiana |
GHI | Jalandhar |
Table-3: Account
ACCOUNT NUMBER | BRANCH NAME | BALANCE |
1111 | ABC | 50000 |
1112 | DEF | 10000 |
1113 | GHI | 9000 |
1114 | ABC | 7000 |
Table-4: Loan
LOAN NUMBER | BRANCH NAME | AMOUNT |
L33 | ABC | 10000 |
L35 | DEF | 15000 |
L49 | GHI | 9000 |
L98 | DEF | 65000 |
Table-5: Borrower
CUSTOMER NAME | LOAN NUMBER |
Saurabh | L33 |
Mehak | L49 |
Ria | L98 |
Table-6: Depositor
CUSTOMER NAME | ACCOUNT NUMBER |
Saurabh | 1111 |
Mehak | 1113 |
Sumiti | 1114 |
1: Find the loan number, branch, amount of loans of greater than or equal to 10000 amount.
{t| t ∈ loan ∧ t[amount]>=10000}
LOAN NUMBER | BRANCH NAME | AMOUNT |
L33 | ABC | 10000 |
L35 | DEF | 15000 |
L98 | DEF | 65000 |
2: Find the loan number for each loan of an amount greater or equal to 10000.
{t| ∃ s ∈ loan(t[loan number] = s[loan number] ∧ s[amount]>=10000)}
LOAN NUMBER |
L33 |
L35 |
L98 |
3: Find the names of all customers who have a loan and an account at the bank.
{t | ∃ s ∈ borrower( t[customer-name] = s[customer-name]) ∧ ∃ u ∈ depositor( t[customer-name] = u[customer-name])}
CUSTOMER NAME |
Saurabh |
Mehak |
4: Find the names of all customers having a loan at the “ABC” branch.
{t | ∃ s ∈ borrower(t[customer-name] = s[customer-name] ∧ ∃ u ∈ loan(u[branch-name] = “ABC” ∧ u[loan-number] = s[loan-number]))}
CUSTOMER NAME |
Saurabh |
DOMAIN RELATIONAL CALCULUS
{ < x1, x2, x3, ..., xn > | P (x1, x2, x3, ..., xn ) }
where, < x1, x2, x3, …, xn > represents resulting domains variables and
P (x1, x2, x3, …, xn ) represents the condition or formula equivalent to the Predicate calculus.
Predicate Calculus Formula:
The domain variables those will be in resulting relation must appear before | within ≺ and ≻ and all the domain variables must appear in which order they are in original relation or table.
CUSTOMER NAME | STREET | CITY |
Debomit | Kadamtala | Alipurduar |
Sayantan | Udaypur | Balurghat |
Soumya | Nutanchati | Bankura |
Ritu | Juhu | Mumbai |
Table-1: Customer
LOAN NUMBER | BRANCH NAME | AMOUNT |
L01 | Main | 200 |
L03 | Main | 150 |
L10 | Sub | 90 |
L08 | Main | 60 |
Table-2: Loan
Table-3: Borrower
CUSTOMER NAME | LOAN NUMBER |
Ritu | L01 |
Debomit | L08 |
Soumya | L03 |
1: Find the loan number, branch, amount of loans of greater than or equal to 100 amount.
{≺l, b, a≻ | ≺l, b, a≻ ∈ loan ∧ (a ≥ 100)}
LOAN NUMBER | BRANCH NAME | AMOUNT |
L01 | Main | 200 |
L03 | Main | 150 |
2: Find the loan number for each loan of an amount greater or equal to 150.
{≺l≻ | ∃ b, a (≺l, b, a≻ ∈ loan ∧ (a ≥ 150)}
LOAN NUMBER |
L01 |
L03 |
3: Find the names of all customers having a loan at the “Main” branch and find the loan amount .
{≺c, a≻ | ∃ l (≺c, l≻ ∈ borrower ∧ ∃ b (≺l, b, a≻ ∈ loan ∧ (b = “Main”)))}
CUSTOMER NAME | AMOUNT |
Ritu | 200 |
Debomit | 60 |
Soumya | 150 |
LOAN NUMBER | BRANCH NAME | AMOUNT |
L01 | Main | 200 |
L03 | Main | 150 |
L10 | Sub | 90 |
L08 | Main | 60 |
CUSTOMER NAME | LOAN NUMBER |
Ritu | L01 |
Debomit | L08 |
Soumya | L03 |
Table-3: Borrower
Table-2: Loan
Display the customer name and city who are having the loan number L1 and L3
Display loan no, customer name and city who took amount greater than 100$
{l,n,c|∃s(<n,s,c>)∈customer^∃b,a((<l,b,a>)∈loan^(a>100))^∃<n,l>∈Borrower}
INTEGRITY CONSTRAINTS:
Types of Integrity Constraint:
1. Domain constraints
2. Entity integrity constraints
Example:
3. Referential Integrity Constraints
4. Key constraints
Example:
VIEWS
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
SELECT column1, column2.....
FROM table_name
WHERE condition;
Creating View from a single table:
SQL>CREATE VIEW DetailsView AS
SELECT NAME, ADDRESS
FROM Student_Details
WHERE STU_ID < 4;
SQL>SELECT * FROM DetailsView;
NAME | ADDRESS |
Stephan | Delhi |
Kathrin | Noida |
David | Ghaziabad |
Creating View from multiple tables
Example:
SQL>CREATE VIEW MarksView AS
SELECT Student_Detail.NAME, Student_Detail.ADDRESS, Student_Marks.MARKS
FROM Student_Detail, Student_Mark
WHERE Student_Detail.NAME = Student_Marks.NAME;
SQL>SELECT * FROM MarksView;
NAME | ADDRESS | MARKS |
Stephan | Delhi | 97 |
Kathrin | Noida | 86 |
David | Ghaziabad | 74 |
Alina | Gurugram | 90 |
Deleting View
Syntax:
DROP VIEW view_name;
Example:
SQl>DROP VIEW MarksView;
Updating a View
There are certain conditions needed to be satisfied to update a view. If any one of these conditions is not met, then we will not be allowed to update the view.
Example:
update detailsview set sname='dutt' where address='delhi';
Inserting Rows into a View
Syntax:
SQL>INSERT INTO view_name(column1, column2 , column3,..) VALUES(value1, value2, value3..);
Example:
SQL>INSERT INTO DetailsView(NAME, ADDRESS) VALUES(‘Hari’,’Gurgaon’);
Deleting a row from a View:
Syntax:
DELETE FROM view_name WHERE condition;
Example:
SQL>delete from detailsview where sname='dutt';
Uses of a View :�A good database should contain views due to the given reasons:
Aggregate Functions example
We will be using SalesOrderDetail of Adventureworks database for the below examples.
Sum()
Select sum (OrderQty) [Total Quantity] from [Sales].[SalesOrderDetail]
This sums up the OrderQty column value of SalesOrderDetail table.
The output is
Avg()
select avg(OrderQty) [Total Quantity] from [Sales].[SalesOrderDetail]
This gives the average of OrderQty column of SalesOrderDetail table.
Max()
select max(OrderQty) [Total Quantity] from [Sales].[SalesOrderDetail]
This gives out the maximum value of the OrderQty column of [SalesOrderDetail] table.
Min()
select min(OrderQty) [Total Quantity] from [Sales].[SalesOrderDetail]
This gives out the minimum value of the OrderQty column of [SalesOrderDetail] table.
Count()
Select count (*) from [Person]. [Person]
Returns total number of records in the Person table
1.Min Aggregate Function :
The Min aggregate function stands for the minimum. It returns the minimum value by checking the whole column.To calculate the minimum value in the column of the table the column must be in number datatype format.
Syntax :
min(number_column)
Select Min(number_column) from tablename;
Select Min(Number-column) from tablename where condition;
These are above different syntax of Min function. Let say you need to find out the minimum grade for the Employees for specific course from Employee table.
Select Min(grade) from Employee;
The above query will give you the minimum grade for Employees. Make sure that the grade column is in numeric format. If you want to find out the Min grade for the Department name Security then following query is helpful.
Select Min(grade)from Employee where department=’Security’;
The above query will give you the minimum grade from Employee table where department name is security.
2. Max Aggregate Function :
The Max aggregate function stands for the Maximum. It returns the maximum value by checking the whole column.To calculate the maximum value in the column of the table the column must be in number datatype format.
Syntax :
max(number_column)
Select Max(number_column) from tablename;
Select Max(Number-column) from tablename where condition;
These are above different syntax of Max function. Let say you need to find out the maximum grade for the Employees for specific course from Employee table.
Select Max(grade) from Employee;
The above query will give you the maximum grade for Employees.Make sure that the grade column is in numeric format.If you want to find out the Max grade for the Department name Security then following query is helpful.
Select Max(grade)from Employee where department=’Security’;
The above query will give you the maximum grade from Employee table where department name is security.
3. Avg Aggregate Function :
The Avg aggregate function is one of the most used SQL Aggregate function.This function provides you the Average of the given column.Calculating average value of given column is useful in different purpose. The calculating average of specific column is used in different reports as well.The Avg is abbreviation of Average.The column must be in number format to calculate its Average.
Syntax :
Avg(number_column)
Select Avg(number_column) from tablename;
Select Avg(Number-column) from tablename where condition;
These are above different syntax of avg function. Lets say user needs to calculate the average salary of the employee. This expression is most used expression in HR reporting.
Select Avg(salary) from Employee;
Select Avg(salary) from Employee where department=’Business Intelligence’;
Select Avg(salary) from Employee where department=’Business Intelligence’ group by position;
4.Count Aggregate function:
This function is undoubtedly most used aggregate function.The count function is used to calculate the count of the rows in the specified column. There are so many scenarios where user needs to calculate the count of the rows.The Count function is most used function in reporting and analytics.
Syntax :
A) COUNT (Numeric_Column_Name)
B) COUNT (*)
C) COUNT (DISTINCT Column_Name)
Example 1: Calculate the count of Employees from Employee table.
Select count(*) from Employees;
Example 2 : Calculate the count of Employees who are software Engineers
Select count(Eno) from Employees where job_title=’Software Engineer’;
Example 3 : Calculate the count of Employees who are Software Engineer by removing duplicate Employees.This is most common scenario where user needs to remove duplicates. If the Employee table does not have any constraints then the values from Employee table gets duplicated.In that case user needs to use distinct keyword before counting the column name.
Select count(distinct Eno) from Employees where job_title=’Software Engineer’;
5.Sum Aggregate Function :
There are lot of times user will confused in Avg function and Sum function.The Sum function calculates the sum of the numeric column.
Syntax:
Sum(number_column)
Select Sum(number_column) from tablename;
Select Sum(Number-column) from tablename where condition;
Lets say user wants to calculate the total salary from Employees table.
Select Sum(salary) from Employees;
There are scenarios where user wants to calculate the sum of the salary departmentwise.
Select Sum(salary) from Employees where deparment_name=’Software’;
String Function Example
LTRIM()
Removes space from left side of the string
select ltrim(' tes')
RTRIM()
Removes space from left side of the string
select Rtrim('tes ')
Len()
Gives the length of the string.
select Len('Test')
LEFT()
select Left('Sanchayan',3)
This SQL Statement extracts three characters from the left side of the string.
RIGHT()
select Right('Sanchayan',3)
The above SQL Statement extracts three characters from the right side of the string
Examples of Date function
GETDATE()
Gives out the current date
select GETDATE()
DATEADD()
SELECT DATEADD (month, 1, '20060830');
Add a month with the date value 20060830
DAY()
select day('12/18/2019')
The SQL Statement gives the current day value of the date passed as parameter.
MONTH()
select MONTH('12/18/2019')
The SQL Statement gives the current month value of the date passed as parameter.
YEAR()
select YEAR('12/18/2019')
The SQL Statement gives the current year value of the date passed as parameter.
CAST()
SELECT CAST(25.65 AS int)
This converts the value 25.65 into integer.
The output is
CONVERT()
Converts a string into a different data type here integer.
SELECT CONVERT(int, 25.65);
The output is as below
CURRENT_USER
This advance function gives out the current user of the system
select CURRENT_USER
ISNUMERIC()
This function checks whether the parameter passed in it is numeric or not.
select ISNUMERIC(5)
This gives out 1 if true and 0 if false.