Advance SQL: SQL Performance Tuning
SQL Views
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.
Views, which are kind 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 such 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.
SQL CREATE VIEW Statement
In SQL, a view is a virtual table based on the result-set of an SQL statement.
A view contains rows and columns, just like a real table. The fields in a view are fields from one
or more real tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if
the data were coming from one single table.
SQL CREATE VIEW Syntax
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
Note: A view always shows up-to-date data! The database engine recreates the data, using the
view's SQL statement, every time a user queries a view.
SQL CREATE VIEW Examples
If you have the Northwind database you can see that it has several views installed by default.
The view "Current Product List" lists all active products (products that are not discontinued)
from the "Products" table. The view is created with the following SQL:
CREATE VIEW [Current Product List] AS
SELECT ProductID,ProductName
FROM Products
WHERE Discontinued=No
We can query the view above as follows:
SELECT * FROM [Current Product List]
Another view in the Northwind sample database selects every product in the "Products" table
with a unit price higher than the average unit price:
CREATE VIEW [Products Above Average Price] AS
SELECT ProductName,UnitPrice
FROM Products
WHERE UnitPrice>(SELECT AVG(UnitPrice) FROM Products)
We can query the view above as follows:
SELECT * FROM [Products Above Average Price]
Another view in the Northwind database calculates the total sale for each category in 1997. Note
that this view selects its data from another view called "Product Sales for 1997":
CREATE VIEW [Category Sales For 1997] AS
SELECT DISTINCT CategoryName,Sum(ProductSales) AS CategorySales
FROM [Product Sales for 1997]
GROUP BY CategoryName
We can query the view above as follows:
SELECT * FROM [Category Sales For 1997]
We can also add a condition to the query. Now we want to see the total sale only for the category
"Beverages":
SELECT * FROM [Category Sales For 1997]
WHERE CategoryName='Beverages'
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.
SQL Updating a View
You can update a view by using the following syntax:
SQL CREATE OR REPLACE VIEW Syntax
CREATE OR REPLACE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
Now we want to add the "Category" column to the "Current Product List" view. We will update
the view with the following SQL:
CREATE OR REPLACE VIEW [Current Product List] AS
SELECT ProductID,ProductName,Category
FROM Products
WHERE Discontinued=No
Updating a View:
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.
All NOT NULL columns from the base table must be included in the view in order for
the INSERT query to function.
SQL > UPDATE CUSTOMERS_VIEW
SET AGE = 35
WHERE name='Ramesh';
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.
Here we can not insert rows in CUSTOMERS_VIEW because we have not included all the
NOT NULL columns in this view, otherwise you can insert rows in a view in similar way as
you insert them in a table.
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 same would reflect
in the view itself. Now, try to query base table, and 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 |
+----+----------+-----+-----------+----------+
SQL Dropping a View
You can delete a view with the DROP VIEW command.
SQL DROP VIEW Syntax
DROP VIEW view_name
Read-Only View
We can create a view with read-only option to restrict access to the view.
Syntax to create a view with Read-Only Access
CREATE or REPLACE force view view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition with read-only
The above syntax will create view for read-only purpose, we cannot Update or Insert data into
read-only view. It will throw an error.
Types of View
There are two types of view,
Simple View
Complex View
Simple View Complex View
Created from one table Created from one or more table
Does not contain functions Contain functions
Does not contain groups of data Contains groups of data
SQL Joins
SQL joins are used to combine rows from two or more tables.
An SQL JOIN clause is used to combine rows from two or more tables, based on a common field
between them.
The most common type of join is: SQL INNER JOIN (simple join). An SQL INNER JOIN
returns all rows from multiple tables where the join condition is met.
Let's look at a selection from the "Orders" table:
OrderID CustomerID OrderDate
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
Then, have a look at a selection from the "Customers" table:
CustomerID CustomerName ContactName Country
1 Alfreds Futterkiste Maria Anders Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Mexico
3 Antonio Moreno Taquería Antonio Moreno Mexico
Example
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;
it will produce something like this:
OrderID CustomerName OrderDate
10308 Ana Trujillo Emparedados y helados 9/18/1996
10365 Antonio Moreno Taquería 11/27/1996
10383 Around the Horn 12/16/1996
10355 Around the Horn 11/15/1996
10278 Berglunds snabbköp 8/12/1996
Different SQL JOINs
Before we continue with examples, we will list the types of the different SQL JOINs you can
use:
INNER JOIN: Returns all rows when there is at least one match in BOTH tables
LEFT JOIN: Return all rows from the left table, and the matched rows from the right
table
RIGHT JOIN: Return all rows from the right table, and the matched rows from the left
table
FULL JOIN: Return all rows when there is a match in ONE of the tables
SQL INNER JOIN Keyword
The INNER JOIN keyword selects all rows from both tables as long as there is a match between
the columns in both tables.
SQL INNER JOIN Syntax
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;
or:
SELECT column_name(s)
FROM table1
JOIN table2
ON table1.column_name=table2.column_name;
PS! INNER JOIN is the same as JOIN.
SQL INNER JOIN Example
The following SQL statement will return all customers with orders:
Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
INNER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
Note: The INNER JOIN keyword selects all rows from both tables as long as there is a match
between the columns. If there are rows in the "Customers" table that do not have matches in
"Orders", these customers will NOT be listed.
SQL LEFT JOIN Keyword
The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in
the right table (table2). The result is NULL in the right side when there is no match.
SQL LEFT JOIN Syntax
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name=table2.column_name;
or:
SELECT column_name(s)
FROM table1
LEFT OUTER JOIN table2
ON table1.column_name=table2.column_name;
PS! In some databases LEFT JOIN is called LEFT OUTER JOIN.
SQL LEFT JOIN Example
The following SQL statement will return all customers, and any orders they might have:
Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
SQL RIGHT JOIN Keyword
The RIGHT JOIN keyword returns all rows from the right table (table2), with the matching rows
in the left table (table1). The result is NULL in the left side when there is no match.
SQL RIGHT JOIN Syntax
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name=table2.column_name;
or:
SELECT column_name(s)
FROM table1
RIGHT OUTER JOIN table2
ON table1.column_name=table2.column_name;
PS! In some databases RIGHT JOIN is called RIGHT OUTER JOIN.
SQL RIGHT JOIN Example
The following SQL statement will return all employees, and any orders they have placed:
Example
SELECT Orders.OrderID, Employees.FirstName
FROM Orders
RIGHT JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID
ORDER BY Orders.OrderID;
SQL FULL OUTER JOIN Keyword
The FULL OUTER JOIN keyword returns all rows from the left table (table1) and from the right
table (table2).
The FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT joins.
SQL FULL OUTER JOIN Syntax
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;
SQL FULL OUTER JOIN Example
The following SQL statement selects all customers, and all orders:
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
SQL Sequence
Sequence is a feature supported by some database systems to produce unique values on demand.
Some DBMS like MySQL supports AUTO_INCREMENT in place of Sequence.
AUTO_INCREMENT is applied on columns, it automatically increments the column value by 1
each time a new record is entered into the table. Sequence is also some what similar to
AUTO_INCREMENT but its has some extra features.
Syntax to create sequences is,
CREATE Sequence sequence-name
start with initial-value
increment by increment-value
maxvalue maximum-value
cycle|nocycle
initial-value specifies the starting value of the Sequence, increment-value is the value by which
sequence will be incremented and maxvalue specifies the maximum value until which sequence
will increment itself.cycle specifies that if the maximum value exceeds the set limit, sequence
will restart its cycle from the begining. No cycle specifies that if sequence exceeds maxvalue an
error will be thrown.
Example to create Sequence
The sequence query is following
CREATE Sequence seq_1
start with 1
increment by 1
maxvalue 999
cycle ;
Example to use Sequence
The class table,
ID NAME
1 abhi
2 adam
4 alex
The sql query will be,
INSERT into class value(seq_1.nextval,'anu');
Result table will look like,
ID NAME
1 abhi
2 adam
4 alex
1 anu
Once you use nextval the sequence will increment even if you don't Insert any record into the
table.
ALTER SEQUENCE
Purpose
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.
Prerequisites
The sequence must be in your own schema, or you must have the ALTER object privilege on the
sequence, or you must have the ALTER ANYSEQUENCE system privilege.
Syntax
alter_sequence::=
Examples
Modifying a Sequence: Examples This statement sets a new maximum value for
the customers_seq sequence, which was created in "Creating a Sequence: Example":
CREATE SEQUENCE customers_seq
START WITH 1000
INCREMENT BY 1
NOCACHE
NOCYCLE;
ALTER SEQUENCE customers_seq
MAXVALUE 1500;
This statement turns on CYCLE and CACHE for the customers_seq sequence:
ALTER SEQUENCE customers_seq
CYCLE
CACHE 5;
Example
CREATE SCHEMA Test ;
GO
CREATE SEQUENCE Test.TestSeq
AS int
START WITH 125
INCREMENT BY 25
MINVALUE 100
MAXVALUE 200
CYCLE
CACHE 3
;
GO
And Alter
ALTER SEQUENCE Test. TestSeq
RESTART WITH 100
INCREMENT BY 50
MINVALUE 50
MAXVALUE 200
NO CYCLE
NO CACHE
;
GO
DROP SEQUENCE
Purpose
Use the DROP SEQUENCE statement to remove a sequence from the database.
Prerequisites
The sequence must be in your own schema or you must have
the DROP ANY SEQUENCE system privilege.
Syntax
drop_sequence::=
Example
DROP SEQUENCE oe.customers_seq;
SQL CREATE INDEX Statement
The CREATE INDEX statement is used to create indexes in tables.
Indexes allow the database application to find data fast; without reading the whole table.
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.
The CREATE INDEX Command:
The basic syntax of CREATE INDEX is as follows:
CREATE INDEX index_name ON table_name;
Single-Column Indexes:
A single-column index is one that is created based on only one table column. The basic syntax
is as follows:
CREATE INDEX index_name
ON table_name (column_name);
Unique Indexes:
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. The basic syntax is as follows:
CREATE UNIQUE INDEX index_name
on table_name (column_name);
Composite Indexes:
A composite index is an index on two or more columns of a table. The basic syntax is as
follows:
CREATE INDEX index_name
on table_name (column1, column2);
Whether to create a single-column index or a composite index, take into consideration the
column(s) that you may use very frequently in a query's WHERE clause as filter conditions.
Should there be only one column used, a single-column index should be the choice. Should
there be two or more columns that are frequently used in the WHERE clause as filters, the
composite index would be the best choice.
Implicit Indexes:
Implicit indexes are indexes that are automatically created by the database server when an
object is created. Indexes are automatically created for primary key constraints and unique
constraints.
The DROP INDEX Command:
An index can be dropped using SQL DROP command. Care should be taken when dropping an
index because performance may be slowed or improved.
The basic syntax is as follows:
DROP INDEX index_name;
You can check INDEX Constraint chapter to see actual examples on Indexes.
When should indexes be avoided?
Although indexes are intended to enhance a database's performance, there are times when they
should be avoided. The following guidelines indicate when the use of an index should be
reconsidered:
Indexes should not be used on small tables.
Tables that have frequent, large batch update or insert operations.
Indexes should not be used on columns that contain a high number of NULL values.
Columns that are frequently manipulated should not be indexed.
Creating Snapshots
You create a snapshot using the SQL command CREATE SNAPSHOT. As when creating tables,
you can specify storage characteristics, extent sizes and allocation, and the tablespace to hold the
snapshot, or a cluster to hold the snapshot (in which case all of the previous options do not
apply). You can also specify how the snapshot is to be refreshed and the distributed query that
defines the snapshot; this is unique to snapshots.
For example, the following CREATE SNAPSHOT statement defines a local snapshot to
replicate the remote EMP table located in NY:
CREATE SNAPSHOT emp_sf
PCTFREE 5 PCTUSED 60
TABLESPACE users
STORAGE (INITIAL 50K NEXT 50K PCTINCREASE 50)
REFRESH FAST
START WITH sysdate
NEXT sysdate + 7
AS SELECT * FROM [email protected];
Whenever you create a snapshot, Oracle immediately fills the base table with the rows returned
by the query that defines the snapshot. Thereafter, the snapshot is refreshed as specified by the
REFRESH clause; see "Refreshing Snapshots"
Creating a Clustered Snapshot
You can create a snapshot in a cluster, just as you can a table. For example, the following
statement creates a snapshot named EMP_DALLAS in the EMP_DEPT cluster:
CREATE SNAPSHOT emp_dallas
...
CLUSTER emp_dept
... ;
You can change a snapshot's storage parameters using the ALTER SNAPSHOT command. For
example, the following command alters the EMP snapshot's PCTFREE parameter:
ALTER SNAPSHOT emp PCTFREE 10;
You cannot change a snapshot's defining query; you must drop the snapshot and then re-create it.
Privileges Required to Alter a Snapshot
To alter a snapshot's storage parameters, the snapshot must be contained in your schema or you
must have the ALTER ANY SNAPSHOT and ALTER ANY TABLE system privileges.
ALTER SNAPSHOT - Examples
The only parts of a snapshot that can be altered are its storage parameters, refresh type and
refresh start, and next interval. The select for the snapshot, base tables, and other data related
items cannot be changed without dropping and recreating the snapshot.
For example, to alter the PCTFREE and PCTUSED of the trial_summary snapshot the following
command would be used:
SQL> ALTER SNAPSHOT trial_summary
1: PCTFREE 10 PCTUSED 80;
snapshot altered
If we wished to change the refresh interval to THURSDAY from FRIDAY at 1900 hours the
command would be:
SQL> ALTER SNAPSHOT trial_summary
1: NEXT NEXT_DAY(SYSDATE, 'THURSDAY') + 19/24;
snapshot altered
To alter the refresh option used by the LOCAL_TRANSACTION snapshot, execute the comand:
ALTER SNAPSHOT local_transaction
COMPLETE;
Dropping Snapshots
You can drop a snapshot independently of its master tables or the snapshot log. To drop a local
snapshot, use the SQL command DROP SNAPSHOT. For example:
DROP SNAPSHOT emp;
If you drop the only snapshot of a master table, you should also drop the snapshot log of the
master table, if there is one.
Privileges Required to Drop a Snapshot
Only the owner of a snapshot or a user with the DROP ANY SNAPSHOT system privilege can
drop a snapshot
ORACLE/PLSQL: SYNONYMS
This Oracle tutorial explains how to create and drop synonyms in Oracle with syntax and
examples.
DESCRIPTION
A synonym is an alternative name for objects such as tables, views, sequences, stored
procedures, and other database objects.
You generally use synonyms when you are granting access to an object from another schema and
you don't want the users to have to worry about knowing which schema owns the object.
CREATE SYNONYM (OR REPLACE)
You may wish to create a synonym so that users do not have to prefix the table name with the
schema name when using the table in a query.
Syntax
The syntax to create a synonym in Oracle is:
CREATE [OR REPLACE] [PUBLIC] SYNONYM [schema .] synonym_name
FOR [schema .] object_name [@ dblink];
OR REPLACE
Allows you to recreate the synonym (if it already exists) without having to issue a DROP
synonym command.
PUBLIC
It means that the synonym is a public synonym and is accessible to all users. Remember
though that the user must first have the appropriate privileges to the object to use the
synonym.
schema
The appropriate schema. If this phrase is omitted, Oracle assumes that you are referring
to your own schema.
object_name
The name of the object for which you are creating the synonym. It can be one of the
following:
table
view
sequence
stored procedure
function
package
materialized view
java class schema object
user-defined object
synonym
Example
Let's look at an example of how to create a synonym in Oracle.
For example:
CREATE PUBLIC SYNONYM suppliers
FOR app.suppliers;
This first CREATE SYNONYM example demonstrates how to create a synonym
called suppliers. Now, users of other schemas can reference the table called suppliers without
having to prefix the table name with the schema named app. For example:
SELECT * FROM suppliers;
If this synonym already existed and you wanted to redefine it, you could always use the OR
REPLACE phrase as follows:
CREATE OR REPLACE PUBLIC SYNONYM suppliers
FOR app.suppliers;
DROP SYNONYM
Once a synonym has been created in Oracle, you might at some point need to drop the synonym.
Syntax
The syntax to drop a synonym in Oracle is:
DROP [PUBLIC] SYNONYM [schema .] synonym_name [force];
PUBLIC
Allows you to drop a public synonym. If you have specified PUBLIC, then you don't
specify a schema.
force
It will force Oracle to drop the synonym even if it has dependencies. It is probably not a
good idea to use force as it can cause invalidation of Oracle objects.
Example
Let's look at an example of how to drop a synonym in Oracle.
For example:
DROP PUBLIC SYNONYM suppliers;
This DROP statement would drop the synonym called suppliers that we defined earlier.