CH-3 Interactive SQL and Advanced SQL - SQL Performance Tuning
CH-3 Interactive SQL and Advanced SQL - SQL Performance Tuning
INSTR Searches a character string for a character string subset and returns the start
position and/or occurrence of the substring
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.
SUBSTR Returns a string of specified length from a larger character string beginning at
a specified character position
Consider following “Person” table
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 Table:-
City
pune
pune
Manglore
Result Table:-
City(Substr)
Pun
pun
Man
6. LPAD & 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 &&
Result Table:-
the first name is rajesh and city is pune
ABS It returns the absolute value of ‘n’. ABS(-15.36) SQL> Select ABS(- 15.36
(absolute) 15.36) from dual;
Power It returns m raised to the nth Power (m, n) SQL> select power (3,2) 6
power. Nth must be an integer ”raised” from dual;
else an error is returned.
Round Round the value of number x to y round(X, [Y]) SQL> select round 140.23
(X,Y) decimal places. (140.234, 2) from dual;
SQRT Returns square root of n. sqrt(n) select sqrt(25) from 5
dual;
GREATEST Returns a greatest value in a list of Greatest select greatest(4,5,17) 17
expressions. (expr1,expr2,e from dual;
xpr3…exprn)
LEAST Returns the least value in a list of least(expr1,ex select least(4,5,17) from 4
expressions. pr2,…..,exprn) dual;
;
MOD Returns the remainder of a first mod(m, n) select mod(15,7) from 1
number divided by second dual;
number passed a parameter.
• 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.
• 1. GROUP BY: It helps to arrange similar data into groups. It is also used with SQL functions to
group the result from one or more tables.
• Syntax:- SELECT column_name, sum(column_name) FROM table GROUP BY column_name;
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
B1 Atlas 12000
3.3.3 ORDER BY CLAUSE
Q. Explain order by clause with suitable example.(4M)
• ORDER BY clause is used to display a selected set of fields from a relation in an ordered
approach (desc/asc) base on some field.
• 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.
• SQL> SELECT name, salary FROM staff ORDER BY salary;
Fname Salary
Mary 9000.00
David 12000.00
Resultant Table
Ann 12000.00
Susan 24000.00
John 30000.00
Fname Salary
Ann 12000.00
emp dept
Eno Ename Salary Deptno Deptno Deptname Location
1 Ajay 7000 10 10 100 Pune
2 Amar 8000 10 20 102 Mumbai
3 Neeta 5000 20 30 103 Nagpur
4 Karan 6000 40
INNER JOIN:
INNER JOIN is also referred to as an EQUIJOIN. The INNER JOIN displays records that
have similar values in both tables.
This is a simple JOIN in which the result is based on matched data as per the condition
specified in the query.
OUTER JOIN:
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 JOIN keyword returns all records from the left table (table-I), and the matched records
from the right table (table-2). The result is NULL from the right side, if there is no match.
In SQL, the CROSS JOIN is used to combine each row of the first table with each row of the second table. It
is also known as the Cartesian join since it returns the Cartesian product of the sets of rows from the joined
tables.
Syntax:
SELECT [column names] FROM [Table1] CROSS JOIN [Table2]
Example:
SELECT * FROM emp1 CROSS JOIN dept1;
5. Self-join
•A self join is a join in which a table is joined with itself.
•The self join can be viewed as a join of two copies of the same table.
•The syntax of the command for joining a table to itself is almost same as that for joining two different
tables.
•To distinguish the column names from one another, aliases for the actual the table name are used, since both
the tables have the same name.
•Syntax:
SELECT a.column_name, b.column_name...
FROM table1 a, table1 b
WHERE a.common_filed= b.common_field;
Example:
SELECT E.Name as Employee, M.Name as Manager FROM Employee E LEFT JOIN Employee M ON
E.ManagerId = M.EmployeeId
OUTPUT-
SUB QUERIES
Q. Explain Sub-query concept with example.(4M)
• A Subquery or Inner query or Nested query is a query within another SQL query and embedded
within the WHERE clause.
• 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.
• An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY.
• The GROUP BY can be used to perform the same function as the ORDER BY in a subquery.
• Example:
• Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table. Now to copy
complete CUSTOMERS table into CUSTOMERS_BKP, following is the
• Syntax:
SQL> INSERT INTO CUSTOMERS_BKP
SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID FROM CUSTOMERS) ;
3.4 VIEW
Q. What are views? Give its syntax and explain its advantages. (Views - 2 marks; Syntax - 1 mark;
Advantages (Any two) - 1 mark)
Q. Explain views with example. (Explanation of view with syntax – 3 Marks, Example - 1 Mark)
View can be a virtual table which derived its data from one or more than one table. View can be created
using tables of same database or different database.
View is a logical copy of physical table.
It is used for security purposes because they provide encapsulation of the name of the table. Data is in the
virtual table, not stored permanently. It displays only selected data. A view provides several benefits.
o Views can hide complexity.
o Views can be used as a security mechanism.
o Views can simplify supporting legacy code.
o Define view with its features.
o Differentiate between table & view.
3.4.1 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.
+----+----------+-----+-----------+----------+
| 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_VIEW1 AS SELECT * FROM CUSTOMERS;
SQL > SELECT * FROM CUSTOMERS_VIEW1;
This would produce the following result.
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
SQL > CREATE VIEW CUSTOMERS_VIEW2 AS SELECT name, age FROM CUSTOMERS;
SQL > SELECT * FROM CUSTOMERS_VIEW2;
This would produce the following result.
+----------+-----+
| name | age |
+----------+-----+
| Ramesh | 32 |
| Khilan | 25 |
| kaushik | 23 |
| Chaitali | 25 |
| Hardik | 27 |
| Komal | 22 |
| Muffy | 24 |
+----------+-----+
SQL > CREATE VIEW CUSTOMERS_VIEW3 AS SELECT name, age FROM CUSTOMERS
WHERE age>25;
SQL > SELECT * FROM CUSTOMERS_VIEW3;
This would produce the following result.
+----------+-----+
| name | age |
+----------+-----+
| Ramesh | 32 |
| Hardik | 27 |
+----------+-----+
3.4.2 UPDATING A VIEWS
Syntax:
UPDATE view_name SET Col_name=New_value WHERE Condition;
Example:
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 |
+----+----------+-----+-----------+----------+
3.4.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.
DATABASE OBJECT
Index, Sequence and Synonym are database object.
3.5 SEQUENCES
Q. 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)
Q. Explain sequences with example. (Definition of sequence - 1 Mark, syntax – 2 Marks, Example - 1
Mark)
A sequence is a set of integers 1, 2, 3, 4 that are generated in order on demand.
Sequences are commonly used in databases because many applications require each row
in a table to contain a unique value and sequences provide an easy way to generate them.
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,
o Increment by num: Used to specify the interval between sequence numbers.
o Start with num: States the first sequence numbers that needs to be generated.
o Minvalue num: This is used to state the minimum value of the sequence.
o Maxvalue num: It states the maximum value generated by sequence.
o 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.
o 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.
o 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;
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);
3.7 SYNONYMS
Q. What are Synonyms? Write a syntax for creating a synonym.(4M)
Q. What are Synonyms? How to create and drop synonym?(4M)
A synonym is an alternative name for objects such as tables, views, sequences, stored procedures, and
other database objects. DML operation performed on synonym will affect the table. The main functionality
of synonym is to access the database objects between different schemas without using the schema names.
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.
3.8.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;