0% found this document useful (0 votes)
3 views17 pages

Unit 2 SQL

The document explains the concept of views in SQL, detailing how they function as virtual tables that can be created from one or more real tables, along with their syntax for creation and deletion. It also covers the advantages of using views, such as security, query simplicity, and data integrity, as well as the structure of PL/SQL blocks and examples of PL/SQL programming. Additionally, it discusses limitations of DML statements on views and introduces materialized views as a performance optimization technique.

Uploaded by

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

Unit 2 SQL

The document explains the concept of views in SQL, detailing how they function as virtual tables that can be created from one or more real tables, along with their syntax for creation and deletion. It also covers the advantages of using views, such as security, query simplicity, and data integrity, as well as the structure of PL/SQL blocks and examples of PL/SQL programming. Additionally, it discusses limitations of DML statements on views and introduces materialized views as a performance optimization technique.

Uploaded by

Jacob Davies
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

 What is view ? Write a Syntax to create a view.

Explain different types of


view.
 What is view ? What are the objectives of creating the view ? Give the
syntax for dropping the view.

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.

Views in SQL are kind of virtual tables. A view also has rows and columns as they
are in a real table in the database.

We can create a view by selecting fields from one or more tables present in the
database. A View can either have all the rows of a table or specific rows based on
certain condition.

Views are used for security purpose in databases, views restricts the user
from viewing certain column and rows means by using view we can apply the
restriction on accessing the particular rows and columns for specific user. Views
display only those data which are mentioned in the query, so it shows only data
which is returned by the query that is defined at the time of creation of the View.

CREATING VIEWS
We can create View using CREATE VIEW statement. A View can be created
from a single table or multiple tables.
Syntax:
CREATE VIEW view_name AS SELECT column1, column2..... FROM
table_name WHERE condition;
view_name: Name for the View
table_name: Name of the table
condition: Condition to select rows
Examples:
Creating View from a single table:
In this example we will create a View named DetailsView from the table
StudentDetails.
Query:
CREATE VIEW DetailsView AS SELECT NAME, ADDRESS FROM
StudentDetails WHERE S_ID < 5;
To see the data in the View, we can query the view in the same manner as we
query a table.
SELECT * FROM DetailsView;
Output:

 In this example, we will create a view named StudentNames from the table
StudentDetails.
Query:
CREATE VIEW StudentNames AS SELECT S_ID, NAME FROM
StudentDetails ORDER BY NAME;
 If we now query the view as,
SELECT * FROM StudentNames;
Output:

 Creating View from multiple tables: In this example we will create a View
named MarksView from two tables StudentDetails and StudentMarks. To create
a View from multiple tables we can simply include multiple tables in the
SELECT statement.
Query:
CREATE VIEW MarksView AS SELECT StudentDetails.NAME,
StudentDetails.ADDRESS, StudentMarks.MARKS FROM StudentDetails,
StudentMarks WHERE StudentDetails.NAME = StudentMarks.NAME;
 To display data of View MarksView:
SELECT * FROM MarksView;
 Output:

 Give the syntax for dropping the view.

DELETING VIEWS
we will want to delete it. SQL allows us to delete an existing View. We can delete
or drop a View using the DROP statement.
Syntax:
DROP VIEW view_name;
view_name: Name of the View which we want to delete.
For example, if we want to delete the View MarksView, we can do this as:
DROP VIEW MarksView;

UPDATING VIEWS
There are certain conditions needed to be satisfied to update a view. If any one of
these conditions is not met, then we will not be allowed to update the view.
1. The SELECT statement which is used to create the view should not include
GROUP BY clause or ORDER BY clause.
2. The SELECT statement should not have the DISTINCT keyword.
3. The View should have all NOT NULL values.
4. The view should not be created using nested queries or complex queries.
5. The view should be created from a single table. If the view is created using
multiple tables then we will not be allowed to update the view.
6. We can use the CREATE OR REPLACE VIEW statement to add or remove
fields from a view.
Syntax:
CREATE OR REPLACE VIEW view_name AS
SELECT column1,column2,..
FROM table_name
WHERE condition;
 For example, if we want to update the view MarksView and add the field AGE
to this View from StudentMarks Table, we can do this as:
CREATE OR REPLACE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS,
StudentMarks.MARKS, StudentMarks.AGE
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
 If we fetch all the data from MarksView now as:
SELECT * FROM MarksView;

Output:

Inserting a row in a view: We can insert a row in a View in a same way as we do


in a table. We can use the INSERT INTO statement of SQL to insert a row in a
View.
Syntax:
INSERT INTO view_name(column1, column2 , column3,..)
VALUES(value1, value2, value3..);
view_name: Name of the View
Example: In the below example we will insert a new row in the View DetailsView
which we have created above in the example of “creating views from a single
table”.
INSERT INTO DetailsView(NAME, ADDRESS)
VALUES("Suresh","Gurgaon");
 If we fetch all the data from DetailsView now as,
SELECT * FROM DetailsView;
Output:

Deleting a row from a View: Deleting rows from a view is also as simple as
deleting rows from a table. We can use the DELETE statement of SQL to delete
rows from a view. Also deleting a row from a view first delete the row from the
actual table and the change is then reflected in the view.
Syntax:
DELETE FROM view_name
WHERE condition;
view_name:Name of view from where we want to delete rows
condition: Condition to select rows
Example: In this example, we will delete the last row from the view DetailsView
which we just added in the above example of inserting rows.
DELETE FROM DetailsView
WHERE NAME="Suresh";
 If we fetch all the data from DetailsView now as,
SELECT * FROM DetailsView;
Output:

 Differentiate between SQL and PL/SQL progamming.


 Differentiate between SQL and PL/SQL.
 Write a PL/SQL block for swapping two numbers.
In PL/SQL code groups of commands are arranged within a block. A block group
related declarations or statements.
In declare part, we declare variables and between begin and end part, we perform
the operations.
Basic structure of pl/sql block
declare
-- declare all the variables
begin -- for start block
-- make a program here
end -- for end block

Declare

-- declare variable num1, num2 and temp of datatype number


num1 number;
num2 number;
temp number;
begin
num1:=1000;
num2:=2000;
-- print result before swapping
dbms_output.put_line('before');
dbms_output.put_line('num1 = '|| num1 ||' num2 = '|| num2);

-- swapping of numbers num1 and num2


temp := num1;
num1 := num2;
num2 := temp;

-- print result after swapping


dbms_output.put_line('after');
dbms_output.put_line('num1 = '|| num1 ||' num2 = '|| num2);

end;

Output:
before
num1 = 1000 num2 = 2000
after
num1 = 2000 num2 = 1000

 Write a program in PL/SQL to find the largest of three numbers.


--To fnd the greatest number among given three numbers
DECLARE
--a assigning with 46
a NUMBER := 46;
--b assigning with 67
b NUMBER := 67;
--c assigning with 21
c NUMBER := 21;
BEGIN
--block start
--If condition start
IF a > b
AND a > c THEN
--if a is greater then print a
dbms_output.Put_line('Greatest number is '
||a);
ELSIF b > a
AND b > c THEN
--if b is greater then print b
dbms_output.Put_line('Greatest number is '||b);
ELSE
--if c is greater then print c
dbms_output.Put_line('Greatest number is '||c);
END IF;
--end if condition
END;
--End program

Output:
Greatest number is 67

 Give syntax and example of Loop statement


Basic loop structure encloses sequence of statements in between
the LOOP and END LOOP statements. With each iteration, the sequence of
statements is executed and then control resumes at the top of the loop.

Syntax

LOOP
Sequence of statements;
END LOOP;
Here, the sequence of statement(s) may be a single statement or a block of
statements. An EXIT statement or an EXIT WHEN statement is required to break
the loop.

Example

DECLARE
x number := 10;
BEGIN
LOOP
dbms_output.put_line(x);
x := x + 10;
IF x > 50 THEN
exit;
END IF;
END LOOP;
-- after exit, control resumes here
dbms_output.put_line('After Exit x is: ' || x);
END;
/
When the above code is executed at the SQL prompt, it produces the following result

10
20
30
40
50
After Exit x is: 60
PL/SQL procedure successfully completed.

 Write a program in PL/SQL to find the factorial of given number N using


FOR ... Loop Command.

declare
-- it gives the final answer after computation
fac number :=1;

-- given number n
-- taking input from user
n number := &1;

-- start block
begin

-- start while loop


while n > 0 loop

-- multiple with n and decrease n's value


fac:=n*fac;
n:=n-1;
end loop;
-- end loop

-- print result of fac


dbms_output.put_line(fac);

-- end the begin block


end;
Output:(if given input as 5)
120

 Explain PL/SQL Block Structure.


In PL/SQL, the code is not executed in single line format, but it is always executed
by grouping the code into a single element called Blocks.
Blocks contain both PL/SQL as well as SQL instruction. All these instruction will
be executed as a whole rather than executing a single instruction at a time.

Block Structure
PL/SQL blocks have a pre-defined structure in which the code is to be grouped.
Below are different sections of PL/SQL blocks.

1. Declaration section
2. Execution section
3. Exception-Handling section

The below picture illustrates the different PL/SQL block and their section order.
Declaration Section
This is the first section of the PL/SQL blocks. This section is an optional part. This
is the section in which the declaration of variables, cursors, exceptions,
subprograms, pragma instructions and collections that are needed in the block will
be declared. Below are few more characteristics of this part.

This particular section is optional and can be skipped if no declarations are


needed.

 This should be the first section in a PL/SQL block, if present.


 This section starts with the keyword ‘DECLARE’ for triggers and anonymous
block. For other subprograms, this keyword will not be present. Instead, the
part after the subprogram name definition marks the declaration section.
 This section should always be followed by execution section.
Execution Section
Execution part is the main and mandatory part which actually executes the code that
is written inside it. Since the PL/SQL expects the executable statements from this
block this cannot be an empty block, i.e., it should have at least one valid executable
code line in it. Below are few more characteristics of this part.

 This can contain both PL/SQL code and SQL code.


 This can contain one or many blocks inside it as a nested block.
 This section starts with the keyword ‘BEGIN’.
 This section should be followed either by ‘END’ or Exception-Handling
section (if present)

Exception-Handling Section:
The exception is unavoidable in the program which occurs at run-time and to handle
this Oracle has provided an Exception-handling section in blocks. This section can
also contain PL/SQL statements. This is an optional section of the PL/SQL blocks.

 This is the section where the exception raised in the execution block is
handled.
 This section is the last part of the PL/SQL block.
 Control from this section can never return to the execution block.
 This section starts with the keyword ‘EXCEPTION’.
 This section should always be followed by the keyword ‘END’.

The Keyword ‘END’ marks the end of PL/SQL block.

 Write a PL/SQL Code to decide the larger of two numbers.


DECLARE
N NUMBER;
M NUMBER;
BEGIN
DBMS_OUTPUT.PUT_LINE('ENTER A NUMBER');
N:=&NUMBER;
DBMS_OUTPUT.PUT_LINE('ENTER A NUMBER');
M:=&NUMBER;
IF N<M THEN
DBMS_OUTPUT.PUT_LINE(''|| N ||' IS GREATER THAN '|| M ||'');
ELSE
DBMS_OUTPUT.PUT_LINE(''|| M ||' IS GREATER THAN '|| N ||'');
END IF;
END;
/
 Write limitations/restrictions of using DML statements on views.
 Each DML statement initiates an implicit transaction, which means that
changes made by the statement are automatically committed at the end of each
successful DML statement.
 Rows that were written to a table recently by using streaming
(the tabledata.insertall method or the Storage Write API) cannot be modified
with UPDATE, DELETE, or MERGE statements. The recent writes are those
that occur within the last 30 minutes. All other rows in the table remain
modifiable by using UPDATE, DELETE, or MERGE statements. The
streamed data can take up to 90 minutes to become available for copy
operations.
 Correlated subqueries within
a when_clause, search_condition, merge_update_clause or merge_insert_cla
use are not supported for MERGE statements.
 Queries that contain DML statements cannot use a wildcard table as the target
of the query. For example, a wildcard table can be used in the FROM clause
of an UPDATE query, but a wildcard table cannot be used as the target of
the UPDATE operation.

 Write a short note on Materialized view.


A materialized view takes the regular view described above and materializes it by
proactively computing the results and storing them in a "virtual" table.

Materialized View definition:

A view can be "materialized" by storing the tuples of the view in the database. Index
structures can be built on the materialized view. Consequently, database accesses to
the materialized view can be much faster than recomputing the view. A materialized
view is like a cache --- a copy of the data that can be accessed quickly.

If a regular view is a saved query, a materialized view is a saved query plus its results
stored as a table.

There are a few important implications of a view being "materialized:"

When referenced in a query, a materialized view doesn't need to be recomputed. --


The results are stored, so querying materialized views tends to be faster.
Because it's stored as if it were a table, indexes can be built on the columns of a
materialized view.

 What are the advantages of views ?


 What are the advantages of creating a view ?

Advantages of views

Security
Each user can be given permission to access the database only through a small
set of views that contain the specific data the user is authorized to see, thus
restricting the user's access to stored data

Query Simplicity
A view can draw data from several different tables and present it as a single table,
turning multi-table queries into single-table queries against the view.

Structural simplicity
Views can give a user a "personalized" view of the database structure, presenting
the database as a set of virtual tables that make sense for that user.

Consistency
A view can present a consistent, unchanged image of the structure of the
database, even if the underlying source tables are split, restructured, or renamed.

Data Integrity
If data is accessed and entered through a view, the DBMS can automatically
check the data to ensure that it meets the specified integrity constraints.

Logical data independence.


View can make the application and database tables to a certain extent
independent. If there is no view, the application must be based on a table. With
the view, the program can be established in view of above, to view the program
with a database table to be separated.

 Explain reference variables with suitable example.

 Consider the following two tables :


Employee (emp_no, name, designation)
Personal_Info (emp_id, date_of_birth, mobile_no)
Answer the following query :
Create a view to include emp_no, name, date_of_birth, mobile_no.
=>Create view combine as select employee.emp_no, employee.name,
personal_info.date_of_birth , personal_info.mobile_no from employee,
personal_info;

 Create a view on the employee table that gives access to limited


information about employee of department number 50:
employee (employee_no, basic_salary, department_no).
 Create view access as select employee_no, basic_salary, department_no from
employee where department_no=50;
 Create a view that give access to limited information about employee in
Department no. 004 from employee table.
Employee (empno, ename, deptno, salary)
 Create view access as select empno, salary from employee where
department_no=004;

 Explain CASE statement with example.


 Explain the CASE statement with example.
 Explain CASE statement with example in oracle.

The CASE expression goes through conditions and returns a value when the first
condition is met (like an if-then-else statement). So, once a condition is true, it
will stop reading and return the result. If no conditions are true, it returns the
value in the ELSE clause. If there is no ELSE part and no conditions are true, it
returns NULL.

Syntax
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;
Below is a selection from the "OrderDetails" table.

OrderDetailID OrderID ProductID Quantity

1 10248 11 12

2 10248 42 10

3 10248 72 5

4 10249 14 9

5 10249 51 40

SELECT OrderID, Quantity,


CASE
WHEN Quantity > 30 THEN 'The quantity is greater than 30'
WHEN Quantity = 30 THEN 'The quantity is 30'
ELSE 'The quantity is under 30'
END AS QuantityText
FROM OrderDetails;

10249 9 The quantity is under 30

10249 40 The quantity is greater than 30

You might also like