You are on page 1of 31

Different Sql Functions With Examples: 

Functions are used to perform


actions on a single value or a table. Functions accept values, take
action on it and then give desired results. Functions cannot be used to
insert, delete or update the values. To perform operations on data, sql server
gives many functions, SQL supports distinct types of functions and these sql server
functions are as follows:

Different Sql Functions With Examples


 Numeric functions
 String functions
 Aggregate functions
 Date functions
 Conversion functions

1. Numeric functions:
Abs ( ): this function is used to convert a negative value to positive value.
Syntax: abs(No.)
Example:
Sql >select abs(100-120) from dual;
Output: 20
Sqrt ( ): this function returns the square root of a given number.
Syntax _ SQRT (No.)
Example:
SQL> select SQRT (81) from dual;
Output: 9
Mod ( ): this function returns the modulus.
Syntax: mod (dividend, divisor)
Example:
SQL> select mod (15,2) from dual,
Output: 1
Power ( ): this function returns the power of given number as per the raised
number specified.
Syntax: power (number, raised number)
Example:
SQL> select power (4, 3) from dual;
Output: 64
Round ( ): this function is used to round off the required number of decimals.
Syntax – round (No., No. of decimals)
Example:
SQL> select round (23.6789, 2) from dual;
Output: 23.68

2. String functions:
Upper ( ): this function converts a string into upper case.
Syntax: upper (‘string’)
Example:
Sql> select upper (‘hello’) from dual;
Output: HELLO
Lower ( ): this function converts a string into lower case.
Syntax: lower (‘string’)
Example:
Sql> select upper (‘HELLO’) from dual;
Output: hello
Initcap ( ): this function converts a string into initial caps.
Syntax: initcap (‘string’)
Example:
Sql> select initcap (‘computer education’) from dual;
Output: Computer Education
Itrim ( ): this function is availed to remove the unnecessary spaces or characters
available to a string.
Syntax: Itrim (‘string’, ‘unnecessary char’)
Example:
Sql> select Itrim (‘xyxyhello’, ‘xy’)
Output: hello
Rtrim ( ): this function is used to remove the unnecessary characters or spaces
available on the right side of a string.
Syntax: rtrim (‘string’, ‘unnecessary char’)
Example:
Sql> select rtrim (‘computerxyzxy’, ‘xy’) from dual;
Output: computerxyz

3. Aggregate functions:
Aggregate functions return single values by performing action of a group of values.
consider the following example of table Emp to simply understand its working
Table Emp

Emp_id Name Salary Age


350 Mark 55000 28
351 Steve 60000 30
352 Roser 60000 31
353 Joseph 75000 34

354 Avlin 90000 32


Sum ( ): this function calculates a sum of a group of values.
Syntax: sum(col _name)
Example:
Select sum(salary) from Emp;
Output:
340000
Average ( ): this function returns the average of group of values.
Syntax: average(col _name)
Example:
Select avg(salary) from Emp;
Output:
68000
Max ( ): this function returns the highest value from group of values.
Syntax: max(col _name)
Example:
Select max(salary) from Emp;
Output:
90000
Min ( ): this function returns the least value from group of values.
Syntax: min(col _name)
Example:
Select min(salary) from Emp;
Output
55000
Count ( ): this function counts the number of values in a group.
Syntax: count(col _name)
Example:
Select count(name) from Emp where salary = 60000;
Output:
2

4. Date functions:
Sysdate: this function returns the system date in the format of dd-mm-yy.
Syntax: sql> select sysdate from dual;
Last_ day ( ): this function returns the last date of a given date.
Syntax: last _day(date)
Next _ day ( ): this function returns the next date of a given date.
Syntax: next _day (date, ‘dy’)
Add _ months ( ): this function is availed to add or subtract the number of months
to a given date.
Syntax: add _months(date, no. of months)
Months _ between ( ): this function returns the number of months present
between two given dates.
Syntax: months _between(date1, date2)

5. Conversion functions:
To _ char ( ): this function converts a string or value into characters or in a
specified format.
Syntax: to_ char(value, ‘format’);
To _ date ( ): this function is used to convert a string value into date format.
Syntax: to _date(‘value’, ‘format’);
To _ number ( ): this function converts a string value into numeric.
Syntax: to_ number(‘value’);
SQL provides many built-in functions to perform operations on data. These functions are
useful while performing mathematical calculations, string concatenations, sub-strings
etc. SQL functions are divided into two categories,

1. Aggregate Functions
2. Scalar Functions

Aggregate Functions
These functions return a single value after performing calculations on a group of
values. Following are some of the frequently used Aggregate functions.

AVG() Function
Average returns average value after calculating it from values in a numeric column.
Its general syntax is,
SELECT AVG(column_name) FROM table_name

Using AVG() function


Consider the following Emp table

eid name age salary

401 Anu 22 9000

402 Shane 29 8000

403 Rohan 34 6000

404 Scott 44 10000

405 Tiger 35 8000


SQL query to find average salary will be,
SELECT avg(salary) from Emp;
Result of the above query will be,

avg(salary)

8200

COUNT() Function
Count returns the number of rows present in the table either based on some condition or
without condition.
Its general syntax is,
SELECT COUNT(column_name) FROM table-name

Using COUNT() function


Consider the following Emp table

eid name age salary

401 Anu 22 9000

402 Shane 29 8000

403 Rohan 34 6000

404 Scott 44 10000

405 Tiger 35 8000

SQL query to count employees, satisfying specified condition is,


SELECT COUNT(name) FROM Emp WHERE salary = 8000;
Result of the above query will be,

count(name)

Example of COUNT(distinct)
Consider the following Emp table

eid name age salary

401 Anu 22 9000

402 Shane 29 8000

403 Rohan 34 6000

404 Scott 44 10000

405 Tiger 35 8000

SQL query is,


SELECT COUNT(DISTINCT salary) FROM emp;
Result of the above query will be,

count(distinct salary)

FIRST() Function
First function returns first value of a selected column
Syntax for FIRST function is,
SELECT FIRST(column_name) FROM table-name;

Using FIRST() function


Consider the following Emp table

eid name age salary

401 Anu 22 9000

402 Shane 29 8000

403 Rohan 34 6000

404 Scott 44 10000

405 Tiger 35 8000

SQL query will be,


SELECT FIRST(salary) FROM Emp;
and the result will be,

first(salary)

9000

LAST() Function
LAST function returns the return last value of the selected column.
Syntax of LAST function is,
SELECT LAST(column_name) FROM table-name;
Using LAST() function
Consider the following Emp table

eid name age salary

401 Anu 22 9000

402 Shane 29 8000

403 Rohan 34 6000

404 Scott 44 10000

405 Tiger 35 8000

SQL query will be,


SELECT LAST(salary) FROM emp;
Result of the above query will be,

last(salary)

8000

MAX() Function
MAX function returns maximum value from selected column of the table.
Syntax of MAX function is,
SELECT MAX(column_name) from table-name;

Using MAX() function


Consider the following Emp table
eid name age salary

401 Anu 22 9000

402 Shane 29 8000

403 Rohan 34 6000

404 Scott 44 10000

405 Tiger 35 8000

SQL query to find the Maximum salary will be,


SELECT MAX(salary) FROM emp;
Result of the above query will be,

MAX(salary)

10000

MIN() Function
MIN function returns minimum value from a selected column of the table.
Syntax for MIN function is,
SELECT MIN(column_name) from table-name;

Using MIN() function


Consider the following Emp table,

eid name age salary

401 Anu 22 9000


402 Shane 29 8000

403 Rohan 34 6000

404 Scott 44 10000

405 Tiger 35 8000

SQL query to find minimum salary is,


SELECT MIN(salary) FROM emp;
Result will be,

MIN(salary)

6000

SUM() Function
SUM function returns total sum of a selected columns numeric values.
Syntax for SUM is,
SELECT SUM(column_name) from table-name;

Using SUM() function


Consider the following Emp table

eid name age salary

401 Anu 22 9000

402 Shane 29 8000


403 Rohan 34 6000

404 Scott 44 10000

405 Tiger 35 8000

SQL query to find sum of salaries will be,


SELECT SUM(salary) FROM emp;
Result of above query is,

SUM(salary)

41000

Scalar Functions
Scalar functions return a single value from an input value. Following are some frequently
used Scalar Functions in SQL.

UCASE() Function
UCASE function is used to convert value of string column to Uppercase characters.
Syntax of UCASE,
SELECT UCASE(column_name) from table-name;

Using UCASE() function


Consider the following Emp table

eid name age salary


401 anu 22 9000

402 shane 29 8000

403 rohan 34 6000

404 scott 44 10000

405 Tiger 35 8000

SQL query for using UCASE is,


SELECT UCASE(name) FROM emp;
Result is,

UCASE(name)

ANU

SHANE

ROHAN

SCOTT

TIGER

LCASE() Function
LCASE function is used to convert value of string columns to Lowecase characters.
Syntax for LCASE is,
SELECT LCASE(column_name) FROM table-name;
Using LCASE() function
Consider the following Emp table

eid name age salary

401 Anu 22 9000

402 Shane 29 8000

403 Rohan 34 6000

404 SCOTT 44 10000

405 Tiger 35 8000

SQL query for converting string value to Lower case is,


SELECT LCASE(name) FROM emp;
Result will be,

LCASE(name)

anu

shane

rohan

scott

tiger

MID() Function
MID function is used to extract substrings from column values of string type in a table.
Syntax for MID function is,
SELECT MID(column_name, start, length) from table-name;

Using MID() function


Consider the following Emp table

eid name age salary

401 anu 22 9000

402 shane 29 8000

403 rohan 34 6000

404 scott 44 10000

405 Tiger 35 8000

SQL query will be,


SELECT MID(name,2,2) FROM emp;
Result will come out to be,

MID(name,2,2)

nu

ha

oh

co
ig

ROUND() Function
ROUND function is used to round a numeric field to number of nearest integer. It is used
on Decimal point values.
Syntax of Round function is,
SELECT ROUND(column_name, decimals) from table-name;

Using ROUND() function


Consider the following Emp table

eid name age salary

401 anu 22 9000.67

402 shane 29 8000.98

403 rohan 34 6000.45

404 scott 44 10000

405 Tiger 35 8000.01

SQL query is,


SELECT ROUND(salary) from emp;
Result will be,

ROUND(salary)

9001
8001

6000

10000

8000

Integrity Constraints in DBMS

Databases, as we all know have become an essential part of any software.


These are better than MS excel or file system because they store the data in an
organized manner. Thus the data retrieval also becomes easy. In addition
databases also provide a facility of applying constraints on certain type of data.
There are various kinds of constraints that can be applied. This article deals
with those constraints.

What are integrity constraints?

Integrity constraints are rules that are to be applied on database columns to


ensure the validity of data. Every time data is entered into that particular
column, it is evaluated against the constraint and only if the result comes out
to be true, then the data is inserted into the column. Thus these constraints
help to maintain the integrity of the data. These are applied as a set of rules
which ensure data quality requirements, hence the name integrity constraints.
The database manages consistency of the same data across different tables
through the integrity constraints. Thus integrity constraints are extremely
essential as they constantly check that the changes made in the database by
any authorized user do not create any inconsistency.

There are various types of integrity constraints that the database provides.
Each has its own function and each ensures data integrity in its own way.
Integrity constraints can be divided into the following:

Entity integrity constraint


Domain Integrity constraint

 Referential Integrity constraint


 Entity Integrity Constraint:

Entity integrity constraints as the name implies is applied on each entity. i.e.
it is applied on individual rows. The constraint here is to have a unique
value for each row in the column or a group of columns it is applied to. This
attribute is essential when a particular record or row of data is to be
accessed. It can be accessed using the entity integrity constraint by
supplying the unique value and accessing the entire record.

There are two such constraints which ensure uniqueness of data. They are-

Primary key
Unique keyword

Primary key ensures that values in a column are unique so that duplicate
values are not allowed and also the primary key column cannot be null.
Thus it focuses on two properties- uniqueness and not null. A table can
contain only one primary key. Primary key can consist of a column or a
group of columns. It is used to uniquely identify records in a table.

Unique keyword is just like the primary key but it allows null values. Both
these are defined on columns during defining the structure of table. Thus
these are used in data definition language.
Domain Integrity Constraints:

These are the constraints on the domain value and thus are column level
constraints unlike entity integrity constraint which are row level. The domain
integrity constraints are used to impose restrictions on some particular
column. Thus they affect the domain value. These can be enforced in the form
of the following-

Check value
Default value
Check is used to impose certain checks like checking if a value is greater than
or lesser than a particular value etc. thus the upper and the lower limit can be
set. 

Default value is the value to be provided in case no value is provided by the


user. We can set a default value for any column depending on its data-type.
These are also used during defining the structure of the tables, in the data
definition language statements.
Referential Integrity Constraint:
Referential integrity constraint makes sure that the values in the column on
which it is applied are already present in the column it is referring to. Thus
here a column of a table refers to the other column of the same or different
table. This ensures that the values are consistent and similar in both the
columns. This is implemented using-

Foreign key
Foreign key normally references the primary key of same or another table. But
it can refer to other columns too. Whenever, same type of attribute exists in
two different tables, the attribute in one of the table is declared as the primary
key and in the other, it is made foreign key, so that the values in both become
consistent. Foreign key is dependent on primary key.

Generalization –
Generalization is the process of extracting common properties from a set of entities and
create a generalized entity from it. It is a bottom-up approach in which two or more entities
can be generalized to a higher level entity if they have some attributes in common. For
Example, STUDENT and FACULTY can be generalized to a higher level entity called PERSON
as shown in Figure 1. In this case, common attributes like P_NAME, P_ADD become part of
higher entity (PERSON) and specialized attributes like S_FEE become part of specialized
entity (STUDENT).

Specialization –
In specialization, an entity is divided into sub-entities based on their characteristics. It is a
top-down approach where higher level entity is specialized into two or more lower level
entities. For Example, EMPLOYEE entity in an Employee management system can be
specialized into DEVELOPER, TESTER etc. as shown in Figure 2. In this case, common
attributes like E_NAME, E_SAL etc. become part of higher entity (EMPLOYEE) and specialized
attributes like TES_TYPE become part of specialized entity (TESTER).

Specialization

For example : In a database of hospital, a person can either be a doctor,
staff or patient which can be spirited according to their functions
and specialties.
 
Specialization : Example

2. Generalization

 For example : Goat, Lion and Monkey have some come traits and they
all together can be combined in class of animals.
 

Generalization: Example

BASIS FOR
GENERALIZATION SPECIALIZATION
COMPARISON

Basic It proceeds in a bottom-up It proceeds in a top-down


BASIS FOR
GENERALIZATION SPECIALIZATION
COMPARISON

manner. manner.

Function Generalization extracts the Specialization splits an entity

common features of multiple to form multiple new entities

entities to form a new that inherit some feature of

entity. the splitting entity.

Entities The higher level entity must The higher level entity may

have lower level entities. not have lower level entities.

Size Generalization reduces the Specialization increases the

size of a schema. size of a schema.

Application Generalization entities on Specialization is applied on a

group of entities. single entity.

Result Generalization results in Specialization results in

forming a single entity from forming the multiple entity

multiple entities. from a single entity.

Constraints on specialization/generalization
There are three constraints that may apply to a specialization/generalization:
membership constraints, disjoint constraints and completeness constraints.
 Membership constraints
Condition defined: Membership of a specialization/generalization
relationship can be defined as a condition in the requirements e.g.
tanker is a ship where cargo = “oil”
User defined: Sometimes the designer can define the superclass-
subclass relationship. This can be done to simplify the design model or
represent a complex relationship that exists between entities.
 Disjoint constraints
Disjoint: The disjoint constraint only applies when a superclass has more
than one subclass. If the subclasses are disjoint, then an entity
occurrence can be a member of only one of the subclasses, e.g.
postgrads or undergrads – you cannot be both. To represent a disjoint
superclass/subclass relationship, ‘Or’ is used.

Overlapping: This applies when an entity occurrence may be a member of


more than one subclass, e.g. student and staff – some people are both.
‘And’ is used to represent the overlapping specialization/generalization
relationship in the ER diagram.

Figure 7.14
 Completeness constraints
Total: Each superclass (higher-level entity) must belong to subclasses
(lower-level entity sets), e.g. a student must be postgrad or undergrad.
To represent completeness in the specialization/generalization
relationship, the keyword ‘Mandatory’ is used.
Partial: Some superclasses may not belong to subclasses (lower-level
entity sets), e.g. some people at UCT are neither student nor staff. The
keyword ‘Optional’ is used to represent a partial
specialization/generalization relationship.

We can show both disjoint and completeness constraints in the ER diagram.


Following our examples, we can combine disjoint and completeness
constraints.

Some members of a university are both students and staff. Not all members of
the university are staff and students.
A student in the university must be either an undergraduate or postgraduate,
but not both.

What is an Entity Relationship Diagram (ER Diagram)?

An ER diagram shows the relationship among entity sets. An entity set is a


group of similar entities and these entities can have attributes. In terms of
DBMS, an entity is a table or attribute of a table in database, so by showing
relationship among tables and their attributes, ER diagram shows the complete
logical structure of a database. Lets have a look at a simple ER diagram to
understand this concept.

A simple ER Diagram:

In the following diagram we have two entities Student and College and their
relationship. The relationship between Student and College is many to one as a
college can have many students however a student cannot study in multiple
colleges at the same time. Student entity has attributes such as Stu_Id,
Stu_Name & Stu_Addr and College entity has attributes such as Col_ID &
Col_Name.
Here are the geometric shapes and their meaning in an E-R Diagram. We will
discuss these terms in detail in the next section(Components of a ER Diagram)
of this guide so don’t worry too much about these terms now, just go through
them once.

Rectangle: Represents Entity sets.


Ellipses: Attributes
Diamonds: Relationship Set
Lines: They link attributes to Entity Sets and Entity sets to Relationship Set
Double Ellipses: Multivalued Attributes
Dashed Ellipses: Derived Attributes
Double Rectangles: Weak Entity Sets
Double Lines: Total participation of an entity in a relationship set

Components of a ER Diagram
1. Entity

An entity is an object or component of data. An entity is represented as


rectangle in an ER diagram.
For example: In the following ER diagram we have two entities Student and
College and these two entities have many to one relationship as many students
study in a single college. We will read more about relationships later, for now
focus on entities.

Weak Entity:
An entity that cannot be uniquely identified by its own attributes and relies on
the relationship with other entity is called weak entity. The weak entity is
represented by a double rectangle. For example – a bank account cannot be
uniquely identified without knowing the bank to which the account belongs, so
bank account is a weak entity.

2. Attribute

An attribute describes the property of an entity. An attribute is represented as


Oval in an ER diagram. There are four types of attributes:

1. Key attribute
2. Composite attribute
3. Multivalued attribute
4. Derived attribute
1. Key attribute:

A key attribute can uniquely identify an entity from an entity set. For example,
student roll number can uniquely identify a student from a set of students. Key
attribute is represented by oval same as other attributes however the text of
key attribute is underlined.

2. Composite attribute:

An attribute that is a combination of other attributes is known as composite


attribute. For example, In student entity, the student address is a composite
attribute as an address is composed of other attributes such as pin code, state,
country.
3. Multivalued attribute:

An attribute that can hold multiple values is known as multivalued attribute. It


is represented with double ovals in an ER Diagram. For example – A person can
have more than one phone numbers so the phone number attribute is
multivalued.

4. Derived attribute:

A derived attribute is one whose value is dynamic and derived from another
attribute. It is represented by dashed oval in an ER Diagram. For example –
Person age is a derived attribute as it changes over time and can be derived
from another attribute (Date of birth).

E-R diagram with multivalued and derived attributes:

3. Relationship

A relationship is represented by diamond shape in ER diagram, it shows the


relationship among entities. There are four types of relationships:
1. One to One
2. One to Many
3. Many to One
4. Many to Many

1. One to One Relationship

When a single instance of an entity is associated with a single instance of


another entity then it is called one to one relationship. For example, a person
has only one passport and a passport is given to one person.

2. One to Many Relationship

When a single instance of an entity is associated with more than one instances
of another entity then it is called one to many relationship. For example – a
customer can place many orders but a order cannot be placed by many
customers.

3. Many to One Relationship

When more than one instances of an entity is associated with a single instance
of another entity then it is called many to one relationship. For example –
many students can study in a single college but a student cannot study in many
colleges at the same time.

4. Many to Many Relationship

When more than one instances of an entity is associated with more than one
instances of another entity then it is called many to many relationship. For
example, a can be assigned to many projects and a project can be assigned to
many students.

Total Participation of an Entity set

A Total participation of an entity set represents that each entity in entity set
must have at least one relationship in a relationship set. For example: In the
below diagram each college must have at-least one associated Student.

You might also like