0% found this document useful (0 votes)
15 views23 pages

SQL Functions and Performance Tuning Guide

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

SQL Functions and Performance Tuning Guide

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

CHAPTER 3

Interactive SQL and Advance SQL: SQL Performance Tuning


(14 Marks)
3.1 SQL Functions
 Two Types of SQL Functions
1. Single-row functions
a. Manipulate data items
b. Accept arguments and return one value
c. Act on each row returned
d. Return one result per row
e. May modify the data type
f. Can be nested
Syntax: - function_name (column| expression, [arg1, arg2...])

2. Multiple-row or Group functions

 Single-row functions :- There are four types of single row functions are:
1. String Functions

FUNCTION USE/DEFINITION
INITCAP Capitalizes the first letter of a string of characters
Searches a character string for a character string subset and returns
INSTR the start
position and/or occurrence of the substring
LOWER Returns a character value that is all lower case
UPPER Returns a character value that is all upper case
LTRIM Trims specified characters from the left end of a string
RTRIM Trims specified characters from the right end of a string
LPAD It is used for formatting from left side by using any character.
RPAD It is used for formatting from right side by using any character.
Returns a numeric value equivalent to the number of characters in a
LENGTH string of
characters
Returns a string of specified length from a larger character string
SUBSTR beginning at
a specified character position

Consider following “Person” table

LastName FirstName Address City


Sharma Rajesh GM Road Pune
Keri John CAMP Pune
Kari Johnson RTO Road Banglore
1. INITCAP: - It display the initial letter as capital.
Syntax: - INITCAP (‘String')
Example:- SQL> Select Initcap(city) from Person;

 Result Table:- City


Pune
Pune
Banglore

2. LOWER & UPPER:- Returns a character value that is all lower/ Upper case
Syntax: - Lower (‘String')
Upper (‘String’)
Example:- SQL> Select lower(city) from
Person;
SQL> Select upper (city) from Person;
 Result Table:-

City City
pune PUNE
pune PUNE
banglore BANGLORE

3. Ltrim & Rtrim: - It trims or cuts the character from left or right.
Syntax: - Ltrim(‘String‘,’trim text’)
Rtrim (‘String’, ‘trim text’)

 Example:- SQL> Select Ltrim(‘Pune’, ‘P’) from Person;


SQL> Select Rtrim (‘Pune’, ‘e’) from Person;
 Result
Table:- City City
une pun
une pun
banglore banglore

4. Translate: - It is used to translate the given character from input string.


 Syntax: - Translate (‘main string’ , ‘string to replaced’, ‘ string to be
replaced by’)
 Example:- SQL> Select translate (‘Banglore’, ‘B’ , ‘ M’) from Person;
 Result City
Table:-
pune
pune
Manglore

5. Substr: - It returns the substring from specified position.


 Syntax: - Substr (‘main string’ , position, character to be replaced’)
 Example:- SQL> Select Substr (city, 1, 3) from Person;
o Result Table:-
City(Subs
tr)
Pun
pun
Man

[Link] & RPAD: - It is used for formatting from left & right side by using any
character.
Syntax: - Lpad (‘main string’ , length, character to be padded’)
Rpad (‘main string’, length, character to be padded’)
Example:- SQL> Select Lpad (city, 10, ‘ * ’) from Person;
SQL> Select Rpad (city, 10, ‘& ’) from Person;
 Result table:-

City City
******Pune Pune &&&&&&
******Pune Pune &&&&&&
**Banglore Banglore &&

7. Concatenation: - It is used to concatenate combining two strings.


Syntax: - String || String
 Example:- SQL> Select ( ‘the first name is’ || firstname || ‘ and city is ’ ||
city) from Person;
 Result Table:- the first name is rajesh and city is pune
the first name is john and city is pune
the first name is johnson and city is
banglore

8. Length: - It is used to calculate the length of given string.


Syntax: - length (‘string’)
Example:- SQL> Select length (city) from Person;
 Result Table:-

City(Leng
th)


2. Arithmetic/Numeric Function

Function Description Syntax Example Output


It returns the absolute value
ABS of ‘n’. ABS(-15.36) SQL> Select ABS(- 15.36
(absolute
) 15.36) from dual;
SQL> select power
Power It returns m raised to the nth Power (m, n) (3,2) 6
power. Nth must be an integer ”raised” from dual;
else an error is returned.
Round the value of number x
Round to y round(X, [Y]) SQL> select round 140.23
(140.234, 2) from
(X,Y) decimal places. dual;
SQRT Returns square root of n. sqrt(n) select sqrt(25) from 5
dual;
Returns a greatest value in a
GREATEST list of Greatest select greatest(4,5,17) 17
expressions. (expr1,expr2,e from dual;
xpr3…exprn)
Returns the least value in a select least(4,5,17)
LEAST list of least(expr1,ex from 4
expressions. pr2,…..,exprn) dual;
;
Returns the remainder of a
MOD first mod(m, n) select mod(15,7) from 1
number divided by second dual;
number passed a parameter.

3. Date & Time Functions


• Oracle stores dates in an internal numeric format: century, year,
month, day, hours, minutes, seconds.
• The default date format is DD-MM-YY.
• SYSDATE is a function returning date and time.
• DUAL is a dummy table used to view SYSDATE.

Function Description Return Value

months_between(d1, Used to find number of months between d1


d2) and d2 3
Where, d1 and d2 are
dates Example: Select months_between
(‘05-Sep-1996‘, ‘05-Dec-1996‘) from
dual;
Returns date after adding the number of
add_months (d, n) months 16-Dec-17
Where, d is date, n no
of specified with the function.
Example: Select add_months(‘16-Sep-
months to be added 17’,3) from
dual;
Returns the date of the first weekday named
Next_day ( d, char) char 06-Sep-17
Where d is date, char-
day that is after the date named by date.
Example: Select next_day (‘01-Sep-
of week 2017‘,
‘Wednesday‘) from dual;
Returns the last day of the month that
Last_day (d) contains date 31-Aug-17
Where, d is date d.
Example: Select last_day (‘1-Aug-17’)
from dual

[Link] Function/Aggregate
Functions Q. What is an
aggregate function?
• An aggregate function summarizes the results of an expression over a
number of rows, returning a single value.
• The general syntax for most of the aggregate functions is as follows:
• Syntax:- Aggregate_function ([DISTINCT|ALL] expression)
• Some of the commonly used aggregate functions are :
• SUM
• COUNT Sno Fname Salary Position
• AVG
SL100 John 30000.00 Manager
• MIN
• MAX SL101 Susan 24000.00 Manager
• Consider following table:- SL102 David 12000.00 Project Manager
SL103 Ann 12000.00 Project Manager
SL104 Mary 9000.00 Project Manager

Function Description Output


Avg(column) Returns: The average of the values in a specified column.
Syntax:- SELECT AVG(column_name) FROM table_name
WHERE condition;
Example:-
SQL>Select avg (salary) from staff; 17400
SQL> Select Avg(salary) from staff where position=
‘manager’; 27000
SUM(column
) Returns: The sum of the values in a specified column.
Syntax:- SELECT SUM(column_name) FROM table_name
WHERE condition;
Example:-
SQL>Select sum (salary) from staff; 87000
SQL> Select sum(salary) from staff where position=
‘manager’; 54000
MAX(column
) Returns: MAX () returns the largest value of a column.
Syntax:- SELECT max(column_name) FROM table_name;
Example:-
SQL>Select max (salary) from staff; 30000
MIN(column) Returns: MIN () returns the smallest value of a column.
Syntax:- SELECT min(column_name) FROM table_name;
Example:-
SQL>Select min (salary) from staff; 9000
Count(colum
n) Returns: The number of values in the specified column.
Syntax:- SELECT COUNT(column_name) FROM table_name
WHERE condition;
Example:- SQL>Select count (Sno ) from staff; 5
SQL>SELECT COUNT(Sno) FROM Staff WHERE position = 2
‘Manager’;

3.2.7 Use of GROUP BY Clause

• 1. GROUP BY: It groups the data from the SELECT table and produce a single
summary row for each group
• When Using GROUP BY:
1. Each item in the SELECT list must be single valued per group.
2. SELECT clause may only contain: Columns names, Aggregate function,
Constants, An expression involving combinations of the above.
• Syntax:- SELECT column_name, sum(column_name) FROM table GROUP BY
column_name;
• Consider following Table:-
Turnover(Cr
C_Code Company )
B1 Atlas 9500
B2 Infosys 4500
“Sales”
Table
B3 Wipro 7100
B1 Atlas 2500
B2 Infosys 3500
• Example:- SELECT c_code, company, sum(turnover) FROM sales GROUP BY
company;

Turnover(C
C_Code Company r)
B1 Atlas 12000
Resultant Table
B2 Infosys 8000
B3 Wipro 7100
2. Having Clause
• Having clause was added to SQL because the where keyword could not be
used against aggregate functions (like sum, avg), & without having clause
would be impossible to test for result conditions.
• Syntax:-
SELECT column, sum (column) FROM table GROUP BY column HAVING
sum (column) condition value;
• Example:-
SELECT c_code, company, sum
(turnover)
FROM sales GROUP BY company
HAVING sum (amount)>10000;

Turnover(Cr Resultant Table


C_Code Company )
B1 Atlas 12000
3. Order BY Clause
• The ORDER BY clause is used in a SELECT statement to sort results
either in ascending or descending order.
• Oracle sorts query results in ascending order by default.
• Syntax:-
SELECT column-list
FROM table_name [WHERE condition]
[ORDER BY column1 [, column2... column] [DESC/ASC]];
• For Example: If you want to sort the staff table by salary of the staff. The
SQL query would be.
• SQL> SELECT name, salary
Fnam
FROM staff e Salary
ORDER BY salary; Mary 9000.00
David 12000.00 Resultant Table
Ann 12000.00
Susan 24000.00
John 30000.00
Fname Salary
• SQL> SELECT name,
salary John 30000.00
FROM Staff Susan 24000.00
ORDER BY name, salary DESC; David 12000.00
Ann 12000.00
Resultant Table Mary 9000.00

3.2.12 Join - Inner join and Outer join (Q. Explain Inner join and Outer join with example.)

 INNER Join: This is a simple JOIN in which the result is based on


matched data as per the condition specified in the query.
 Inner Join Syntax :
SELECT column_name_list FROM table_name1
INNER JOIN
table_name2 ON table_name1.column_name = table_name2.column_name;
 Inner Join Example :
SELECT * FROM emp INNER JOIN dept ON [Link] = [Link];

 Outer Join is based on both matched and unmatched data.


Outer Joins subdivide further into,
• Left Outer Join
• Right Outer Join
• Full Outer Join

1. Left Outer Join


The left outer join returns a result table with the matched data
of two tables then remaining rows of the left table and null for
the right table's column.
o Left Outer Join syntax :
SELECT column-name-list FROM table-name1 LEFT OUTER
JOIN table-name2 ON [Link]-name = table-
[Link]-name;

o Left Outer Join Example:

SELECT * FROM emp LEFT OUTER JOIN dept ON ([Link]=[Link]);

2. Right Outer Join


o The right outer join returns a result table with the matched data of two
tables then
remaining rows of the right table and null for the left table's columns.
o Right Outer Join Syntax:
SELECT column-name-list FROM table-name1 RIGHT OUTER JOIN
table-name2
ON [Link]-name = [Link]-name;
o Right Outer Join Example:
SELECT * FROM emp RIGHT OUTER JOIN dept ON ([Link]=[Link])
3. Full Outer Join
o The full outer join returns a result table with the matched data of two table
then remaining
rows of both left table and then the right table.
o Full Outer Join Syntax :
SELECT column-name-list FROM table-name1 FULL OUTER JOIN
table-name2
ON [Link]-name = [Link]-name;
o Full Outer Join Example:
SELECT empname, sal FROM emp FULL OUTER JOIN dept ON [Link]
= [Link];

4.1 VIEW

 View: Views are virtual relations mainly used for security purpose, and can be provided on
request by a particular user.
 View is a logical copy of physical table.
 A view can contain all rows of a table or selected 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.
 Views are created for security reasons. Instead of coping same table multiple times for different
requirements, views can be created.
v
 It doesn’t exist physically. With the help of view, we can give restricted access to users. When
view is used, underlying table is invisible, thus increasing security. Views can be used to see,
insert, update and delete data from base table.
 SQL CREATE VIEW
Syntax
CREATE VIEW view_name
AS SELECT column_name(s)
FROM table_name
WHERE condition;
Where,
view_name – is the name of view.
SELECT statement- is used to define the columns & rows that you want to display in the view.

Example

Consider the CUSTOMERS table having the following records −


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | 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 |
+----+----------+-----+-----------+----------+

Following is an example to create a view from the CUSTOMERS table. This view would be used to
have customer name and age from the CUSTOMERS table.
SQL > CREATE VIEW CUSTOMERS_VIEW AS
SELECT name, age
FROM CUSTOMERS;
Now, you can query CUSTOMERS_VIEW in a similar way as you query an actual table. Following is
an example for the same.
SQL > 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 |
+----------+-----+

4.1.1 WITH CHECK OPTION

 The WITH CHECK OPTION is a CREATE VIEW statement option. The purpose of the WITH
CHECK OPTION is to ensure that all UPDATE and INSERTs satisfy the condition(s) in the view
definition.
 If they do not satisfy the condition(s), the UPDATE or INSERT returns an error.
 The following is an example of creating same view CUSTOMERS_VIEW with 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.

4.1.2 UPDATING A VIEWS

A view can be updated under certain conditions:


 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.
So if a view satisfies all the above mentioned rules then you can update a view.

You can update a view by using the following syntax:

SQL> 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.
Now, try to query the base table and 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 |
+----+----------+-----+-----------+----------+
You can also update a view by using the following syntax:

CREATE OR REPLACE VIEW view_name AS SELECT column_name(s) FROM


table_name WHERE condition;

Ex. CREATE OR REPLACE VIEW [Current Product List] AS SELECT ProductID,


ProductName, Category FROM Products WHERE Discontinued=No

4.1.3 Inserting Rows into a View:


Rows of data can be inserted into a view. The same rules that apply to the UPDATE command
also apply to the INSERT command.

4.1.4 Deleting Rows into a View:


Rows of data can be deleted from a view. The same rules that apply to the UPDATE and INSERT
commands apply to the DELETE command.
Following is an example to delete a record having AGE= 22.
SQL > 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. Now, try to query the base table and 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

4.1.5 SQL Dropping a View

You can delete a view with the DROP VIEW command.


SQL DROP VIEW
Syntax SQL> DROP VIEW view_name;

4.1.6 SQL Joins

 SQL joins are used to combine rows


from two or more tables. “Customers ” Table
CustomerI C_Nam ContactNam
 An SQL JOIN clause is used to Country
D e e
combine rows from two or more
1 Alfred Maria Germany
tables, based on a common field
between them. 2 Ana Ana Mexico
3 Antonio Antonio Mexico
“Order” Table
Order CustomerI
OrderDate
ID D
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20

Example
 SELECT [Link], Customers.C_Name, [Link] FROM Orders
INNER JOIN Customers ON Orders.C_ID=Customers.C_ID;
 The Resultant table is:-

“Order” Table
OrderID C_Name OrderDate
10308 Ana 1996-09-18

SQL Sub Query


A Subquery is a query within another SQL query and embedded within the WHERE clause.

Important Rule:

o A subquery can be placed in a number of SQL clauses like WHERE clause, FROM clause, HAVING
clause.
o You can use Subquery with SELECT, UPDATE, INSERT, DELETE statements along with the operators
like =, <, >, >=, <=, IN, BETWEEN, etc.
o A subquery is a query within another query. The outer query is known as the main query, and the
inner query is known as a subquery.
o Subqueries are on the right side of the comparison operator.
o A subquery is enclosed in parentheses.
o In the Subquery, ORDER BY command cannot be used. But GROUP BY command can be used to
perform the same function as ORDER BY command.

1. Subqueries with the Select Statement


SQL subqueries are most frequently used with the Select statement.

Syntax

s in Java
SELECT column_name
FROM table_name
WHERE column_name expression operator
( SELECT column_name from table_name WHERE ... );

Example

Consider the EMPLOYEE table have the following records:


ID NAME AGE ADDRESS SALARY

1 John 20 US 2000.00

2 Stephan 26 Dubai 1500.00

3 David 27 Bangkok 2000.00

4 Alina 29 UK 6500.00

5 Kathrin 34 Bangalore 8500.00

6 Harry 42 China 4500.00

7 Jackson 25 Mizoram 10000.00

The subquery with a SELECT statement will be:

SELECT *
FROM EMPLOYEE
WHERE ID IN (SELECT ID
FROM EMPLOYEE
WHERE SALARY > 4500);

This would produce the following result:

ID NAME AGE ADDRESS SALARY

4 Alina 29 UK 6500.00

5 Kathrin 34 Bangalore 8500.00

7 Jackson 25 Mizoram 10000.00

2. Subqueries with the INSERT Statement


o SQL subquery can also be used with the Insert statement. In the insert statement, data returned from
the subquery is used to insert into another table.
o In the subquery, the selected data can be modified with any of the character, date functions.

Syntax:

INSERT INTO table_name (column1, column2, column3....)


SELECT *
FROM table_name
WHERE VALUE OPERATOR

Example

Consider a table EMPLOYEE_BKP with similar as EMPLOYEE.

Now use the following syntax to copy the complete EMPLOYEE table into the EMPLOYEE_BKP table.

INSERT INTO EMPLOYEE_BKP


SELECT * FROM EMPLOYEE
WHERE ID IN (SELECT ID
FROM EMPLOYEE);

3. Subqueries with the UPDATE Statement


The subquery of SQL can be used in conjunction with the Update statement. When a subquery is used with the
Update statement, then either single or multiple columns in a table can be updated.

Syntax

UPDATE table
SET column_name = new_value
WHERE VALUE OPERATOR
(SELECT COLUMN_NAME
FROM TABLE_NAME
WHERE condition);

Example

Let's assume we have an EMPLOYEE_BKP table available which is backup of EMPLOYEE table. The given example
updates the SALARY by .25 times in the EMPLOYEE table for all employee whose AGE is greater than or equal to
29.

UPDATE EMPLOYEE
SET SALARY = SALARY * 0.25
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 29);

This would impact three rows, and finally, the EMPLOYEE table would have the following records.

ID NAME AGE ADDRESS SALARY

1 John 20 US 2000.00

2 Stephan 26 Dubai 1500.00

3 David 27 Bangkok 2000.00

4 Alina 29 UK 1625.00

5 Kathrin 34 Bangalore 2125.00

6 Harry 42 China 1125.00

7 Jackson 25 Mizoram 10000.00

4. Subqueries with the DELETE Statement


The subquery of SQL can be used in conjunction with the Delete statement just like any other statements
mentioned above.

Syntax

DELETE FROM TABLE_NAME


WHERE VALUE OPERATOR
(SELECT COLUMN_NAME
FROM TABLE_NAME
WHERE condition);

Example

Let's assume we have an EMPLOYEE_BKP table available which is backup of EMPLOYEE table. The given example
deletes the records from the EMPLOYEE table for all EMPLOYEE whose AGE is greater than or equal to 29.

DELETE FROM EMPLOYEE


WHERE AGE IN (SELECT AGE FROM EMPLOYEE_BKP
WHERE AGE >= 29 );

This would impact three rows, and finally, the EMPLOYEE table would have the following records.

ID NAME AGE ADDRESS SALARY

1 John 20 US 2000.00

2 Stephan 26 Dubai 1500.00

3 David 27 Bangkok 2000.00

7 Jackson 25 Mizoram 10000.00

4.2 SEQUENCES

* Definition:- A sequence refers to a database object that is capable of generating unique and
sequential integer values.
* Syntax:
o CREATE SEQUENCE <seq_name> [Start with num]
[Increment by num]
[Maxvalue num]
[Minvalue num]
[Cycle/nocycle]
[Cache num/nocache];
Where,
* Increment by num: Used to specify the interval between sequence numbers.
* Start with num: States the first sequence numbers that needs to be generated.
* Minvalue num: This is used to state the minimum value of the sequence.
* Maxvalue num: It states the maximum value generated by sequence.
* Cycle: Cycle indicates that the sequence will be continued for generating the values from the
starting after reaching either its maximum value or minimum value.
* Cache: The cache option is used to pre-allocate a set of sequence numbers and keep these
numbers in the memory so that they can be accessed.
* No Cache: This states that there is no pre-allocation for the values of sequence.
* Example 1:-
* SQL> CREATE SEQUENCE student_seq START with 1 INCREMENT by 1
MAXVALUE 60 nocycle;
* SQL> Sequence Created.
* On execution, oracle will create a sequence student_seq. its start with 1, incrementing the
sequence number by 1. Maximum value that it can generate is 60.
* Referencing a sequence: it is referenced in SQL statement with the NEXTVAL & CURRVAL;
* Ex.2:- CREATE
Sequence seq_1 Start
with 1
Increment by 1
Maxvalue 999 Cycle;
* Suppose consider “info” table

“Info” Table
ID Name
1 John
2 Smith
3 Hari

* The SQL query will be,


* SQL> INSERT into info values(seq_1.nextval, ‘Anu');
* Result table will look like,

“Info” Table
ID Name
1 John
2 Smith
3 Hari
1 Anu

* Once you use nextval the sequence will increment even if you don't insert any record into the
table.
* SQL> Select seq_1.currval from info;

4.2.1 Altering Sequences


* 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.
* Alter sequence <seq_name>
 [Start with num]
 [Increment by num]
 [Maxvalue num] [Minvalue num]
 [Cycle/nocycle]
 [Cache num/no-cache];
* Ex.:-SQL> Alter sequence seq_1 maxvalue 1500;
* SQL> Alter sequence seq_1 cycle cache 10; (This statement turns on cycle & cache for
the seq_1 sequence.)
4.2.2 Dropping Sequences
* Use the DROP SEQUENCE statement to remove a sequence from the database.
* The sequence must be in your own schema or you must have the DROP ANY
SEQUENCE system privilege.
* Syntax:
* SQL> Drop sequence sequence_name;
* Ex.:-
* SQL> Drop sequence Info;

4.3 INDEXES
An index can be created in a table to find data more quickly and efficiently.
The users cannot see the indexes, they are just used to speed up searches/queries.
An index provides direct and fast access to rows in a table. Indexes are created explicitly Or
automatically.
Syntax of CREATE INDEX
CREATE INDEX index_name ON table_name;
 Simple index (Single column): An index created on single column of a table is called a Simple
Index.
Syntax: - CREATE INDEX index_name ON table_name (column_name);
Ex. SQL> CREATE INDEX emp_ind ON EMP (empid);

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

Ex: - CREATE UNIQUE INDEX emp_ind ON EMP (empid);


 Composite (concatenated): Indexes that contain two or more columns from the same table
which are useful for enforcing uniqueness in a table column where there’s no single column that
can uniquely identify a row.
Syntax;- CREATE INDEX index_name ON table_name (column1, column2);
Ex.:- CREATE INDEX emp_ind ON EMP (empid, Dept_name);
Indexing with neat diagram
4.3.2 Indexes

* The DROP INDEX


* An index can be dropped using SQL DROP command.
* Syntax:-
* DROP INDEX index_name;
* Ex.:- DROP INDEX emp_ind;

4.4 SYNONYMS
* Use the create synonyms statement to create a synonyms, which is an alternative name for a table.
* It can provide a level of security by masking the name & owner of an object & by providing
location transparency for remote objects of a distributed database.
* You can create both public & private synonyms.

* A public synonym is owned by special user group named PUBLIC & is accessible to every user in
a database.
* A Private synonym is contained of specific user only.
4.5.1 Creating Synonyms:-
Syntax:-
CREATE SYNONYM Synonym_Name FOR table_name;
Example:-
SQL> CREATE SYNONYM Emp FOR Employee;
SQL> Synonym created.
SQL> SELECT * FROM Emp;

4.5.2 Dropping Synonyms :-


* If a synonym is no longer required, you can drop the sequence using the DROP SYNONYM
statement.
* Syntax:-
o DROP SYNONYM Synonym_Name;
o Example:-
SQL> CREATE SYNONYM Emp;
SQL> SYNONYM created.
SUMMER-16

 What are sequence? Why it is used? Create sequence for STUDENT table. (Definition - 1 mark;
Use - 1 mark; creating valid sequence example/pattern - 2 marks)
 What are views? Give its syntax and explain its advantages. (Views - 2 marks; Syntax - 1 mark;
Advantages (Any two) - 1 mark)
 What is index? Explain types of index. (Index Definition - 2 marks; Any Two Types - 1 mark each)
 What are snapshots? Give its uses. How to create a snapshot?(Definition - 1 mark; any one Use -
1 mark, Syntax/Example - 2 marks)

WINTER– 16
6. What is view?
7. Explain the following terms with syntax and example.
←Creating snapshot
← Altering snapshot
← Dropping a snapshot.

WINTER – 15
 Explain sequences with example. (Definition of sequence - 1 Mark, syntax – 2 Marks, Example -
1 Mark)
 Explain views with example.(Explanation of view with syntax – 3 Marks, Example - 1 Mark)
 Explain snapshot with example. (Explanation of snapshot – 3 Marks, example – 1 Mark)
 Explain the concept of indexing with neat diagram. (Explanation - 3 Marks, Any relevant
Diagram - 1 Mark)
Example: - (On Select Query)

1. Consider the following database: Employee (emp_id, emp_name, emp_city,


emp_addr, emp_dept, join_date) Solve the following query:
i) Display the names of employees in capital letters.
ii) Display the emp_id of employee who live in city Pune and Mumbai.
iii) Display the details of employees whose joining date is after ‘01-Apr.-1997’.
iv) Display the total number of employees whose [Link] ‘10’. (Each correct query - 1
mark)
Ans:- i) Select upper(emp_name) from Employee;
ii) Select emp_id from Employee where emp_city = ‘Pune‘or emp_city =
‗Mumbai‘; iii) Select * from Employee where join_date>‗01-Apr-1997‘;
iv) Select count (emp_id) from Employee where emp_dept = 10;

2. Consider the structure for book table as Book_master


{book_id, book_name, subcode, author, no_of_copies, price}.
Write SQL queries for the following:
i) Display total no. of book for subject ‘DBM’.
ii) Get authorwise list of all books.
iii) Display all books whose prices are between Rs. 200 and
Rs.500 Ans: - i. Select sum (no_of_copies) from Book_master
where book_name=‘DBM‘;
ii. Select author, book_name From Book_master Order by author;
iii. Select book_id From Book_master Where price between 200 and 500;
OR
iii. Select book_id From Book_master Where price >= 200 and price <=
500;

SUMMER-16 (38 Marks)

3. Draw the state diagram of transaction.


4. Explain the steps used in query processing with suitable diagram.
(Diagram - 2 marks; Explanation - 2 marks)
5. Explain ACID properties of transaction. (Four ACID properties - 1 mark
each)
6. Describe Commit and Rollback with syntax. (For each command
explanation - 1 mark; syntax - 1 mark)
7. Consider the following database:
Employee (emp_id, emp_name, emp_city, emp_addr, emp_dept, join_date)
Solve the following query:
i) Display the names of employees in capital letters.
ii) Display the emp_id of employee who live in city Pune and Mumbai.
iii) Display the details of employees whose joining date is after ‘01-Apr.-1997’.
iv) Display the total number of employees whose [Link] ‘10’. (Each correct
query - 1 mark)
8. Describe Grant and Revoke commands. (Description of Grant - 2 marks;
Revoke - 2 marks)
9. Describe string function, date and time function. (Any two String
Function - 2 marks; any two Date and Time Function - 2 marks)
10. Explain with example group by and having clause. (For each clause
- Explanation - 1 mark, syntax/example - 1 mark)
11. List and explain any 4 arithmetic operators in SQL with example. (For
each - 1 mark)
12. Consider the structure for book table as Book_master {book_id,
book_name, subcode, author, no_of_copies, price}. Write SQL queries for
the following:
i) Display total no. of book for subject ‘DBM’.
ii) Get authorwise list of all books.
iii) Display all books whose prices are between Rs. 200 and Rs.500
WINTER– 16

1. List four DDL commands.


2. List DCL commands any four.
3. Explain DELETE and DROP Command with syntax and example.
4. Consider the following database Employee (emp-id, emp-name, emp-city,
empaddr, emp-dept, join-date)
i) Display the emp-id of employee who live in city Pune or Nagpur.
ii) Display the details of employee whose joining date is after 02-July-2007.
iii) Change employee name ‘Ajit’ to ‘Aarav’.
iv) Display the total number of employees whose dept is ‘50’.
5. Give the syntax and example of CREATE and RENAME Commands.
6. Explain ALTER command with any two options.
7. Describe ACID properties of transaction.
8. Explain any four string functions with example.
9. Consider the following database schema: EMP (Empno, Ename, job,
mgr, joindate, salary, comm., deptno). Write the SQL queries for the
following:
i) Write a query to find list of employees whose salary is not less 5000.
ii) Write a query to find list of employees whose job title is either “Manager” or
“Analyst”.
iii) Change the location of deptno 40 to Pune from Chandrapur.
iv) Display the Ename and salary of employees who earn more than Rs.
50,000 and are in deptno
10 or 30.
10. Give the use of grant and revoke command with syntax and example.
11. Explain Inner join and Outer join with example.

WINTER – 15

1. Explain the use of truncate statement. Give example.


2. Consider the structure of student (Name, Mark, Age, Place, Phone, Birthdate).
Write SQL quries for the following:
i. To list name of student who do not have phone number
ii. To list students from Mumbai and Pune.
iii. To change mark of ‘Ajay’ to 88 instead of 80.
iv. To list the students whose age is more than 12. (Correct query – 1 Mark
each)
3. Describe how to delete the data from table with an example. (Description -
2 Marks; Syntax - 1 Mark; Example - 1 Mark)
4. Explain the set operator with help of example. (Each operator - 1 Mark)
5. Explain on delete cascade clause with suitable example. (Explanation - 2
Marks, Example – 2 Marks)
6. Explain any four date function with example. (Any four functions -1 Mark
Each)
7. Explain ACID properties of transaction. (Each property – 1 Mark)

GROUP BY Clause

You might also like