Site icon FahmidasClassroom

Create View in Oracle

P3

View is a virtual table that is created from an existing database table. The way of creating, updating, and deleting view has been shown in this tutorial.

Syntax:

CREATE [OR REPLACE] VIEW view_name AS
SELECT field1, field2, ..., field3
FROM tables
[WHERE conditions];
[WITH READ ONLY]
[WITH CHECK OPTION]

A new view can be created or an existing view can be replaced by a new view by using CREATE or REPLACE statement. The SELECT query of the view can retrieve data from one or more tables with or without the WHERE clause. The ‘WITH READ ONLY’ feature is used in view to create non-updatable view. The ‘WITH CHECK OPTION’ feature is used to prevent the view from updating those fields are not included in the view.

Some examples of creating view in oracle have been shown below.

Example-1: Create a view by using where clause

The following SQL statement will create a simple view from two tables.

CREATE VIEW STD_VIEW AS 
SELECT STD_BASIC.ID, STD_BASIC.NAME, STD_BASIC.BATCH, STD_DEPT.DEPARTMENT
FROM STD_BASIC, STD_DEPT
WHERE STD_BASIC.ID = STD_DEPT.STD_ID;

The following output will appear if the view is created successfully.

The view will contain the following output.

Example-2: Create a view by using inner join

The following SQL statement will create an updatable view from two tables by using inner join.

CREATE or REPLACE VIEW STD_VIEW2 AS 
SELECT STD_BASIC.NAME, STD_BASIC.BATCH, STD_BASIC.SEMESTER, STD_DEPT.DEPARTMENT
FROM STD_BASIC
INNER JOIN STD_DEPT
ON STD_BASIC.ID = STD_DEPT.STD_ID;

The following output will appear if the view is created successfully.

The view will contain the following output.

Example-3: Create a read-only view

The following SQL statement will create a non-updatable view of a table.

CREATE VIEW STD_VIEW3 AS 
SELECT STD_BASIC.ID, STD_BASIC.NAME, STD_BASIC.BATCH, STD_BASIC.SEMESTER 
FROM STD_BASIC 
WITH READ ONLY;

The following output will appear if the view is created successfully.

Example-4: Drop a view

The following SQL statement will drop the existing view.

DROP VIEW STD_VIEW2;

The following output will appear if the view is dropped successfully.

Exercise:

Create two tables named manufacturer (id*, name, address, email) and products (id*, name, price, manufacturer_id). Here, the manufacturer_id is a foreign key of the products table. Create an updatable view that will show the product name, product price, and manufacturer name from two tables.

Exit mobile version