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

Unit3 Notes (1)

Uploaded by

vahaneaniket
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Unit3 Notes (1)

Uploaded by

vahaneaniket
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Interactive SQL and Advance SQL: SQL Performance

Tuning

CO1: Create and Manage Database using SQL Commands


Concept Explanation-String Functions

• String Functions are used to perform string manipulation operations.

Function Example Result Purpose


ASCII ASCII(‘A’) 65 Returns an ASCII code value of a character.
Converts a numeric value to its corresponding ASCII
CHR CHR(’65’) ‘A’
character.
CONCAT CONCAT(‘A’,’BC’) ‘ABC’ Concatenate two strings and return the combined string.
Converts the first character in each word in a specified
INITCAP INITCAP(‘hi there’) ‘Hi There’
string to uppercase and the rest to lowercase.
Search for a substring and return the location of the
INSTR INSTR( ‘This is a playlist’, ‘is’) 3
substring in a string
Return the number of characters (or length) of a
LENGTH LENGTH(‘ABC’) 3
specified string
Return a string with all characters converted to
LOWER LOWER(‘Abc’) ‘abc’
lowercase.
UPPER UPPER(‘Abc’) ‘ABC’ Convert all characters in a specified string to uppercase.

S.V.BAHALE 2
Concept Explanation-String Functions

Function Example Result Purpose


Return a string that is right-padded with the
RPAD RPAD(‘ABC’,5,’*’) ‘ABC**’
specified characters to a certain length.
Return a string that is left-padded with the
LPAD LPAD(‘ABC’,5,’*’) ‘**ABC’
specified characters to a certain length.
‘BLACK AND Replace all occurrences of a substring by
REPLACE REPLACE(‘JACK AND JOND’,’J’,’BL’);
BLOND’ another substring in a string.
Replace all occurrences of characters by
TRANSLATE TRANSLATE(‘12345’, ‘143’, ‘bx’) ‘b2x5’
other characters in a string.
Remove the space character or other
TRIM TRIM(‘ ABC ‘) ‘ABC’ specified characters either from the start or
end of a string.
Remove all spaces or specified character in a
RTRIM RTRIM(‘ ABC ‘) ‘ ABC’
set from the right end of a string.
Remove spaces or other specified characters
LTRIM LTRIM(‘ ABC ‘) ‘ABC ‘
in a set from the left end of a string.
SUBSTR SUBSTR(‘Oracle Substring’, 1, 6 ) ‘Oracle’ Extract a substring from a string.
S.V.BAHALE 2
String Functions

S.V.BAHALE 3
Arithmetic Functions:
• SQL Arithmetic functions are used for numeric manipulation and Mathematical calculations.

• ABS(): It returns the absolute value of a number.


 Syntax: SELECT ABS(-243.5) from dual;
 Output: 243.5

• 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

• COS(): It returns the cosine of a number.


 Syntax: SELECT COS(30) from dual;

• DIV(): It is used for integer division.


 Syntax: SELECT 10 DIV 5 from dual;
 Output: 2

• EXP(): It returns e raised to the power of number.


 Syntax: SELECT EXP(1) from dual;
 Output: 2.718281828459045

• GREATEST(): It returns the greatest value in a list of expressions.


 Syntax: SELECT GREATEST(30, 2, 36, 81, 125) from dual;
 Output: 125

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

• LOG10(): It returns the base-10 logarithm of a number.


 Syntax: SELECT LOG(2) from dual;

• MOD(): It returns the remainder of n divided by m.


 Syntax: SELECT MOD(18, 4) from dual;
 Output: 2

• POW(): It returns m raised to the nth power.


 Syntax: SELECT POW(4, 2) from dual;
 Output: 16

• RADIANS(): It converts a value in degrees to radians.


 Syntax: SELECT RADIANS(180) from dual;
 Output: 3.141592653589793

• RAND(): It returns a random number.


 Syntax: SELECT RAND()from dual;
 Output: 0.33623238684258644

• ROUND(): It returns a number rounded to a certain number of decimal places.


 Syntax: SELECT ROUND(5.553) from dual;
 Output: 6

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

• SIN(): It returns the sine of a number.


 Syntax: SELECT SIN(2) from dual;
 Output: 0.9092974268256817

• SQRT(): It returns the square root of a number.


 Syntax: SELECT SQRT(25) from dual;
 Output: 5

• TAN(): It returns the tangent of a number.


 Syntax: SELECT TAN(1.75) from dual;
 Output: -5.52037992250933

• TRUNCATE(): It returns 7.53635 truncated to 2 places right of the decimal point.


 Syntax: SELECT TRUNCATE(7.53635, 2) from dual;
 Output: 7.53

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

ADDDATE() Add time values (intervals) to a date value


ADDTIME() Add time
CONVERT_TZ() Convert from one time zone to another
CURDATE() Return the current date
CURRENT_DATE(), CURRENT_DATE Synonyms for CURDATE()
CURRENT_TIME(), CURRENT_TIME Synonyms for CURTIME()
CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP Synonyms for NOW()
CURTIME() Return the current time
DATE() Extract the date part of a date or datetime 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()
DAYNAME() Return the name of the weekday
DAYOFMONTH() Return the day of the month (0-31)
DAYOFWEEK() Return the weekday index of the argument
DAYOFYEAR() Return the day of the year (1-366)
EXTRACT() Extract part of a date
FROM_DAYS() Convert a day number to a date
FROM_UNIXTIME() Format Unix timestamp as a date
GET_FORMAT() Return a date format string
HOUR() Extract the hour
LAST_DAY Return the last day of the month for the argument
LOCALTIME(), LOCALTIME Synonym for NOW()
S.V.BAHALE 11
Concept Explanation-Date/Time Functions
Name Description
LOCALTIMESTAMP, LOCALTIMESTAMP() Synonym for NOW()
MAKEDATE() Create a date from the year and day of year
MAKETIME() Create time from hour, minute, second
MICROSECOND() Return the microseconds from argument
MINUTE() Return the minute from the argument
MONTH() Return the month from the date passed
MONTHNAME() Return the name of the month
NOW() Return the current date and time
PERIOD_ADD() Add a period to a year-month
PERIOD_DIFF() Return the number of months between periods
QUARTER() Return the quarter from a date argument
SEC_TO_TIME() Converts seconds to 'hh:mm:ss' format
SECOND() Return the second (0-59)
STR_TO_DATE() Convert a string to a date
SUBDATE() Synonym for DATE_SUB() when invoked with three arguments
SUBTIME() Subtract times
SYSDATE() Return the time at which the function executes
TIME() Extract the time portion of the expression passed
TIME_FORMAT() Format as time
TIME_TO_SEC() Return the argument converted to seconds
TIMEDIFF() Subtract time

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

TIMESTAMPADD() Add an interval to a datetime expression


TIMESTAMPDIFF() Subtract an interval from a datetime expression
TO_DAYS() Return the date argument converted to days
TO_SECONDS() Return the date or datetime argument converted to seconds since Year 0

UNIX_TIMESTAMP() Return a Unix timestamp


UTC_DATE() Return the current UTC date
UTC_TIME() Return the current UTC time
UTC_TIMESTAMP() Return the current UTC date and time
WEEK() Return the week number
WEEKDAY() Return the weekday index
WEEKOFYEAR() Return the calendar week of the date (1-53)
YEAR() Return the year
YEARWEEK() Return the year and week

S.V.BAHALE 13
Concept Explanation-Aggregate Functions
• SUM( [ALL | DISTINCT] expression )
SELECT SUM(Salary) total_sal FROM employees;

• AVG( [ALL | DISTINCT] expression )


SELECT AVG(Salary) FROM employees;

• COUNT( [ALL | DISTINCT] expression )

• COUNT(* )
SELECT COUNT(* ) FROM employees;

• MAX(expression) and MIN(expression)


SELECT MIN (hire_date) oldest, MAX (hire_date) latest
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:

select column, group_function


from <table_name>
[where condition]
[group by group_exprssion]
[Having group_condition]
[order by column]

S.V.BAHALE 15
Concept Explanation-Group By Clause

Below query lists the count of employees working in each department.


 SELECT DEPARTMENT_ID, COUNT ( * )
FROM employees
GROUP BY DEPARTMENT_ID;

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

 Order Clause specifies the order in which rows are displayed.


 The order by clause is used to arrange the records in ascending or descending order.

Guidelines :

1. The order by should be placed last in a query.


2. The default sort is ascending.
3. Sorting can be done by more than one column.

Syntax:

select <expression>
from <table_name>
[where condition]
[order by [column|expression][asc|desc]]

asc:- Ascending order. This is the default sorting order.


desc:- Descending order.

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.

Having clause performs following steps.


1. Rows are grouped
2. Group function is applied to group.
3. Group that match the criteria in having clause is displayed.

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.

SELECT E.first_name FIRST_NAME, D.department_name DNAME


FROM employees E JOIN departments D
ON (E.department_id = D.department_id);

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.

select * from emp e1, emp m1 where e1.e_id=e2.mgr_id;

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.

percentage Table student Table


Category Low_Per High_Per rollno stud_name percentage

Average 50 60 1 Anil 70

Good 61 75 2 Jaya 75

Excellent 76 100 3 Vijay 60

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.

SELECT employee.first_name, employee.salary, department.department_id


FROM employee RIGHT OUTER JOIN department
on (employee.department_id = department.department_id);

FIRST_NAME SALARY DEPARTMENT_ID

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.

SELECT employee.first_name, employee.salary, department.department_id


FROM employee LEFT OUTER JOIN department
on (employee.department_id = department.department_id);

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.

Select * from employee FULL OUTER JOIN department


on (employee.department_id = department.department_id);

Cartesian product or Cross join


• Cross join refers to the Cartesian product of two tables. For two entities A and B, A * B is known as Cartesian
product.
• A Cartesian product consists of all possible combinations of the rows from each of the tables.

SELECT E.first_name, D.DNAME


FROM employees E CROSS JOIN departments D;

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

Single row subqueries :


Single row subquery returns one row from the inner SELECT statement .
Syntax:
Select column1, column2,……, column n
From table_name
Where column1 operator ( select column from table_name where condition ;

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) ;

Multiple column subqueries :


Query that returns values from more than one column are called Multiple column subqueries .
Syntax:
Select column1, column2,……, column n
From table_name
Where (column1 , column 2) IN ( select column 1, column 2 from table_name where condition);

S.V.BAHALE 25
Concept Explanation- Subquery
Examples :
Student Table Marks table

Single row subquery :


Query : Identify all students who get better marks than that of the student who's StudentID is 'V002‘.
First query: query returns the marks (stored in Total_marks field) of 'V002'
SELECT *
FROM Marks
WHERE StudentID= 'V002';

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:

Multiple row subqueries :


• Use of IN:
Select stud_name, ssc_per, branch_code
From stud_info
Where ssc_per IN
(select min(ssc_per)
from stud_info
group by branch_code);

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);

Multiple column subqueries :


Display student name, branch code, ssc percentage , grade of any student whose ssc_per and grades matches both
matches with the ssc_per and grade of any student in IF branch.
Select stud_name, ssc_per, branch_code, grade
From stud_info
Where (ssc_per , grade) IN
(select ssc_per, grade
from stud_info
where branch_code= ‘IF ‘);

S.V.BAHALE 28
Concept Explanation- View

• A view is a virtual table based on the result-set of an SQL statement.


• A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real
tables in the database.
• Views, allow users to do the following −
 Allows user to make simple queries to retrieve results from complicated queries.
 Restrict access to the data.
 Summarize data from various tables which can be used to generate reports.
• Creating Views
• Database views are created using the CREATE VIEW statement. Views can be created from a single table,
multiple tables or another 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.

CREATE VIEW view_name AS


SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example :
CREATE VIEW CUSTOMERS_VIEW AS SELECT name, age
FROM CUSTOMERS;

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 |
+ + +

A view can be updated with the CREATE OR REPLACE VIEW command.

CREATE OR REPLACE VIEW view_name AS


SELECT column1, column2, ...
FROM table_name
WHERE condition;

S.V.BAHALE 31
Concept Explanation- View
The WITH CHECK OPTION :

CREATE VIEW CUSTOMERS_VIEW AS SELECT name, age


FROM CUSTOMERS
WHERE age IS NOT NULL
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.

Insert into CUSTOMERS_VIEW values(8,’Neha’, 30, ‘Yavatmal’,20000);

Deleting Rows from a View :


Rows of data can be deleted from a view.

DELETE FROM CUSTOMERS_VIEW WHERE age = 22;

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.

MAXVALUE Specify the maximum value the sequence can generate.

NOMAXVALUE Specify NOMAXVALUE to indicate a maximum value of 1027 for an ascending sequence or -1 for a
descending sequence.

MINVALUE Specify the minimum value of the 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 ;

Inserting value using a sequence:


insert into dept (deptno, dname, loc )
values(dept_deptno.nextval, ‘marketing’ , ‘mumbai’ );

Viewing current value for the sequence :


select dept_deptno.currval from dual ;

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 :

alter sequence <sequence number>


[increment by n]
[{maxvalue n | nomaxvalue}]
[{minvalue n | nominvalue}]
[{cycle | nocycle}]
[{cache n | nocache}]

Example :
alter sequence dept_deptno maxvalue 120;

 Deleting a sequence :

Syntax : drop sequence <sequence name>;


Example : drop sequence dept_deptno ;

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

You might also like