sql_functions
sql_functions
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
1
CHECK Specifies a condition that must be true
Constraint guidelines
• All constraints are stored in data dictionary.
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.
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
6
Example
7
Unique Key at table level:
8
SQL Primary key
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
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,
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.
• 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.
21
Example: student_details;
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:
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');
24
first_name
id
100 abc
102 pqr
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
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
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:
32
Example
33
SQL WHERE, ANY, ALL Clause
• ANY and ALL keywords are used with a
WHERE or HAVING clause.
• "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
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”)
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
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.
• 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
44
Types of Joins
• Equijoin
• Non-equijoin
• Outer join
• Self join
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
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).
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).
57
The result-set will look like this:
LastName FirstName OrderNo
ABC A 22456
ABC A 24562
XYZ C 77895
XYZ C 44678
34764
58
• SQL FULL JOIN Keyword
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:
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.
65
SQL Outer Join
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,
71
Output
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;
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:
76
• Two types of functions in Oracle.
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:,
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.
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:
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.
83
Function Name Return Value
84
Continue…….
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.
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)
• 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.
88
Continue…
89
Examples of date functions
90
4) Conversion Functions
• These are functions that help us to convert a
value in one form to another form.
91
• Few of the conversion functions available in oracle are:
92
The below table provides the examples for the above functions
TO_CHAR (3000,
'$9999') $3000
TO_CHAR ()
TO_CHAR (SYSDATE, Monday, Aug 2012
'Day, Month YYYY')
93
END
94