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

sql_functions

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

sql_functions

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 94

Constraints

The oracle server uses constraints to prevent invalid data entry into
tables. Constraints prevent the deletion of a table if there are
dependencies.
Data integrity Constraints

Constraint Description

NOT NULL Specifies that the column cannot contain a null value

UNIQUE Specifies a column or combination of columns whose values must be


unique for all rows in the table

PRIMARY Uniquely identifies each row of the table


KEY
FOREIGN KEY Establishes and enforces a foreign key relationship between the
column and a column of the referred table.

1
CHECK Specifies a condition that must be true
Constraint guidelines
• All constraints are stored in data dictionary.

• Create a constraint either:


-at the same time as the table is created or
-after the table has been created.

• We can define a constraint at the column or table


level.

2
 Constraints can be defined in two ways

1) The constraints can be specified immediately after the
column definition. This is called column-level definition.
If data constraints are defined as an attribute of a column
definition when creating or altering a table, they are
column level constraints.

2) The constraints can be specified after all the columns


are defined. This is called table-level definition. If data
constraints are defined after defining all table column
attributes when creating or altering a table structure, it is
a table level constraints.
3
Defining Constraints
CREATE TABLE table_name
(column datatype [column_constraint],
…………..
[table_constraint][….]);

Example:
CREATE TABLE employee(emp_id NUMBER(6),
first_name VARCHAR2(20),
…….
job_id VARCHAR2(10) NOT NULL,
CONSTRAINT emp_id_pk PRIMARY KEY
(emp_id));

4
SQL Not Null Constraint :
• This constraint ensures all rows in the table contain a definite
value for the column which is specified as not null. Which means
a null value is not allowed.
• Syntax:
[CONSTRAINT constraint_ name] NOT NULL
• Example:
• To create a employee table with Null value, the query would be
like,
CREATE TABLE employee
( id number(5),
name char(20) CONSTRAINT nm NOT NULL,
dept char(10),
age number(2),
salary number(10),
location char(10)
5
);
SQL Unique Key

• This constraint ensures that a column or a group of


columns in each row have a distinct value. A
column(s) can have a null value but the values cannot
be duplicated.
• Syntax to define a Unique key at column level:
[CONSTRAINT constraint_name] UNIQUE

• Syntax to define a Unique key at table level:


[CONSTRAINT constraint_name]
UNIQUE (column_name)

6
Example

• To create an employee table with Unique key, the query


would be like,
Unique Key at column level:

CREATE TABLE employee


( id number(5) PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10) UNIQUE
);

7
Unique Key at table level:

• CREATE TABLE employee


( id number(5) PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10),
CONSTRAINT loc_un UNIQUE(location)
);

8
SQL Primary key

• This constraint defines a column or combination of


columns which uniquely identifies each row in the
table.
• Syntax to define a Primary key at column level:
column_name datatype
[CONSTRAINT constraint_name] PRIMARY KEY
• Syntax to define a Primary key at table level:
[CONSTRAINT constraint_name] PRIMARY KEY
(column_name1,column_name2,..)
column_name1, column_name2 are the names of the
columns which define the primary Key.
• The syntax within the bracket i.e. [CONSTRAINT
constraint_name] is optional. 9
• Example: To create an employee table with Primary Key
constraint, the query would be like,
• Primary Key at column level:

CREATE TABLE employee


( id number(5) PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10)
);

10
• Primary Key at table level:
CREATE TABLE employee
( id number(5),
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10),
CONSTRAINT emp_id_pk PRIMARY KEY (id)
);

11
SQL Foreign key or Referential Integrity

• This constraint identifies any column referencing the


PRIMARY KEY in another table.

• It establishes a relationship between two columns in


the same table or between different tables.

• For a column to be defined as a Foreign Key, it


should be defined as a Primary Key in the table which
it is referring.

• One or more columns can be defined as Foreign key.


12
• Syntax to define a Foreign key at column
level:
[CONSTRAINT constraint_name] REFERENCES
Referenced_Table_name(column_name)

• Syntax to define a Foreign key at table


level:

[CONSTRAINT constraint_name] FOREIGN KEY


(column_name) REFERENCES
referenced_table_name(column_name);
13
Example:
• Consider "product" table and "order_items".
Foreign Key at column level:
CREATE TABLE product
( product_id number(5) CONSTRAINT pd_id_pk PRIMARY KEY,
product_name char(20),
supplier_name char(20),
unit_price number(10)
);
OR CREATE TABLE order_items
( order_id number(5) CONSTRAINT od_id_pk PRIMARY KEY,
product_id number(5) CONSTRAINT pd_id_fk
REFERENCES product(product_id),
product_name char(20),
supplier_name char(20),
unit_price number(10)
);
14
• Foreign Key at table level:
CREATE TABLE order_items
( order_id number(5) ,
product_id number(5),
product_name char(20),
supplier_name char(20),
unit_price number(10)
CONSTRAINT od_id_pk PRIMARY KEY(order_id),
CONSTRAINT pd_id_fk FOREIGN KEY(product_id)
REFERENCES product(product_id)
);

15
• If the employee table has a 'mgr_id' i.e, manager id
as a foreign key which references primary key 'id'
within the same table, the query would be like,

• CREATE TABLE employee


( id number(5) PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
mgr_id number(5) REFERENCES employee(id),
salary number(10),
location char(10)
);
16
SQL Check Constraint

• The constraint can be applied for a single column or a group of columns.

• Syntax to define a Check constraint:


[CONSTRAINT constraint_name] CHECK (condition)

• Example: In the employee table to select the gender of a person, the


query would be like,

• Check Constraint at column level:


CREATE TABLE employee
( id number(5) PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
gender char(1) CHECK (gender in ('M','F')),
salary number(10),
location char(10)
); 17
• Check Constraint at table level:

CREATE TABLE employee


( id number(5) PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
gender char(1),
salary number(10),
location char(10),
CONSTRAINT gender_ck CHECK (gender in ('M','F'))
);

18
Subquery
• Subquery or Inner query or Nested query is a query in a
query. A subquery is usually added in the WHERE
clause of the sql statement.
• Most of the time, a subquery is used when you know
how to search for a value using a SELECT statement,
but do not know the exact value.
• Subqueries are an alternate way of returning data from
multiple tables.
• Subqueries can be used with the following sql
statements along with the comparison operators like =,
<, >, >=, <= etc.(these are considered as single-row
operators) while IN,ANY,ALL these are considered as
multiple row operators.
19
• A subquery is a SELECT statement that is embedded in a clause of
another SELECT statement.

• The subquery (inner query) executes once before the main query.

• The result of the subquery is used by the main query(outer query).

• They can be very useful when you need to select rows from a table
with a condition that depends on the data in the table itself.

• The subquery can place in a number of SQL clauses, including:


 WHERE clause
 HAVING clause
 FROM clause
20
Guidelines for using Subqueries
• Enclose subqueries in parentheses.
• Place subqueries on the right side of the
comparison condition
• Syntax:
SELECT select_list
FROM table
WHERE expr operator (SELECT select_list
FROM table);

Operator includes a comparison condition such as >,=,or IN

21
Example: student_details;

id first_name last_name age subject games


100 abc gg 20 Science Cricket
101 xyz pp 22 Maths Football
102 pqr zz 29 Science Cricket
103 lmn aa 28 Maths Badminton
104 def bb 25 History Chess

22
• For Example:
• 1) Usually, a subquery should return only one record, but
sometimes it can also return multiple records when used with
operators like IN, NOT IN in the where clause. The query
would be like,
SELECT first_name, last_name, subject
FROM student_details
WHERE games NOT IN ('Cricket', 'Football');
• The output would be similar to:

first_name last_name subject


lmn aa Badminton
def bb Chess

23
• 2) If you know the name of the students who are
studying science subject, you can get their id's by using
following query:
SELECT id, first_name
FROM student_details
WHERE first_name IN (‘abc', ‘pqr');

• But, if you do not know their names, then to get their


id's you need to write the query like this,
SELECT id, first_name
FROM student_details
WHERE first_name IN (SELECT first_name
FROM student_details
WHERE subject= 'Science');

24
first_name
id

100 abc
102 pqr

In the above sql statement, first the inner query is processed


and then the outer query is processed.

25
Example-employee table
Employee_id EMP_Name Job_id Salary Department
_id
100 ABC ST_Clerk 20000 90
102 XYZ Manager 50000 60
103 PQR Accountant 30000 70
104 LMN Assistant 40000 10
105 DEF ST_Clerk 20000 90
106 JKL Assistant 40000 10

26
• List out names of those employees whose
salary is greater than employee ‘DEF’

SELECT EMP_Name
FROM employee
WHERE salary > 20000

(SELECT salary
FROM employee
WHERE EMP_Name=‘DEF’)
27
Types of subqueries

• Single-row subquery:- Queries that return only one row


from the inner SELECT statement.

• Multiple-row subquery:-Queries that return more than


one row from the inner SELECT statement.

• Multiple-column subquery:-Queries that return more


than one column from the inner SELECT statement.

28
Single-row subquery
• It returns only one row
• Use single row comparison operators
• Query: Display the employees whose job id is
same as that of employee 105
SELECT EMP_Name, job_id
Employee_id EMP_Name
FROM employee 100 ABC
WHERE job_id= 105 DEF

(SELECT job_id
FROM employee
WHERE employee_id=105)
29
Multiple-row subquery
• Return more than one row.
• Use multiple-row comparison operators

Operator Meaning
IN Equal to any member in the
list
ANY Compare value to each value
returned by the subquery
ALL Compare value to every value
returned by the subquery

30
Using the IN Operator in multiple-row subqueries

• Subqueries that return more than one row are called


multiple-row subqueries.
• You use a multiple-row operator, instead of a single-
row operator, with a multiple-row subquery.
• The multiple-row operator expects one or more
values.

SELECT last_name,salary,Depatment_id
FROM employee
WHERE salary IN (SELECT MIN(salary)
FROM employee
Group BY department_id); 31
• Example:
• Find the employees who earn the same salary as the minimum
salary for each department.
• Here, the inner query is executed first, producing a query
result. The main query block is then processed and uses the
values returned by the inner query to complete its search
condition. Hence the query would be:

SELECT EMP_name, salary, Depatment_id


FROM employee
WHERE salary IN (,,,,,,,,,,)

32
Example

Employee_id EMP_Name Job_id Salary Departmen


t_id
100 ABC ST_Clerk 20000 90
102 XYZ Manager 50000 60
103 PQR Accountant 30000 70
104 LMN Assistant 15000 10
105 DEF ST_Clerk 25000 90
106 JKL Assistant 10000 10
107 UVW Adviser 22000 30

33
SQL WHERE, ANY, ALL Clause
• ANY and ALL keywords are used with a
WHERE or HAVING clause.

• ANY and ALL operate on subqueries that return


multiple values.

• ANY returns true if any of the subquery values


meet the condition.

• ALL returns true if all of the subquery values


meet the condition. 34
• "x = ANY (...)": The value must match one or more values in the list to
evaluate to TRUE.

• "x != ANY (...)": The value must not match one or more values in the
list to evaluate to TRUE.

• "x > ANY (...)": The value must be greater than the smallest value in
the list to evaluate to TRUE.

• "x < ANY (...)": The value must be smaller than the biggest value in the
list to evaluate to TRUE.

• "x >= ANY (...)": The value must be greater than or equal to the
smallest value in the list to evaluate to TRUE.

• "x <= ANY (...)": The value must be smaller than or equal to the
biggest value in the list to evaluate to TRUE. 35
Query

• Consider example which displays employees


who are not clerk and whose salary is less than
that of any other clerk.
• The maximum salary that a clerk earn is
25000.

36
Using the ANY Operator in multiple-row subqueries

SELECT Employee_id,Emp_name,Job_id,Salary,
FROM employee
WHERE salary < ANY
20000,25000

SELECT salary
FROM employee
WHERE job_id=ST_Clerk”)

AND job_id< > ‘ST_Clerk’;

37
Employee_id EMP_Name Job_id Salary
104 LMN Assistant 15000
106 JKL Assistant 10000
107 UVW Adviser 22000

38
• "x = ALL (...)": The value must match all the values in the list to
evaluate to TRUE.

• "x != ALL (...)": The value must not match any values in the list to
evaluate to TRUE.

• "x > ALL (...)": The value must be greater than the biggest value in
the list to evaluate to TRUE.

• "x < ALL (...)": The value must be smaller than the smallest value in
the list to evaluate to TRUE.

• "x >= ALL (...)": The value must be greater than or equal to the
biggest value in the list to evaluate to TRUE.

• "x <= ALL (...)": The value must be smaller than or equal to the
smallest value in the list to evaluate to TRUE. 39
Query

• Consider example which displays employees


whose salary is less than the salary of all
employees with a job_id of ST_clerk and
whose job is not ST_Clerk.

40
Using the ALL Operator in multiple-row subqueries

SELECT Employee_id,Emp_name,Job_id,Salary,
FROM employee 20000,25000
WHERE salary < ALL

SELECT salary
FROM employee
WHERE job_id=‘ST_Clerk’)
AND job_id<> ‘ST_Clerk’;

41
Employee_id EMP_Name Job_id Salary
104 LMN Assistant 15000
106 JKL Assistant 10000

42
Cartesian Product
• If a sql join condition is omitted or if it is invalid the join
operation will result in a Cartesian product.

• The Cartesian product returns a number of rows equal to


the product of all rows in all the tables being joined.

• To avoid a cartesian product, always include a valid join


condition in the WHERE clause

• For example, if the first table has 20 rows and the second
table has 10 rows, the result will be 20 * 10, or 200 rows.
This query takes a long time to execute.
43
Example
employee table department table
Emp_id Last_nm Dept_id
Dept_id Dept_nm Loc_id
100 Abc 90
90 sales 1700
200 Def 90
90 sales 1500
300 Ghi 20
20 accounting 1200
400 Jkl 50
50 contracting 1400
500 mno 60
60 admin 1100
70 IT 1200

Cartesian Product :5*6=30


SELECT last_nm,dept_nm i.e 30 rows are selected.
FROM employee,department;

44
Types of Joins

• Equijoin
• Non-equijoin
• Outer join
• Self join

 SQL Joins are used to relate information in different


tables. A Join condition is a part of the sql query that
retrieves rows from two or more tables.

 A SQL Join condition is used in the SQL WHERE


clause of select, update, delete statements.
45
SQL-JOIN
• The JOIN keyword is used in an SQL statement to
query data from two or more tables, based on a
relationship between certain columns in these tables.

• Tables in a database are often related to each other


with keys.

• A primary key is a column (or a combination of


columns) with a unique value for each row. Each
primary key value must be unique within the table.
The purpose is to bind data together, across tables,
without repeating all of the data in every table.
46
• The Syntax for joining two tables is:
SELECT table1.coumn,table2.column
FROM table1, table2
WHERE table1.column1=table2.column2
Where,
table1.column1=table2.column2; is the condition that
joins or relates the tables together.
 Different SQL JOINs
• JOIN/inner join: Return rows when there is at least one match in
both tables.
• LEFT JOIN: Return all rows from the left table, even if there are
no matches in the right table.
• RIGHT JOIN: Return all rows from the right table, even if there
are no matches in the left table.
• FULL JOIN: Return rows when there is a match in one of the
47
tables.
• SQL INNER JOIN Keyword
The INNER JOIN keyword return rows when there
is at least one match in both tables.

• SQL INNER JOIN Syntax


SELECT column_name(s)
FROM table_name1
INNER JOIN table_name2
ON
table_name1.column_name=table_name2.column_name

48
SQL INNER JOIN Example
The "Persons" table:
P_Id LastName FirstName Address City
1 ABC A ST1 pune
2 PQR B ST2 pune
3 XYZ C ST3 mumbai

The "Orders" table:


O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15

Now we want to list all the persons with any orders.


We use the SELECT statement: 49
• SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
INNER JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
• The result-set will look like this:

LastName FirstName OrderNo


ABC A 22456
ABC A 24562
XYZ C 77895
XYZ C 44678

The INNER JOIN keyword return rows when there is at least


one match in both tables. If there are rows in "Persons" that do
not have matches in "Orders", those rows will NOT be listed.

50
• SQL LEFT JOIN Keyword
The LEFT JOIN keyword returns all rows from the left
table (table_name1), even if there are no matches in the
right table (table_name2).

• SQL LEFT JOIN Syntax


SELECT column_name(s)
FROM table_name1
LEFT JOIN table_name2
ON table_name1.column_name=table_name2.column_name

In some databases LEFT JOIN is called LEFT OUTER JOIN.


51
SQL LEFT JOIN Example
The "Persons" table:

P_Id LastName FirstName Address City


1 ABC A ST1 pune
2 PQR B ST2 pune
3 XYZ C ST3 mumbai

The "Orders" table:

O_Id OrderNo P_Id


1 77895 3
2 44678 3
3 22456 1
4 24562 1
52
• Now if we want to list all the persons and their
orders - if any, from the tables above.

• We use the following SELECT statement:


SELECT Persons.LastName,
Persons.FirstName, Orders.OrderNo
FROM Persons
LEFT JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName

53
• The result-set will look like this:
LastName FirstName OrderNo
ABC A 22456
ABC A 24562
XYZ C 77895
XYZ C 44678
PQR B

The LEFT JOIN keyword returns all the rows from the left
table (Persons), even if there are no matches in the right table
(Orders).

54
• SQL RIGHT JOIN Keyword
The RIGHT JOIN keyword returns all the rows
from the right table (table_name2), even if there are no
matches in the left table (table_name1).

• SQL RIGHT JOIN Syntax


SELECT column_name(s)
FROM table_name1
RIGHT JOIN table_name2
ON table_name1.column_name=table_name2.column_name

• In some databases RIGHT JOIN is called RIGHT


OUTER JOIN.
55
SQL RIGHT JOIN Example
The "Persons" table:

P_Id LastName FirstName Address City


1 ABC A ST1 pune
2 PQR B ST2 pune
3 XYZ C ST3 mumbai

The "Orders" table:

O_Id OrderNo P_Id


1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
56
• Now if we want to list all the orders with
containing persons - if any, from the tables
above.
• We use the following SELECT statement:
SELECT Persons.LastName, Persons.FirstName,
Orders.OrderNo
FROM Persons
RIGHT JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName

57
The result-set will look like this:
LastName FirstName OrderNo
ABC A 22456
ABC A 24562
XYZ C 77895
XYZ C 44678
34764

The RIGHT JOIN keyword returns all the rows from


the right table (Orders), even if there are no matches in
the left table (Persons).

58
• SQL FULL JOIN Keyword

The FULL JOIN keyword return rows when there is a


match in one of the tables.

• SQL FULL JOIN Syntax

SELECT column_name(s)
FROM table_name1
FULL JOIN table_name2
ON table_name1.column_name=table_name2.column_name

59
• SQL FULL JOIN Example
The "Persons" table:

P_Id LastName FirstName Address City


1 ABC A ST1 pune
2 PQR B ST2 pune
3 XYZ C ST3 mumbai

The "Orders" table:


O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
60
• Now if we want to list all the persons and their
orders, and all the orders with their persons.

• We use the following SELECT statement:


SELECT Persons.LastName, Persons.FirstName,
Orders.OrderNo
FROM Persons
FULL JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName

61
LastName FirstName OrderNo
ABC A 22456
ABC A 24562
XYZ C 77895
XYZ C 44678
PQR B
34764

The FULL JOIN keyword returns all the rows from the
left table (Persons), and all the rows from the right
table (Orders). If there are rows in "Persons" that do
not have matches in "Orders", or if there are rows in
"Orders" that do not have matches in "Persons", those
rows will be listed as well. 62
• SQL Joins can be classified into Equi join and
Non Equi join.

1) SQL Equi joins


It is a simple sql join condition which uses the equal
sign as the comparison operator. Two types of
equi joins are SQL Outer join and SQL Inner join.

2) SQL Non equi joins


It is a sql join condition which makes use of some
comparison operator other than the equal sign like
>, <, >=, <=
63
1) SQL Equi Joins:
An equi-join is further classified into two categories:
a) SQL Inner Join b) SQL Outer Join

a) SQL Inner Join:


All the rows returned by the sql query satisfy the sql join
condition specified.

• The columns must be referenced by the table name in the


join condition, because P_id is a column in both the
tables and needs a way to be identified. This avoids
ambiguity in using the columns in the SQL SELECT
statement.
64
• database table "product";
product_id product_name supplier_name unit_price
100 Camera Nikon 300
101 Television Onida 100
102 Refrigerator Vediocon 150
103 Ipod Apple 75
104 Mobile Nokia 50

database table "order_items"

order_id product_id total_units customer


5100 104 30 Infosys
5101 102 5 Satyam
5102 103 25 Wipro
5103 101 10 TCS

65
SQL Outer Join

• This sql join condition returns all rows from both


tables which satisfy the join condition along with
rows which do not satisfy the join condition from
one of the tables. The sql outer join operator in
Oracle is ( + ) and is used on one side of the join
condition only.

• The syntax differs for different RDBMS


implementation. Few of them represent the join
conditions as "sql left outer join", "sql right outer
join".
66
• If you want to display all the product data
along with order items data, with null values
displayed for order items if a product has no
order item, the sql query for outer join would
be as shown below:

• SELECT p.product_id, p.product_name,


o.order_id, o.total_units
FROM order_items o, product p
WHERE o.product_id (+) = p.product_id;
67
• The output would be like,

product_id product_name order_id total_units


100 Camera
101 Television 5103 10
102 Refrigerator 5101 5
103 Ipod 5102 25
104 Mobile 5100 30

If the (+) operator is used in the left side of the join condition it
is equivalent to left outer join. If used on the right side of the
join condition it is equivalent to right outer join.

68
• 1) SQL Self Join:
A Self Join is a type of sql join which is
used to join a table to itself, particularly when the
table has a FOREIGN KEY that references its
own PRIMARY KEY. It is necessary to ensure
that the join statement defines an alias for both
copies of the table to avoid column ambiguity.
To join a table to itself, we can use Self-
join.

69
Employees-worker
Employee_Id Last_Name Manager_id
100 ABC
101 PQR 100
102 XYZ 100
103 LMN 102
104 UVW 103

Employee_Id Last_Name
Employees-manager
100 ABC
101 PQR
102 XYZ
103 LMN
104 UVW
70
Manager_id in the worker table is equal to Employee_id in
the Manager table.
 To find the name of each employee’s manager, you need
to join the employees table to itself , or perform a self
join.
The below query is an example of a self join,

SELECT worker.Last_name || ‘works for’ || manager.Last_name


FROM employees worker, employees manager
WHERE worker.Manager_id=manager.employee_id;

71
Output

worker.Last_name || ‘works for’ || manager.Last_name


PQR works for ABC
XYZ works for ABC
LMN works for XYZ
………………..
……………

72
2) SQL Non Equi Join:
• A Non Equi Join is a SQL Join whose condition
is established using all comparison operators
except the equal (=) operator. Like >=, <=, <, >
• A non-equijoin is a join condition containing
something other than an equality operator.
• For example:
If you want to find the names of students who are
not studying either History, the sql query would be
like,
• SELECT first_name, last_name, subject
FROM student_details
WHERE subject != ‘History' 73
Example: student_details;

id first_name last_name age subject games


100 abc gg 20 Science Cricket
101 xyz pp 22 Maths Football
102 pqr zz 29 Science Cricket
103 lmn aa 28 Maths Badminton
104 def bb 25 History Chess

74
• The output would be something like,
first_name last_name subject
lmn aa Maths
xyz pp Maths
pqr zz Science
abc gg Science

75
SQL Functions
Functions are a very powerful feature of SQL and can be
used to do the following:

•Perform calculations on data


•Manipulate output for groups of rows
•Format dates and numbers for display
•Convert column data types.

76
• Two types of functions in Oracle.

1) Single Row Functions: Single row or Scalar


functions return a value for every row that is processed
in a query.

2) Group Functions: These functions group the rows of


data based on the values returned by the query. The
group functions are used to calculate aggregate values
like total or average, which return just one total or one
average value after processing a group of rows.

77
Single row functions
• These are used to manipulate data items. They accept
one or more arguments and return one value for each
row returned by the query. An argument can be one of
the following :
• User –supplied constant
• Variable value
• Column name
• Expression
These functions operate on single rows only and return
one result per row.

78
• Four types of single row functions are:,

1) Numeric Functions: These are functions that accept


numeric input and return numeric values.

2) Character or Text Functions: These are functions that


accept character input and can return both character and
number values.

3) Date Functions: These are functions that take values that


are of datatype DATE as input and return values of datatype
DATE, except for the MONTHS_BETWEEN function,
which returns a number.

79
4) Conversion Functions: These are functions
that help us to convert a value in one form to
another form. For Example: a null value into
an actual value, or a value from one datatype
to another datatype like NVL, TO_CHAR,
TO_NUMBER, TO_DATE etc.

• You can combine more than one function


together in an expression. This is known as
nesting of functions.

80
• 1) Numeric Functions:
Numeric functions are used to perform operations on
numbers. They accept numeric values as input and return
numeric values as output. Few of the Numeric functions are:

Function Name Return Value


ABS (x) Absolute value of the number 'x'
Integer value that is Greater than or equal to the
CEIL (x)
number 'x'
Integer value that is Less than or equal to the number
FLOOR (x)
'x'
TRUNC (x, y) Truncates value of number 'x' up to 'y' decimal places
Rounded off value of the number 'x' up to the number
ROUND (x, y)
'y' decimal places

81
Function Name Examples Return Value
ABS (1) 1
ABS (x)
ABS (-1) -1
CEIL (2.83) 3
CEIL (x) CEIL (2.49) 3

FLOOR (2.83) 2
FLOOR (x) FLOOR (2.49) 2

trunc(125.815, 1)
125.8
trunc(125.815, 2)
125.81
TRUNC (x, y) trunc(125.815, 3)
125.815
trunc(-125.815, 2)
-125.81

round(125.315, 0) 125
round(125.315, 1) 125.3
round(125.315, 2) 125.32
ROUND (x, y)
round(125.315, 3) 125.315
round(-125.315, 2) -125.32
82
2) Character or Text Functions:
Character or text functions are used to manipulate text strings. They accept strings
or characters as input and can return both character and number values as output.

Function Name Return Value


All the letters in 'string_value'
LOWER (string_value)
is converted to lowercase.

All the letters in 'string_value'


UPPER (string_value)
is converted to uppercase.

83
Function Name Return Value

All the letters in 'string_value' is


INITCAP (string_value)
converted to mixed case.

All occurrences of 'trim_text' is


LTRIM (string_value, trim_text) removed from the left of
'string_value'.

All occurrences of 'trim_text' is


RTRIM (string_value, trim_text) removed from the right of
'string_value' .

84
Continue…….

All occurrences of 'trim_text'


from the left and right of
TRIM (trim_text FROM
'string_value' , 'trim_text' can
string_value)
also be only one character
long .

Returns 'n' number of characters


SUBSTR (string_value, m, n) from 'string_value' starting from
the 'm' position.

Number of characters in
LENGTH (string_value)
'string_value' is returned.
85
Returns 'string_value' left-
LPAD (string_value, n, padded with 'pad_value' . The
pad_value) length of the whole string will be
of 'n' characters.

Returns 'string_value' right-


RPAD (string_value, n, padded with 'pad_value' . The
pad_value) length of the whole string will be
of 'n' characters.

86
Function Name Examples
LOWER(string_value) LOWER('Good Morning')
UPPER(string_value) UPPER('Good Morning')
INITCAP(string_value) INITCAP('GOOD MORNING')
LTRIM(string_value, trim_text) LTRIM ('Good Morning', 'Good)

RTRIM ('Good Morning', '


RTRIM (string_value, trim_text)
Morning')

TRIM (trim_text FROM


TRIM ('o' FROM 'Good Morning')
string_value)

SUBSTR (string_value, m, n) SUBSTR ('Good Morning', 6, 7)


LENGTH (string_value) LENGTH ('Good Morning')
LPAD (string_value, n, pad_value) LPAD ('Good', 6, '*')
RPAD (string_value, n, pad_value) RPAD ('Good', 6, '*')
87
3) Date Functions:

• These are functions that take values that are of datatype DATE as input
and return values of datatype as DATE, except for the
MONTHS_BETWEEN function, which returns a number as output.
• Few date functions are as given below.

Function Name Return Value


Returns a date value after adding 'n'
ADD_MONTHS (date, n)
months to the date 'x'.
Returns the number of months between
MONTHS_BETWEEN (x1, x2)
dates x1 and x2.
Returns the date 'x' rounded off to the
nearest century, year, month, date, hour,
ROUND (x, date_format)
minute, or second as specified by the
'date_format'.

88
Continue…

Returns the date 'x' lesser than or


equal to the nearest century, year,
TRUNC (x, date_format)
month, date, hour, minute, or second as
specified by the 'date_format'.
Returns the next date of the 'week_day'
NEXT_DAY (x, week_day)
on or after the date 'x' occurs.
It is used to determine the number of days
LAST_DAY (x) remaining in a month from the date 'x'
specified.
Returns the systems current date and
SYSDATE
time.
NEW_TIME (x, zone1, Returns the date and time in zone2 if date
zone2) 'x' represents the time in zone1.

89
Examples of date functions

Function Name Examples Return Value


ADD_MONTHS ( ) ADD_MONTHS ('16-Sep-81', 3) 16-Dec-81
MONTHS_BETWEEN ('16-Sep-81',
MONTHS_BETWEEN( ) 3
'16-Dec-81')
NEXT_DAY ('01-Jun-08',
NEXT_DAY( ) 04-JUN-08
'Wednesday')
LAST_DAY( ) LAST_DAY ('01-Jun-08') 30-Jun-08
NEW_TIME ('01-Jun-08', 'IST',
NEW_TIME( ) 31-May-08
'EST')

90
4) Conversion Functions
• These are functions that help us to convert a
value in one form to another form.

• For Ex: a null value into an actual value, or a


value from one data type to another data type
like NVL, TO_CHAR, TO_NUMBER,
TO_DATE.

91
• Few of the conversion functions available in oracle are:

Function Name Return Value


Converts Numeric and Date values to a
character string value. It cannot be
TO_CHAR (x [,y])
used for calculations since it is a string
value.
Converts a valid Numeric and
Character values to a Date value. Date
TO_DATE (x [, date_format])
is formatted to the format specified by
'date_format'.
If 'x' is NULL, replace it with 'y'. 'x'
NVL (x, y)
and 'y' must be of the same datatype.

92
The below table provides the examples for the above functions

Function Name Examples Return Value

TO_CHAR (3000,
'$9999') $3000
TO_CHAR ()
TO_CHAR (SYSDATE, Monday, Aug 2012
'Day, Month YYYY')

TO_DATE () TO_DATE ('01-Aug-12') 01-Aug-2012

NVL () NVL (null, 1) 1

93
END

94

You might also like