Download as pdf or txt
Download as pdf or txt
You are on page 1of 83

Unit-III:

INTERACTIVE SQL AND ADVANCE SQL: SQL


PERFORMANCE TUNING
Marks:14

Database Management System (DMS) Mr. S. Y. Divekar


Database Management System (DMS) Mr. S. Y. Divekar
Topic:- 3.1 : Outlines
In-built Function :
String Function.
Arithmetic Function.

Database Management System (DMS) Mr. S. Y. Divekar


In-Built Function : String
String functions String function are used to perform an operation
on input string and return an output string.
ASCII(): This function is used to find the ASCII value of a
character.
Syntax: SELECT ascii('t'); Output: 116
CHAR_LENGTH(): This function is used to find the length of a
word.
Syntax: SELECT char_length('Hello!'); Output: 6
CHARACTER_LENGTH(): This function is used to find the length
of a line.
Syntax: SELECT CHARACTER_LENGTH('ANKIT DUBEY'); Output: 11

Database Management System (DMS) Mr. S. Y. Divekar


In-Built Function : String
CONCAT(): This function is used to add two words or strings.
Syntax: SELECT ‘Sanchit' || ' ' || ‘Bhosale' FROM dual;
Output: ‘Sanchit Bhosale’
LCASE(): This function is used to convert the given string into
lower case.
Syntax: LCASE (" SANCHIT BHOSALE "); Output: sanchit bhosale
LEFT(): This function is used to SELECT a sub string from the left
of given size or characters.
Syntax: SELECT LEFT(‘Sanchit Bhosale ', 6); Output: Sanchi
LENGTH(): This function is used to find the length of a word.
Syntax: LENGTH(' Sanchit Bhosale '); Output: 15

Database Management System (DMS) Mr. S. Y. Divekar


In-Built Function : String
FORMAT(): This function is used to display a number in the given
format.
Syntax: SELECT Format("0.981", "Percent") FROM dual;
Output: ‘98.10%’
LPAD(): This function is used to make the given string of the
given size by adding the given symbol.
Syntax: LPAD('geeks', 8, '0'); Output: 000geeks
RPAD(): This function is used to make the given string as long as
the given size by adding the given symbol on the right.
Syntax: RPAD('geeks', 8, '0'); Output: ‘geeks000’
RIGHT(): This function is used to SELECT a sub string from the
right end of the given size
Syntax: SELECT RIGHT('geeksforgeeks.org', 4) from dual;
Output: ‘.org’
Database Management System (DMS) Mr. S. Y. Divekar
In-Built Function : String
LTRIM(): This function is used to cut the given sub string from
the original string.
 Syntax: LTRIM('123123geeks', '123'); Output: ‘geeks’
RTRIM(): This function is used to cut the given sub string from
the original string.
Syntax: RTRIM('geeksxyxzyyy', 'xyz'); Output: ‘geeks’
POSITION(): This function is used to find position of the first
occurrence of the given alphabet.
Syntax: SELECT POSITION('e' IN 'geeksforgeeks') FROM dual;
Output: 2
LOCATE(): This function is used to find the nth position of the
given word in a string.
Syntax: SELECT LOCATE('for', 'geeksforgeeks', 1) from dual;
Output: 6
Database Management System (DMS) Mr. S. Y. Divekar
In-Built Function : String
REPEAT(): This function is used to write the given string again
and again till the number of times mentioned.
Syntax: SELECT REPEAT('geeks', 2) FROM dual;
Output: ‘geeksgeeks’
REPLACE(): This function is used to cut the given string by
removing the given sub string.
Syntax: REPLACE('123geeks123', '123'); Output: ‘geeks’
REVERSE(): This function is used to reverse a string.
Syntax: SELECT REVERSE('geeksforgeeks.org') FROM dual;
Output: ‘gro.skeegrofskeeg’
SUBSTR(): This function is used to find a sub string from the a
string from the given position.
Syntax: SUBSTR('geeksforgeeks', 1, 5); Output: ‘geeks’

Database Management System (DMS) Mr. S. Y. Divekar


In-Built Function : String

Database Management System (DMS) Mr. S. Y. Divekar


In-Built Function : Arithmetic Function
Mathematical functions are very important in SQL to implement
different mathematical concepts in queries.
ABS(): returns the absolute value of a number passed as
argument.
Syntax: SELECT ABS(-17.36) FROM dual; Output: 17.36
CEIL(): will rounded up any positive or negative decimal value
within the function upwards.
Syntax: SELECT CEIL(17.36) FROM dual; Output: 18
FLOOR(): rounded up any positive or negative decimal value
down to the next least integer value. SQL DISTINCT along with the
SQL FLOOR() function is used to retrieve only unique value after
rounded down to the next least integer value depending on the
column specified.
Syntax: SELECT FLOOR(17.36) FROM dual; Output: 17
Syntax: SELECT FLOOR(-17.36) FROM dual; Output: -18
Database Management System (DMS) Mr. S. Y. Divekar
In-Built Function : Arithmetic Function
EXP(): returns e raised to the n-th power(n is the numeric
expression), where e is the base of natural algorithm and the
value of e is approximately 2.71828183.
Syntax: SELECT EXP(2) AS e_to_2s_power FROM dual;
Output: 7.3890560989306502272304274605750078132
MOD(): function returns the remainder from a division. The SQL
DISTINCT command along with the SQL MOD() function is used to
retrieve only unique records depending on the specified column
or expression. MOD(dividend , divider )
Syntax: SELECT MOD(25 , 7) FROM dual; Output: 4
 LN(): function returns the natural logarithm of n, where n is
greater than 0 and its base is a number equal to approximately
2.71828183.
Syntax: SELECT LN(65) "natural_log of 65" FROM dual;
Output: 4.17438726989563711065424677479150624431
Database Management System (DMS) Mr. S. Y. Divekar
In-Built Function : Arithmetic Function
POWER(): POWER returns the value of a number raised to
another, where both of the numbers are passed as arguments.
The SQL DISTINCT command along with the SQL POWER()
function can be used to retrieve only unique data depending on a
specified expression. POWER( base, exponent )
Syntax: SELECT POWER(2 , 3) FROM dual; Output: 8
LOG10(): It returns the base-10 logarithm of a number.
Syntax: SELECT LOG(2) FROM dual;
Output: 0.6931471805599453
 RAND(): It returns a random number.
Syntax: SELECT RAND() FROM dual; Output: 0.3362323868
 ROUND(): It returns a number rounded to a certain number of
decimal places.
Syntax: SELECT ROUND(5.553) FROM dual; Output: 6

Database Management System (DMS) Mr. S. Y. Divekar


In-Built Function : Arithmetic Function
SIGN(): It returns a value indicating the sign of a number.
Syntax: SELECT SIGN(255.5) FROM dual; Output: 1
SQRT(): It returns the square root of a number.
Syntax: SELECT SQRT(25) FROM dual;
Output: 5
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
TRUNCATE(): This doesn’t work for SQL Server. It returns
7.53635 truncated to 2 places right of the decimal point.
Syntax: SELECT TRUNCATE(7.53635, 2) FROM dual; Output: 7.53

Database Management System (DMS) Mr. S. Y. Divekar


In-Built Function : Arithmetic Function
COS(): It returns the cosine of a number.
Syntax: SELECT COS(30) FROM dual;
Output: 0.15425144988758405
COT(): It returns the cotangent of a number.
Syntax: SELECT COT(6) FROM dual;
Output: -3.436353004180128
SIN(): It returns the sine of a number.
Syntax: SELECT SIN(2) FROM dual;
Output: 0.9092974268256817
 TAN(): It returns the tangent of a number.
Syntax: SELECT TAN(1.75) FROM dual;
Output: -5.52037992250933

Database Management System (DMS) Mr. S. Y. Divekar


In-Built Function : Arithmetic Function
LEAST() : The LEAST() function returns the smallest value of the
list of arguments.
LEAST(arg1, arg2, arg3, ...)
Syntax: SELECT LEAST(3, 12, 34, 8, 25) FROM dual;
Output: 3
GREATEST() : The LEAST() function returns the smallest value of
the list of arguments.
GREATEST (arg1, arg2, arg3, ...)
Syntax: SELECT GREATEST (3, 12, 34, 8, 25) FROM dual;
Output: 34

Database Management System (DMS) Mr. S. Y. Divekar


Topic:- 3.2 : Outlines
Date and time function
 Aggregate functions

Database Management System (DMS) Mr. S. Y. Divekar


Date and time function
Dates are complicated for newbies, since while working with
database, the format of the date in table must be matched with
the input date in order to insert. In various scenarios instead of
date, datetime (time is also involved with date) is used.
SYSDATE(): It returns the current date and time.
Syntax: SELECT SYSDATE() FROM dual;
Output: 2020-10-06 09:19:03
MONTH(): It returns the month portion of a date value.
Syntax: SELECT MONTH ('2018/07/18')AS MONTH FROM dual;
Output: 7

Database Management System (DMS) Mr. S. Y. Divekar


Date and time function
ADD_MONTHS(): This function returns a date with a given
number of months added (date plus integer months). A month is
defined by the session parameter NLS_CALENDAR.
ADD_MONTHS(date, integer)
Syntax: SELECT ADD_MONTHS(‘05-JAN-20’, 7) FROM dual;
Output: 05-AUG-20

Database Management System (DMS) Mr. S. Y. Divekar


Date and time function
MONTHS_BETWEEN(): MONTHS_BETWEEN returns number
of months between dates date1 and date2.
If date1 is later than date2, then the result is positive.
If date1 is earlier than date2, then the result is negative.
If date1 and date2 are either the same days of the month or
both last days of months, then the result is always an integer.
Otherwise Oracle Database calculates the fractional portion of
the result based on a 31-day month and considers the difference
in time components date1 and date2.

MONTHS_BETWEEN(date1, date2)

Database Management System (DMS) Mr. S. Y. Divekar


Date and time function
MONTHS_BETWEEN():

Syntax: SELECT ADD_MONTHS(‘05-JAN-20’, ‘05-OCT-20’) FROM


dual;
Output: 9

Database Management System (DMS) Mr. S. Y. Divekar


Date and time function
NEXT_DAY(): NEXT_DAY returns the date of the first weekday
that is later than the date.
NEXT_DAY(date, char)
Syntax: SELECT NEXT_DAY('06-OCT-2020','MONDAY')"NEXT DAY" FROM dual;
Output: 12-OCT-2020 00:00:00

Database Management System (DMS) Mr. S. Y. Divekar


Date and time function
LAST_DAY():LAST_DAY() function returns the last day of the
month that contains a date. The return type is always DATE,
regardless of the datatype of date.
LAST_DAY(date)
Syntax: SELECT LAST_DAY(SYSDATE)"LAST DAY" FROM dual;
Output: 31-OCT-2020

Database Management System (DMS) Mr. S. Y. Divekar


Date and time function
SYSTIMESTAMP():The SYSTIMESTAMP function is used to get the
system date, including fractional seconds and time zone, of the
system on which the database resides.
SYSTIMESTAMP
Syntax: SELECT SYSTIMESTAMP FROM dual;
Output: 06-OCT-20 12.55.19.384000 PM +05:30

Database Management System (DMS) Mr. S. Y. Divekar


Date and time function
DATE_ADD():The DATE_ADD() function adds a time/date interval
to a date and then returns the date.
DATE_ADD(date, INTERVAL value addunit)
Syntax: SELECT DATE_ADD("2020-10-06 12:40:21",
INTERVAL 15 MINUTE) FROM dual;
Output: 06-OCT-20 12.55.19.384000 PM +05:30
DATE_SUB():The DATE_SUB() function subtracts a time/date
interval from a date and then returns the date.
DATE_SUB (date, INTERVAL value addunit)
Syntax: SELECT DATE_SUB ("2020-10-06 12:40:21",
INTERVAL 15 MINUTE) FROM dual;
Output: 06-OCT-20 12.25.19.384000 PM +05:30

Database Management System (DMS) Mr. S. Y. Divekar


Date and time function
NOW():The NOW() function returns the current date and time.
Syntax: SELECT NOW() FROM dual;
Output: 06-OCT-20 12.55.19.384000 PM +05:30
DATEDIFF():The DATEDIFF() function returns the number of days
between two date values.
DATEDIFF(date1, date2)
Syntax: SELECT DATEDIFF("2020-06-25", "2020-06-15")FROM
dual;
Output: 10

Database Management System (DMS) Mr. S. Y. Divekar


Conversion Functions in SQL
If the programmer wants, they can explicitly convert data types
from one form to another. There are SQL functions provided for
this express purpose.
TO_CHAR():This function is used to explicitly convert a number
or date data type to char.
TO_CHAR(number,format,parameters)
Syntax: SELECT TO_CHAR( sysdate, 'YYYY-MM-DD' )FROM dual;
Output: 2020-10-06
TO_NUMBER ():This function is used to explicitly convert a
string to number. If the string to be converted does not contain
numeric characters then TO_NUMBER shows an error.
TO_NUMBER(number,format,parameters)
Syntax: SELECT TO_NUMBER('546', '999') FROM dual;
Output: 546
Database Management System (DMS) Mr. S. Y. Divekar
Conversion Functions in SQL
TO_DATE():This function takes character values and returns the
output in the date format.
TO_DATE(number, format, parameters)
Syntax: SELECT to_date(20201110,'yyyymmdd') FROM DUAL;
Output: 10-NOV-20

Syntax: select to_char(to_date(20201006,'yyyymmdd'),'dd/mm/yyyy') from


dual;
Output: 06/10/2020

Database Management System (DMS) Mr. S. Y. Divekar


Aggregate functions in SQL
Aggregate function is a function where the values of multiple rows
are grouped together as input on certain criteria to form a single
value of more significant meaning.
Various Aggregate Functions
1) Count()
2) Sum()
3) Avg()
4) Min()
5) Max()

Database Management System (DMS) Mr. S. Y. Divekar


Aggregate functions in SQL
Count():The COUNT() aggregate function returns the number of
rows in a group, including rows with NULL values.
COUNT counts how many rows are in a particular column.
Syntax: SELECT COUNT (column_name) FROM table_name
WHERE condition;
Example: SELECT COUNT (emp_name) FROM employee
WHERE dept_id=406;
Sum():The SUM() aggregate function returns the summation of
all non-NULL values a set.
Syntax: SELECT SUM (column_name) FROM table_name
WHERE condition;
Example: SELECT SUM (Salary) FROM employee
WHERE dept_name=‘co’;

Database Management System (DMS) Mr. S. Y. Divekar


Aggregate functions in SQL
AVG():The AVG() aggregate function calculates the average of non-NULL
values in a set.
Syntax: SELECT AVG (column_name) FROM table_name
WHERE condition;
Example: SELECT AVG (Salary) FROM employee;
MIN(): The MIN() aggregate function returns the lowest value (minimum)
in a set of non-NULL values.
Syntax: SELECT MIN (column_name) FROM table_name
WHERE condition;
Example: SELECT MIN (Salary) FROM employee
WHERE dept_name=‘co’;
MAX(): The MAX() aggregate function returns the highest value
(maximum) in a set of non-NULL values.
Syntax: SELECT MAX(column_name) FROM table_name
WHERE condition;
Example: SELECT MAX(Salary) FROM employee
WHERE dept_name=‘co’;
Database Management System (DMS) Mr. S. Y. Divekar
Topic:- 3.3 : Outlines
Query using Group By, Order BY Aggregate,
Having clause
Joins- Inner and Outer Join
Sub Queries.

Database Management System (DMS) Mr. S. Y. Divekar


GROUP BY CLAUSE IN SQL
This clause shows that the rows should be classified according to
the specified expression values for every group.
A GROUP BY clause, part of a select Expression, groups a result
into subsets that have matching values for one or more columns.
In each group, no two rows have the same value for the grouping
column or columns. NULLs are considered equivalent for grouping
purposes.
Syntax: SELECT column1, column2 FROM table_name
WHERE [ conditions ] GROUP BY column1, column2;
Example: SELECT Dept_Name, SUM(Salary) FROM employee
GROUP BY Dept_Name;

Database Management System (DMS) Mr. S. Y. Divekar


HAVING CLAUSE IN SQL
The HAVING Clause enables you to specify conditions that filter
which group results appear in the results.
The WHERE clause places conditions on the selected columns,
whereas the HAVING clause places conditions on groups created
by the GROUP BY clause.
The expressions used in this clause must contain an aggregate
function that is COUNT, AVG, SUM, MIN, MAX.
Syntax: SELECT column1, column2 FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
HAVING condition;
Example: SELECT Dept_Name, SUM(Salary) FROM employee
GROUP BY Dept_Name HAVING SUM(Salary) > 60000;

Database Management System (DMS) Mr. S. Y. Divekar


ORDER BY CLAUSE IN SQL
The SQL ORDER BY clause is used to sort the data in ascending or
descending order, based on one or more columns. Some
databases sort the query results in an ascending order by default.
Syntax: SELECT column1, column2 FROM table_name
WHERE [ conditions ]
ORDER BY column1, column2, .. columnN [ASC | DESC];
Example: SELECT * FROM employee
ORDER BY Emp_Name, SALARY;
Example: SELECT * FROM employee
ORDER BY Emp_Name DESC;
Example:
SELECT Emp_no, Emp_Name, SUM(Salary) FROM Employee
GROUP BY Emp_Name HAVING SUM(Salary) < 30000
ORDER BY Emp_Name DESC;
Database Management System (DMS) Mr. S. Y. Divekar
JOIN IN SQL
SQL Join is used to fetch data from two or more tables, which is
joined to appear as single set of data. It is used for combining
column from two or more tables by using values common to both
tables.
JOIN Keyword is used in SQL queries for joining two or more
tables.
Minimum required condition for joining table, is (n-1) where n, is
number of tables. A table can also join to itself, which is known
as, Self Join.
A JOIN clause is used to combine rows from two or more tables,
based on a related column between them.

Database Management System (DMS) Mr. S. Y. Divekar


Types of SQL JOINs
Following are the types of JOIN that we can use in SQL:
oINNER : (INNER) JOIN: Returns records that have matching values
in both tables.
oLEFT (OUTER) JOIN: Returns all records from the left table, and
the matched records from the right table
oRIGHT (OUTER) JOIN: Returns all records from the right table,
and the matched records from the left table.
oFULL (OUTER) JOIN: Returns all records when there is a match in
either left or right table.

Database Management System (DMS) Mr. S. Y. Divekar


INNER JOIN:
The INNER JOIN keyword selects all rows from both the tables as
long as the condition satisfies. This keyword will create the result-
set by combining all rows from both the tables where the
condition satisfies i.e value of the common field will be same.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,.... FROM
table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;
table1: First table.
table2: Second table
matching_column: Column common to both the tables.

Database Management System (DMS) Mr. S. Y. Divekar


INNER JOIN:
Create Employees and Departments tables as following:
Employee table:
◦ Emp_id (Number) / identifier
◦ Emp_name (varchar)
◦ Emp_DOB (date)
◦ Dept_Id (reference to departments table)

Department table:
◦ Dept_id (Number) / identifier
◦ Dept_Name (varchar)

Example: SELECT Employee.Emp_id, Employee.Emp_name ,


Department.Dept_name FROM Employee INNER JOIN
Department ON Employee.Dept_id = Department.Dept_id ;

Database Management System (DMS) Mr. S. Y. Divekar


LEFT JOIN:
This join returns all the rows of the table on the left side of the
join and matching rows for the table on the right side of join. The
rows for which there is no matching row on right side, the result-
set will contain null. LEFT JOIN is also known as LEFT OUTER JOIN.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1 LEFT JOIN table2
ON table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.

Database Management System (DMS) Mr. S. Y. Divekar


LEFT JOIN:
Create Employees and Departments tables as following:
Employee table:
◦ Emp_id (Number) / identifier
◦ Emp_name (varchar)
◦ Emp_DOB (date)
◦ Dept_Id (reference to departments table)

Department table:
◦ Dept_id (Number) / identifier
◦ Dept_Name (varchar)

Example: SELECT Employee.Emp_id, Employee.Emp_name ,


Department.Dept_name FROM Employee LEFT JOIN Department
ON Employee.Dept_id = Department.Dept_id ;

Database Management System (DMS) Mr. S. Y. Divekar


RIGHT JOIN:
RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of
the table on the right side of the join and matching rows for the
table on the left side of join. The rows for which there is no
matching row on left side, the result-set will contain null. RIGHT
JOIN is also known as RIGHT OUTER JOIN.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1 RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.

Database Management System (DMS) Mr. S. Y. Divekar


RIGHT JOIN:
Create Employees and Departments tables as following:
Employee table:
◦ Emp_id (Number) / identifier
◦ Emp_name (varchar)
◦ Emp_DOB (date)
◦ Dept_Id (reference to departments table)

Department table:
◦ Dept_id (Number) / identifier
◦ Dept_Name (varchar)

Example: SELECT Employee.Emp_id, Employee.Emp_name ,


Department.Dept_name
FROM Employee RIGHT JOIN Department
ON Employee.Dept_id = Department.Dept_id ;

Database Management System (DMS) Mr. S. Y. Divekar


FULL JOIN:
FULL JOIN creates the result-set by combining result of both LEFT
JOIN and RIGHT JOIN. The result-set will contain all the rows from
both the tables. The rows for which there is no matching, the
result-set will contain NULL values.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1 FULL JOIN table2
ON table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.

Database Management System (DMS) Mr. S. Y. Divekar


FULL JOIN:
Create Employees and Departments tables as following:
Employee table:
◦ Emp_id (Number) / identifier
◦ Emp_name (varchar)
◦ Emp_DOB (date)
◦ Dept_Id (reference to departments table)

Department table:
◦ Dept_id (Number) / identifier
◦ Dept_Name (varchar)

Example: SELECT Employee.Emp_id, Employee.Emp_name ,


Department.Dept_name
FROM Employee FULL JOIN Department
ON Employee.Dept_id = Department.Dept_id ;

Database Management System (DMS) Mr. S. Y. Divekar


SQL - Sub Queries:
A Subquery or Inner query or a Nested query is a query within
another SQL query and embedded within the WHERE clause.
A subquery is used to return data that will be used in the main
query as a condition to further restrict the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and
DELETE statements along with the operators like =, <, >, >=, <=,
IN, BETWEEN, etc.

There are a few rules that subqueries must follow


Subqueries must be enclosed within parentheses.
A subquery can have only one column in the SELECT clause,
unless multiple columns are in the main query for the subquery
to compare its selected columns.

Database Management System (DMS) Mr. S. Y. Divekar


SQL - Sub Queries:
There are a few rules that subqueries must follow
An ORDER BY command cannot be used in a subquery, although
the main query can use an ORDER BY. The GROUP BY command
can be used to perform the same function as the ORDER BY in a
subquery.
Subqueries that return more than one row can only be used with
multiple value operators such as the IN operator.
The SELECT list cannot include any references to values that
evaluate to a BLOB, ARRAY, CLOB, or NCLOB.
A subquery cannot be immediately enclosed in a set function.
The BETWEEN operator cannot be used with a subquery.
However, the BETWEEN operator can be used within the
subquery.

Database Management System (DMS) Mr. S. Y. Divekar


Subqueries with the SELECT Statement:
Subqueries are most frequently used with the SELECT statement.
The basic syntax is as follows .
Syntax:
SELECT column_name [, column_name ] FROM table1 [, table2 ]
WHERE column_name OPERATOR (SELECT column_name [,
column_name ] FROM table1 [, table2 ] [WHERE]);

Example:
SELECT * FROM Employee WHERE Emp_id IN (SELECT Emp_id
FROM Employee WHERE SALARY > 6500) ;

Database Management System (DMS) Mr. S. Y. Divekar


Subqueries with the INSERT Statement:
Subqueries also can be used with INSERT statements. The INSERT
statement uses the data returned from the subquery to insert
into another table. The selected data in the subquery can be
modified with any of the character, date or number functions.
Syntax:
INSERT INTO table_name [ (column1 [, column2 ]) ] SELECT [
*|column1 [, column2 ] FROM table1 [, table2 ] [ WHERE VALUE
OPERATOR ]
Example:
Consider a table EMP_SYD with similar structure as Employee
table. Now to copy the complete Employee table into the
EMP_SYD table, you can use the following syntax.
INSERT INTO EMP_SYD SELECT * FROM Employee WHERE Emp_ID
IN (SELECT Emp_ID FROM Employee ) ;

Database Management System (DMS) Mr. S. Y. Divekar


Subqueries with the UPDATE Statement:
The subquery can be used in conjunction with the UPDATE
statement. Either single or multiple columns in a table can be
updated when using a subquery with the UPDATE statement.
Syntax:
UPDATE table SET column_name = new_value [ WHERE
OPERATOR [ VALUE ] (SELECT COLUMN_NAME FROM
TABLE_NAME) [ WHERE) ]
Example:
Assuming, we have EMP_SYD table available which is backup of
Employee table. The following example updates SALARY by 0.25
times in the Employee table for all the customers whose AGE is
greater than or equal to 27.
UPDATE Employee SET SALARY = SALARY * 0.25 WHERE AGE IN
(SELECT AGE FROM EMP_SYD WHERE AGE >= 27 );

Database Management System (DMS) Mr. S. Y. Divekar


Subqueries with the DELETE Statement:
The subquery can be used in conjunction with the DELETE
statement like with any other statements mentioned above.
Syntax:
DELETE FROM TABLE_NAME [ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME FROM TABLE_NAME) [ WHERE) ]
Example:
Assuming, we have a EMP_SYD table available which is a backup
of the Employee table. The following example deletes the records
from the Employee table for all the customers whose AGE is
greater than or equal to 27.

DELETE FROM CUSTOMERS WHERE AGE IN (SELECT AGE FROM


EMP_SYD WHERE AGE >= 27 );

Database Management System (DMS) Mr. S. Y. Divekar


Topic:- 3.4 : Outlines
Views: Concept of View,
create Views Command,
Updating Views
Views and Joins,
view and sub queries,
Dropping views

Database Management System (DMS) Mr. S. Y. Divekar


Views:
The view is a virtual table. It does not physically exist. Rather, it is
created by a query joining one or more tables.
A view contains rows and columns, just like a real table.
A view is nothing more than a SQL statement that is stored in the
database with an associated name. A view is actually a
composition of a table in the form of a predefined SQL query.
A view can contain all rows of a table or select rows from a table.
A view can be created from one or many tables which depends on
the written SQL query to create a view.
The fields in a view are fields from one or more real tables in the
database.

Database Management System (DMS) Mr. S. Y. Divekar


Views:
Views, which are a type of virtual tables allow users to do the
following −
Structure data in a way that users or classes of users find natural
or intuitive.
Restrict access to the data in such a way that a user can see and
(sometimes) modify exactly what they need and no more.
Summarize data from various tables which can be used to
generate reports.

Database Management System (DMS) Mr. S. Y. Divekar


Creating Views:
Database views are created using the CREATE VIEW statement.
Views can be created from a single table, multiple tables or
another view.
To create a view, a user must have the appropriate system
privilege according to the specific implementation.
Syntax:
CREATE VIEW view_name AS SELECT column1, column2..... FROM
table_name WHERE [condition];

Database Management System (DMS) Mr. S. Y. Divekar


Creating Views:
Example:
Consider the Employee table having the following

Following is an example to create a view from the Employee


table. This view would be used to have Employee name and age
from the Employee table.

CREATE VIEW EMP_VIEW AS SELECT name, age FROM Employee;

SELECT * FROM EMP_VIEW;

Database Management System (DMS) Mr. S. Y. Divekar


Updating a View:
A view can be updated with the CREATE OR REPLACE VIEW
command.
There are certain conditions needed to be satisfied to update a
view. If any one of these conditions is not met, then we will not
be allowed to update the view.
The SELECT statement which is used to create the view should
not include GROUP BY clause or ORDER BY clause.
The SELECT statement should not have the DISTINCT keyword.
The View should have all NOT NULL values.
The view should not be created using nested queries or complex
queries.
The view should be created from a single table. If the view is
created using multiple tables then we will not be allowed to
update the view.
Database Management System (DMS) Mr. S. Y. Divekar
Updating Views:
Syntax:
CREATE OR REPLACE VIEW view_name AS SELECT column1,
column2..... FROM table_name WHERE [condition];

Example:

CREATE OR REPLACE VIEW EMP_VIEW AS SELECT name, age


FROM Employee WHERE name=‘Krishna’;

UPDATE EMP_VIEW
SET AGE = 35
WHERE name = 'Ramesh';
SELECT * FROM EMP_VIEW;

Database Management System (DMS) Mr. S. Y. Divekar


Deleting a row from a View:
Deleting rows from a view is also as simple as deleting rows from
a table. We can use the DELETE statement of SQL to delete rows
from a view. Also deleting a row from a view first delete the row
from the actual table and the change is then reflected in the view.
Syntax:
DELETE FROM view_name WHERE condition;
Example:
DELETE FROM EMP_VIEW WHERE Name="Suresh";

Database Management System (DMS) Mr. S. Y. Divekar


Inserting a row in a view:
We can insert a row in a View in a same way as we do in a table.
We can use the INSERT INTO statement of SQL to insert a row in a
View.

Syntax:
INSERT INTO view_name(column1, column2 , column3,..) VALUES
(value1, value2, value3..);

Example:
INSERT INTO EMP_VIEW (Name, Age) VALUES (‘Sanchi’, 18);

Database Management System (DMS) Mr. S. Y. Divekar


Creating View from multiple tables
(View with JOIN):
To create a View from multiple tables we can simply include
multiple tables in the SELECT statement.

Example:
In this example we will create a View named MarksView from
two tables StudentDetails and StudentMarks.
CREATE VIEW MarksView AS SELECT StudentDetails.NAME,
StudentDetails.ADDRESS, StudentMarks.MARKS FROM
StudentDetails, StudentMarks WHERE StudentDetails.NAME =
StudentMarks.NAME;
Database Management System (DMS) Mr. S. Y. Divekar
View with subquery :
To create a View a subquery is used to return data that will be
used in the main query as a condition to further restrict the data
to be retrieved

Example:
CREATE VIEW Emp_View2 AS SELECT * FROM Employee WHERE
Emp_id IN (SELECT Emp_id FROM Employee WHERE SALARY >
1500) ;

Database Management System (DMS) Mr. S. Y. Divekar


Dropping Views:
A view is deleted with the DROP VIEW command.

Syntax:
DROP VIEW view_name;
Example:
DROP VIEW EMP_VIEW;

Database Management System (DMS) Mr. S. Y. Divekar


Topic:- 3.5 : Outlines
Sequences :
Creating sequences,
Altering Sequences,
Dropping sequences

Database Management System (DMS) Mr. S. Y. Divekar


Sequences :
Sequence is a set of integers 1, 2, 3, … that are generated and
supported by some database systems to produce unique values
on demand.
A sequence is a user defined schema bound object that
generates a sequence of numeric values.
Sequences are frequently used in many databases because
many applications require each row in a table to contain a unique
value and sequences provides an easy way to generate them.
The sequence of numeric values is generated in an ascending or
descending order at defined intervals and can be configured to
restart when exceeds max_value.

Database Management System (DMS) Mr. S. Y. Divekar


Create Sequences :
Syntax:
CREATE SEQUENCE sequence_name START WITH initial_value
INCREMENT BY increment_value
MINVALUE minimum value
MAXVALUE maximum value
CYCLE|NOCYCLE ;
initial_value: starting value from where the sequence starts.
Initial_value should be greater than or equal to minimum value and less
than equal to maximum value.
increment_value: Value by which sequence will increment itself.
Increment_value can be positive or negative.
minimum_value: Minimum value of the sequence.
maximum_value: Maximum value of the sequence.
cycle: When sequence reaches its set_limit it starts from beginning.
nocycle: An exception will be thrown if sequence exceeds its
max_value.

Database Management System (DMS) Mr. S. Y. Divekar


Create Sequences :
Example:
creating sequence in ascending order
CREATE SEQUENCE sequence_1 start with 1
increment by 1 minvalue 0 maxvalue 100 cycle;
creating sequence in descending order
CREATE SEQUENCE sequence_2 start with 100
increment by -1 minvalue 1 maxvalue 100 cycle;
CURRVAL and NEXTVAL
A sequence is a schema object that can generate unique
sequential values. These values are often used for primary and
unique keys. You can refer to sequence values in SQL statements
with these pseudocolumns:
CURRVAL : returns the current value of a sequence.
NEXTVAL : increments the sequence and returns the next value.
Database Management System (DMS) Mr. S. Y. Divekar
Create Sequences :
Example:
use sequence : create a table named students with columns as id
and name.
CREATE TABLE students ( ID number(10), NAME char(20) );
insert values into table using Sequence
INSERT into students VALUES (sequence_1.nextval,'Ramesh');
INSERT into students VALUES (sequence_1.nextval,'Suresh');

Database Management System (DMS) Mr. S. Y. Divekar


ALTER SEQUENCE:
Use the ALTER SEQUENCE statement to change the increment,
minimum and maximum values, cached numbers, and behavior of
an existing sequence. This statement affects only future sequence
numbers.
Syntax:
ALTER SEQUENCE sequence_name
INCREMENT BY increment_value
MINVALUE minimum value
MAXVALUE maximum value
CYCLE|NOCYCLE
CACHE cache_size | NOCACHE
ORDER | NOORDER;

Database Management System (DMS) Mr. S. Y. Divekar


ALTER SEQUENCE:
Example:
This statement sets a new maximum value for the sequence_1
sequence,.
ALTER SEQUENCE sequence_1 MAXVALUE 1500;
This statement turns on CYCLE and CACHE for the
sequence_1 sequence
ALTER SEQUENCE sequence_1
CYCLE
CACHE 5;

Database Management System (DMS) Mr. S. Y. Divekar


DROP SEQUENCE:
The DROP SEQUENCE statement to remove a sequence from the
database.
Syntax:

DROP SEQUENCE sequence_name;

Example:
The following statement drops the sequence sequence_1 .

DROP SEQUENCE sequence_1 ;

Database Management System (DMS) Mr. S. Y. Divekar


Topic:- 3.6 and 3.7 : Outlines
Indexes:
Index Types,
Creating of an Index:
Simple Index,
Unique Index,
 Composite Index,
Dropping Index,

Database Management System (DMS) Mr. S. Y. Divekar


Indexes:
Index is a database object, which can be created on one or more
columns (16 Max column combinations). When creating the index
will read the column(s) and forms a relevant data structure to
minimize the number of data comparisons.
The index will improve the performance of data retrieval and adds
some overhead on data modification such as create, delete and
modify. So it depends on how much data retrieval can be
performed on table versus how much of DML (Insert, Delete and
Update) operations.
Index is basically use for fast data retrieval from database.
Example: For example, if you want to
reference all pages in a book that discuss a
certain topic, you first refer to the index, which
lists all topics alphabetically and are then
referred to one or more specific page numbers.

Database Management System (DMS) Mr. S. Y. Divekar


Types of Indexes:
There are following types of SQL Indexes:
Simple Index:
Simple INDEX create only one selected column of the database
table.
Syntax:
CREATE INDEX index_name ON table_name (column_name);
Example:
CREATE INDEX UI1_EMP ON Employee(Emp_no);

Database Management System (DMS) Mr. S. Y. Divekar


Types of Indexes:
Unique Index:
Defines the index as a unique constraint for the table and
disallows any duplicate values into the indexed column or columns
of the table.
Unique indexes are used not only for performance, but also for
data integrity. A unique index does not allow any duplicate values
to be inserted into the table.
Syntax:
CREATE UNIQUE INDEX index_name ON table_name (column_name);
Example:
CREATE UNIQUE INDEX UI1_EMP ON Employee(Emp_no);

Database Management System (DMS) Mr. S. Y. Divekar


Types of Indexes:
Composite Index:
A composite index is an index on two or more columns of a table.
When two or more columns in single table are related which each
other and used in where condition of select statement then user
should create composite index on the columns which are created.
If all columns selected by in query are in composite index then
oracle will return the values from the index without accessing the
table.

Syntax:
CREATE INDEX index_name ON table_name (column_name1,
column_name2,.. );

Database Management System (DMS) Mr. S. Y. Divekar


Types of Indexes:
Composite Index:
Example:
Select e.Emp_name,d.Dept_name from Employee e ,Deartment
d where e.Empno=d.empno and e.Deptno=d.Deptno;

Suppose we want to do indexing on Employee and Department


table. Here in above example Empno and Deptno are related to
each other. So we can create index on Employee_Num and
Department_Num.

CREATE INDEX CI1_EMP_DEPT ON Employee(Empno,Deptno);

Database Management System (DMS) Mr. S. Y. Divekar


DROP INDEX:
The DROP INDEX statement to remove a INDEX from the
database.
Syntax:

DROP INDEX Index_name;

Example:
The following statement drops the Index Index_1 .

DROP INDEX Index_1 ;

Database Management System (DMS) Mr. S. Y. Divekar


Topic:- 3.8 : Outlines
Synonyms:
Creating Synonyms
Dropping Synonyms

Database Management System (DMS) Mr. S. Y. Divekar


SYNONYM:
A synonym is an alternative name for objects such as tables,
views, sequences, stored procedures, and other database objects.
Synonyms provide both data independence and location
transparency. Synonyms permit applications to function without
modification regardless of which user owns the table or view and
regardless of which database holds the table or view. However,
synonyms are not a substitute for privileges on database objects.
Appropriate privileges must be granted to a user before the user
can use the synonym.

Database Management System (DMS) Mr. S. Y. Divekar


SYNONYM :
Syntax:
CREATE [OR REPLACE] [PUBLIC] SYNONYM [schema1.]synonym FOR [schema2.]object;

[OR REPLACE]: Specify OR REPLACE to re-create the synonym if it already


exists. Use this clause to change the definition of an existing synonym without
first dropping it.
[PUBLIC]: Specify PUBLIC to create a public synonym. Public synonyms are
accessible to all users, but each user must have appropriate privileges on the
underlying object in order to use the synonym. When resolving references to
an object, TimesTen uses a public synonym only if the object is not prefaced by
a schema name.
[schema1.]synonym : Specify the schema to contain the synonym. If you
omit schema1, then TimesTen creates the synonym in your own schema. You
cannot specify a schema for the synonym if you have specified
PUBLIC.synonym is the name of the synonym. The name is limited to 30 bytes.
[schema2.]object: Specify the schema in which the object resides. object is
the name of the object for which you are creating a synonym. If you do not
qualify object with schema2, then the database assumes that the schema
object is in your own schema. schema2 and the object do not need to exist
when the synonym is created.
Database Management System (DMS) Mr. S. Y. Divekar
SYNONYM :
Example:
The schemas oe and sh both contain tables named Employee. In
the next example, user SYSTEM creates a PUBLIC synonym
named Employee for oe.employee:

CREATE PUBLIC SYNONYM Employee FOR oe. Employee;

Database Management System (DMS) Mr. S. Y. Divekar


DROP SYNONYM :
The drop synonym command can be used to drop the synonyms.
Remember to use PUBLIC clause while dropping a public
synonym.
Syntax:

DROP PUBLIC SYNONYM synonyms_name;


DROP SYNONYM synonyms_name;

Example:
DROP PUBLIC SYNONYM Employee;
DROP SYNONYM Emp;

Database Management System (DMS) Mr. S. Y. Divekar


Thanks

Database Management System (DMS) Mr. S. Y. Divekar

You might also like