Unit3 Notes (1)
Unit3 Notes (1)
Tuning
S.V.BAHALE 2
Concept Explanation-String Functions
S.V.BAHALE 3
Arithmetic Functions:
• SQL Arithmetic functions are used for numeric manipulation and Mathematical calculations.
• CEIL()/CEILING(): It returns the smallest integer value that is greater than or equal to a number.
Syntax: SELECT CEIL(25.75) from dual;
Output: 26
• FLOOR(): It returns the largest integer value that is less than or equal to a number.
Syntax: SELECT FLOOR(25.75) from dual;
Output: 25
S.V.BAHALE 4
Arithmetic Functions:
• LEAST(): It returns the smallest value in a list of expressions.
Syntax: SELECT LEAST(30, 2, 36, 81, 125) from dual;
Output: 2
S.V.BAHALE 5
Arithmetic Functions:
• SIGN(): It returns a value indicating the sign of a number.
Syntax: SELECT SIGN(255.5) from dual;
Output: 1
S.V.BAHALE 6
Concept Explanation-Date and Time Functions
• ADD_MONTHS
Select ADD_MONTHS('2016-02-29', 1 ) from dual;
31-MAR-16
Add a number of months (n) to a date and return the same day which is n of months away.
• CURRENT_DATE
SELECT CURRENT_DATE FROM dual
;16-AUG-2019 19:43:44
Return the current date and time in the session time zone
• LAST_DAY
Select LAST_DAY('2016-02-01') from dual;
29-FEB-16
Gets the last day of the month of a specified date.
• MONTHS_BETWEEN
Select MONTHS_BETWEEN('2017-07-01', '2017-01-01' ) from dual;
6
Return the number of months between two dates.
S.V.BAHALE 7
Concept Explanation-Date/Time Functions
• NEXT_DAY
SELECT NEXT_DAY('2000-01-01', 'SUNDAY' ) FROM DUAL ;
02-JAN-00
Get the first weekday that is later than a specified date.
• ROUND
SELECT ROUND('2019-07-16', 'MM') FROM DUAL ;
01-AUG-19
Return a date rounded to a specific unit of measure.
• SYSDATE
SELECT SYSDATE FROM DUAL ;
01-AUG-19
Return the current system date and time of the operating system where the Oracle Database resides.
• TRUNC
SELECT TRUNC('2019-07-16', 'MM') FROM DUAL ;
01-JUL-19
Return a date truncated to a specific unit of measure.
S.V.BAHALE 8
Concept Explanation-Date/Time Functions
• TO_CHAR
SELECT TO_CHAR('2017-01-01', 'DL' ) FROM DUAL ;
Sunday, January 01, 2017
Convert a DATE or an INTERVAL value to a character string in a specified format.
• TO_DATE
SELECT TO_DATE( '01 Jan 2017', 'DD MON YYYY' ) FROM DUAL ;
01-JAN-17
Convert a date which is in the character string to a DATE value.
• TO_NUMBER
SELECT TO_NUMBER( '01 Jan 2017‘) FROM DUAL ;
S.V.BAHALE 9
Concept Explanation-Date/Time Functions
• DATE()
Extract the date part of a date or date time expression
• DATE_ADD()
Add time values (intervals) to a date value
• DATE_FORMAT()
Format date as specified
• DATE_SUB()
Subtract a time value (interval) from a date
• DATEDIFF()
Subtract two dates
• DAY()
Synonym for DAYOFMONTH()
S.V.BAHALE 10
Concept Explanation-Date/Time Functions
Name Description
S.V.BAHALE 12
Concept Explanation-Date/Time Functions
Name Description
TIMESTAMP() With a single argument, this function returns the date or datetime expression; with two
arguments, the sum of the arguments
S.V.BAHALE 13
Concept Explanation-Aggregate Functions
• SUM( [ALL | DISTINCT] expression )
SELECT SUM(Salary) total_sal FROM employees;
• COUNT(* )
SELECT COUNT(* ) FROM employees;
S.V.BAHALE 14
Concept Explanation-Group By Clause
The group by clause can be used to divide the rows in a table into groups. The group functions can also be
used to return summary information for each group.
The group condition restricts the group of rows returned to those groups for which the specified condition
is True.
Guidelines :
1. A column or expression in the select clause that is not an aggregate function must be there in group by clause.
2. Column alias cannot be used in group by clause.
3. GROUP BY clause can only be used with aggregate functions like SUM, AVG, COUNT, MAX, and MIN.
4. Aggregate functions cannot be used in a GROUP BY clause.
Syntax:
S.V.BAHALE 15
Concept Explanation-Group By Clause
Similarly, below query to find sum of salaries for respective job ids in each department. Note the
group is established based on Department and Job id. So they appear in GROUP BY clause.
SELECT DEPARTMENT_ID, JOB_ID, SUM (SAL)
FROM employees
GROUP BY DEPARTMENT_ID, JOB_ID;
The below query also produces the same result. Please note that grouping is based on the
department id and job id columns but not used for display purpose.
SELECT SUM (SALARY)
FROM employees
GROUP BY DEPARTMENT_ID, JOB_ID;
S.V.BAHALE 16
Concept Explanation-Order by clause
Guidelines :
Syntax:
select <expression>
from <table_name>
[where condition]
[order by [column|expression][asc|desc]]
S.V.BAHALE 17
Concept Explanation-Having Clause
Having clause is used to specify which groups are to be displayed. HAVING clause filters rows AFTER the
GROUPING action.
Guidelines :
1. Having clause is used to restrict groups instead of where clause.
2. Having clause can precede the group by clause.
Syntax:
select column, group_function
from <table_name>
[where condition]
[group by group_expression]
[Having group_condition]
[order by column]
The group condition restricts the group of rows returned to those groups for which the specified condition
is True.
SELECT JOB_ID, SUM (SALARY)
FROM employees
GROUP BY JOB_ID
HAVING SUM (SALARY) > 10000;
S.V.BAHALE 18
Concept Explanation-Join
Join :
• Join operations take two relations and return another relation as the result.
• Join is used to combine the data spread across the tables.
Guidelines :
1. Rows in one table can be joined to rows in another table according to the common value existing in corresponding
columns , usually primary key or foreign key columns.
2. Precede the column name with table names(e.g Table1.column1) in select statement if same column name appears in
more than one table.
Types of Join:
• Natural join (also known as an equijoin or a simple join) :
A join based on equality is called equi-join. A comparison operator equal to (=) is used to perform a join. Creates a join
by using a commonly named and defined column.
• Non-equality join :
Joins tables when there are no equivalent rows in the tables to be joined-for example, to match values in one column
of a table with a range of values in another table. Non-equality join uses relational operators (<,>,<=,>=, !=) to specify
relationship between columns belonging to different tables.
• Self-join:
Joins a table to itself i.e it joins one row of a table to another. It compares each row of a table with itself and also with
other rows of the same table.
• Outer join : Returns all records of a table when there is a match in either left or right table.
• Cartesian join (also known as a Cartesian product or cross join) :
Replicates each row from the first table with every row from the second table. Creates a join between tables by
displaying every possible record combination.
S.V.BAHALE 19
Concept Explanation-Natural Join (equijoin )
• Equi-Join :
• A join which is based on equality is called equi-join. In equi-join comparison operator (=) is used to perform a
join. It retrieves rows from tables having common column , and the columns are join compatible.
• Consider the DEPARTMENTS and EMPLOYEES tables. Each table has a column named deptno.
select * from emp, dept where emp.deptno=dept.deptno;
SELECT E.first_name FIRST_NAME, D.department_name DNAME
FROM employees E NATURAL JOIN departments D;
FIRST_NAME DNAME
MILLER DEPT 1
JOHN DEPT 1
MARTIN DEPT 2
EDWIN DEPT 2
• The below SELECT query joins the two tables by explicitly specifying the join condition with the ON keyword.
S.V.BAHALE 20
Concept Explanation-Self Join and Non Equi-Join
Self Join :
• When a table is joined to itself, the join is known as Self Join.
Consider EMPLOYEES table, which contains employee and their reporting managers.
To find manager's name for an employee would require a join on the EMP table itself.
Non Equi-Join :
A join that specifies the relationship between columns belonging to different tables by making use of relational
operators other than equal to, BETWEEN, IS NULL, IS NOT NULL.
Average 50 60 1 Anil 70
Good 61 75 2 Jaya 75
4 Amol 80
Query: Display category of students from student table depending upon their percentage.
select s.stud_name, s.percentage, p. Category
from student s, percentage p
where s.percentage between p.Low_Per and p.High_Per ;
S.V.BAHALE 21
Concept Explanation-Outer Joins
There are three types of outer joins: the LEFT, RIGHT, and FULL OUTER JOIN.
Right Outer Join
A RIGHT OUTER JOIN returns all the records from the right table, and the matched records from the left table.
The result is NULL from left side when there is no match.
JOHN 6000 10
EDWIN 2000 20
MILLER 2500 10
MARTIN 4000 20
30
Left Outer Join
A LEFT OUTER JOIN returns all the records from the left table, and the matched records from the right table.
The result is NULL from the right side when there is no match.
S.V.BAHALE 22
Concept Explanation-Outer Joins
Full Outer Join
The FULL OUTER JOIN returns all the records when there is a match in either left or right table records.
S.V.BAHALE 23
Concept Explanation- Subquery
• A Subquery or Inner query or a Nested query is a query within another SQL query and embedded within the WHERE
clause.
Types of Subqueries:
Single row subqueries
Multiple rows subqueries
Multiple columns subqueries
Guidelines:
Subquery must appear on right side of operator and must be enclosed in parenthesis.
Main select statement is called as outer query block.
Subquery is called as inner query block.
The inner query block executed first.
Then outer query block is processed and it uses the values returned by inner query block to complete its
search condition.
Subqueries can be used in where clause and having clause.
An ORDER BY command cannot be used in a subquery, although the main query can use an ORDER BY
clause.
You can use the comparison operators, such as >, <, or =. The comparison operator can also be a multiple-row
operator, such as IN, ANY, or ALL.
S.V.BAHALE 24
Concept Explanation- Subquery
Multiple rows subqueries :
Subqueries that returns more than one row are called Multiple rows subqueries .
Syntax:
Select column1, column2,……, column n
From table_name
Where column1 IN ( select group_function from table_name group by column) ;
S.V.BAHALE 25
Concept Explanation- Subquery
Examples :
Student Table Marks table
Query result:
Second query: query identifies the students who get better marks than the result of the first query.
SELECT a. StudentID a.name, b.total_marks
FROM student a, marks b
WHERE a. StudentID = b. StudentID AND b.total_marks >80;
Query result:
S.V.BAHALE 26
Concept Explanation- Subquery
Subquery Example:
SELECT a.studentid, a.name, b.total_marks
FROM student a, marks b
WHERE a.studentid = b.studentid AND b.total_marks >
(SELECT total_marks
FROM marks
WHERE studentid = 'V002');
Query result:
S.V.BAHALE 27
Concept Explanation- Subquery
Multiple row subqueries :
• Use of ANY:
Select *
From stud_info
Where ssc_per > ANY
(select min(ssc_per)
from stud_info
group by branch_code);
• Use of ALL:
Select *
From stud_info
Where ssc_per > ALL
(select min(ssc_per)
from stud_info
group by branch_code);
S.V.BAHALE 28
Concept Explanation- View
S.V.BAHALE 29
Concept Explanation- View
Syntax :
CREATE [OR REPLACE][Force/NoForce] VIEW view_name [alias name]AS
SELECT column1, column2, ...
FROM table_name
WHERE condition
[with CHECK OPTION[constraint]]
[with READONLY];
Replace:- Recreates a view if it is already exists.
Force:- Creates a view regardless of whether or not the base table exists.
NoForce:- Creates a view only if base table exists.
With Check Option:- Specifies that only rows accessible to the view can be inserted or updated.
Constraint:- is the name assigned to CHECK OPTION constraint
With READONLY :- Ensures that no DML operations can be performed on this view.
S.V.BAHALE 30
Concept Explanation- View
Output:
SELECT * FROM CUSTOMERS_VIEW;
This would produce the following result.
+ + +
| name | age |
+ + +
| Ramesh | 32 |
| Khilan | 25 |
| kaushik | 23 |
| Chaitali | 25 |
| Hardik | 27 |
| Komal | 22 |
| Muffy | 24 |
+ + +
S.V.BAHALE 31
Concept Explanation- View
The WITH CHECK OPTION :
The WITH CHECK OPTION in this case should deny the entry of any NULL values in the view's AGE column,
because the view is defined by data that does not have a NULL value in the AGE column.
Dropping a View
A view is deleted with the DROP VIEW command.
Syntax
DROP VIEW view_name;
Example
DROP VIEW CUSTOMERS_VIEW;
S.V.BAHALE 32
Concept Explanation- View
Updating a View :
A view can be updated under certain conditions which are given below −
• The SELECT clause may not contain the keyword DISTINCT.
• The SELECT clause may not contain summary functions.
• The SELECT clause may not contain set functions.
• The SELECT clause may not contain set operators.
• The SELECT clause may not contain an ORDER BY clause.
• The FROM clause may not contain multiple tables.
• The WHERE clause may not contain subqueries.
• The query may not contain GROUP BY or HAVING.
• Calculated columns may not be updated.
• All NOT NULL columns from the base table must be included in the view in order for the INSERT query to function.
So, if a view satisfies all the above-mentioned rules then you can update that view
Example :
UPDATE CUSTOMERS_VIEW
SET AGE = 35 WHERE name = 'Ramesh';
This would ultimately update the base table CUSTOMERS and the same would reflect in the view itself.
The SELECT statement would produce the following result.
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
S.V.BAHALE 33
Concept Explanation- View
Inserting Rows into a View :
Rows of data can be inserted into a view.
This would ultimately delete a row from the base table CUSTOMERS and the same would reflect in the view
itself.
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
S.V.BAHALE 34
Concept Explanation- Sequence
• A sequence is a database object , which can generate unique, sequential integer values.
• It can be used to automatically generate primary key or unique key values.
• A sequence can either be an ascending or descending order.
• After creating a sequence its values are accessed with the help of pseudo column currval and nextval.
• currval : Returns the current value of the sequence
• nextval :Returns initial values of sequence when referred first time later on increment value by using
increment by clause.
• Syntax:
Create sequence <sequence name>
[increment by n]
[start with n]
[{maxvalue n | nomax value}]
[{minvalue n | nomin value}]
[{cycle | nocycle}]
[{cache n | nocache}];
• INCREMENT BY Specify the interval between sequence numbers. This integer value can be any positive or
negative integer, but it cannot be 0.
S.V.BAHALE 35
Concept Explanation- Sequence
START WITH Specify the first sequence number to be generated.
NOMAXVALUE Specify NOMAXVALUE to indicate a maximum value of 1027 for an ascending sequence or -1 for a
descending sequence.
NOMINVALUE Specify NOMINVALUE to indicate a minimum value of 1 for an ascending sequence or -1026 for a
descending sequence.
CYCLE Specify CYCLE to indicate that the sequence continues to generate values after reaching either its
maximum or minimum value.
NOCYCLE Specify NOCYCLE to indicate that the sequence cannot generate more values after reaching its
maximum or minimum value.
CACHE Specify how many values of the sequence the database preallocates and keeps in memory for faster
access.
NOCACHE Specify NOCACHE to indicate that values of the sequence are not preallocated. If you omit
both CACHE and NOCACHE, then the database caches 20 sequence numbers by default.
ORDER Specify ORDER to guarantee that sequence numbers are generated in order of request.
NOORDER Specify NOORDER if you do not want to guarantee sequence numbers are generated in order of
request.
NOORDER Specify NOORDER if you do not want to guarantee sequence numbers are generated in order of
request.
S.V.BAHALE 36
Concept Explanation- Sequence
Example 1:
CREATE SEQUENCE customers_seq
START WITH 1000
INCREMENT BY 1
NOCACHE
NOCYCLE;
The first reference to customers_seq.nextval returns 1000. The second returns 1001. Each subsequent
reference will return a value 1 greater than the previous reference.
Example 2:
Create sequence dept_deptno
increment by 10
start with 10
maxvalue 100
nocache
nocycle ;
S.V.BAHALE 37
Concept Explanation- Sequence
Modifying a sequence :
• To set or eliminate minimum or maximum value
• To change the increment value.
• To change the number of cached sequence numbers.
• Start with option can not be changed using alter sequence.
Syntax :
Example :
alter sequence dept_deptno maxvalue 120;
Deleting a sequence :
S.V.BAHALE 38
Concept Explanation- Index
• An Index is a schema object that can speed up the retrieval of rows by using pointers.
• An Index provides direct and fast access to rows in a table. It is mostly useful on large tables and on columns
that appear frequently in where clause.
• We can create multiple indexes on one table.
• When a table is dropped index will also drop.
• Index can be automatically created when Primary or Unique key constraint is defined in a table.
• Manually it can be created using create index command.
Types of Index :
Simple Index :
• Simple Index is a Index on a single column.
Composite Index :
• An Index created on more than one column of a table.
• Oder of columns is important and should be arranged in descending order as per their
importance.
Unique Index :
• Allows to enforce uniqueness of values in one or more column. You can create more than one
unique index per table.
S.V.BAHALE 39
Concept Explanation- Index
Creating indexes :
1. When a column is frequently used in where clause or in a join condition.
2. The column contains a large wide range of values.
3. The column contains a large number of null values.
Syntax :
create index <index name>
ON table (column *, column+…);
Example 1:
create index emp_ename_idx
ON emp(ename);
Example 2:
create index sid
ON emp(empno, ename);
Example 3:
create unique index uid
ON emp(empno);
Viewing Table Indexes :
show indexes from emp;
Removing an index :
Syntax : drop index <index _name> ;
Example : drop index emp_ename_idx ;
S.V.BAHALE 40
Concept Explanation- Synonym
• Synonym is a database object, which is used as an alias for a table, view or sequence.
• Synonym can be either private or public .
• A normal user can create a private synonym and public synonym is created by a database Administrator(DBA).
• User can perform all DML manipulations such as insert, delete, update on synonym.
• User can not perform any DDL operations on synonyms except drop operation.
• All the manipulations affect the table.
Uses :
• Simplify SQL statements.
• Hide the name and owner of an object.
• Provide public access to an object.
Syntax :
create [or replace ][private | public]
Synonym <synonym_name>
for <object_name>;
OR REPLACE : Allows to create a synonym if it is already exists.
Public : Creates a synonym accessible to all users.
Object name : The name of object for which you are creating the synonym.
S.V.BAHALE 41
Concept Explanation- Synonym
Example :
1) Create synonym employee for emp;
2) Create public synonym sy1 for emp;
Using synonym :
Select * from sy1;
Removing a synonym :
Syntax : drop synonym < synonym _name> ;
Example : drop synonym employee;
S.V.BAHALE 42