SQL Functions and Performance Tuning Guide
SQL Functions and Performance Tuning Guide
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
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’)
[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 &&
City(Leng
th)
2. Arithmetic/Numeric Function
[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
• 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;
3.2.12 Join - Inner join and Outer join (Q. Explain Inner join and Outer join with example.)
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
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 |
+----------+-----+
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.
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:
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
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.
Syntax
s in Java
SELECT column_name
FROM table_name
WHERE column_name expression operator
( SELECT column_name from table_name WHERE ... );
Example
1 John 20 US 2000.00
4 Alina 29 UK 6500.00
SELECT *
FROM EMPLOYEE
WHERE ID IN (SELECT ID
FROM EMPLOYEE
WHERE SALARY > 4500);
4 Alina 29 UK 6500.00
Syntax:
Example
Now use the following syntax to copy the complete EMPLOYEE table into the EMPLOYEE_BKP table.
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.
1 John 20 US 2000.00
4 Alina 29 UK 1625.00
Syntax
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.
This would impact three rows, and finally, the EMPLOYEE table would have the following records.
1 John 20 US 2000.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
“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.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);
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;
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)
WINTER – 15
GROUP BY Clause