Rdbms Day6
Rdbms Day6
Views
Concept of an index
Embedded SQL
In today’s session we would be discussing about the concept of views, the concept of an index and
how it is useful in database implementations and the concept embedded SQL programming using
pro*c.
1
Views
“Views “ is an important and useful feature in RDBMS. It helps achieve sharing with proper security.
We will be looking at
What is a view
How to create a view
How to update/delete a view
Different types of views
Advantages and disadvantages of views in the next few slides
2
What is a view?
A view is a kind of “virtual table”
ER/CORP/CRS/DB07/003
Copyright © 2004, 3
Infosys Technologies Ltd Version No: 2.0
Views are tables whose contents are taken or derived from other tables.
To the user, the view appears like a table with columns and rows
But in reality, the view doesn’t exists in the database as a stored set of values
The rows and columns that we find inside a view are actually the results generated by a query that
defines the view
View is like a window through which we see a limited region of the actual table
The table from where the actual data is obtained is called the source table
3
What is a view to the DBMS
We can use views in select statements like
Select * from view_employees where age > 23;
DBMS translates the request to an equivalent request to the source table
ER/CORP/CRS/DB07/003
Copyright © 2004, 4
Infosys Technologies Ltd Version No: 2.0
For simple queries the results are generated row by row on the fly.
For more complex views the DBMS must generate a temporary table representing the view and later
discard it.
4
Create a view
CREATE VIEW ViewSupplier
AS SELECT *
FROM Supplier;
ER/CORP/CRS/DB07/003
Copyright © 2004, 5
Infosys Technologies Ltd Version No: 2.0
You must have permission on the table refereed in the view to successfully create the view
Can assign a new name to each column chosen in the view
Only names can be different. The data type etc remain the same as the source table because, the
values are after all going to be derived from that table
If no names are specified for columns, the same name as used in the source table is used
5
Assigning names to columns
CREATE VIEW ViewSupplier
AS SELECT S.SNO, S.SName, S.City
FROM Supplier S
WHERE City = ‘BHU’;
ER/CORP/CRS/DB07/003
Copyright © 2004, 6
Infosys Technologies Ltd Version No: 2.0
We can assign names for the various columns in the view. This may be totally different from what
has been used in the source table
6
Types of views
Horizontal views
Vertical views
Row/column subset views
Grouped views
Joined views
ER/CORP/CRS/DB07/003
Copyright © 2004, 7
Infosys Technologies Ltd Version No: 2.0
Based on how the view is created. We will discuss them in detail in the following slides
7
Horizontal views
Create view Bgraders as select * from employee where grade =‘B’;
Bgraders
Employee
ER/CORP/CRS/DB07/003
Copyright © 2004, 8
Infosys Technologies Ltd Version No: 2.0
Here a horizontal subset of the source table is taken to create the view.
Very useful when data belonging to different categories are present in the table.
A private( virtual) table for each category can be created and given access to the person concerned
8
Vertical views
A view which selects only
Genemp few columns of a table:
For e.g:
Create view Genemp as
select Empno, Name, Age
from Employee;
ER/CORP/CRS/DB07/003
Copyright © 2004, 9
Infosys Technologies Ltd Version No: 2.0
9
Row/column subset views
CREATE VIEW ViewSupplier
AS SELECT S.SNO, S.SName, S.City
FROM Supplier S
WHERE City = ‘BHU’;
ER/CORP/CRS/DB07/003
Copyright © 2004, 10
Infosys Technologies Ltd Version No: 2.0
SQL standard doesn’t define any notion of horizontal or vertical views . It is for our own
understanding that we have given names for views which select only selected rows/columns from the
source table as horizontal/vertical views. There could be a combination of these two concepts where
a view selects a subset of rows and columns
10
Grouped views
The query contains a group by clause
ER/CORP/CRS/DB07/003
Copyright © 2004, 11
Infosys Technologies Ltd Version No: 2.0
Grouped views are created based on a grouped query. They group rows of data and produce one
row in the result corresponding to each group
So, the rows in the view don’t have a one to one correspondence with the rows of the source table
11
Joined views
Created by specifying a two-table or three-table query in the view creation
command
ER/CORP/CRS/DB07/003
Copyright © 2004, 12
Infosys Technologies Ltd Version No: 2.0
(Refer to the supplier,parts, shipment tables we have used in our earlier slides on DDL,DML)
The advantage with this type of view is, any subsequent info can be extracted from this view as a
single-table query instead of writing a more complex two or three table query . For e.g:
Would help extract data which is actually spread over more than one table
12
Updating a VIEW
ER/CORP/CRS/DB07/003
Copyright © 2004, 13
Infosys Technologies Ltd Version No: 2.0
Depending on the commercial implementation being used, views may or may not be updateable. In some
cases, all views are not updateable. In some others a view is updateable if it is from one table, else it is not. In
still others, a view is updateable if it is the result of a simple query; if it is defined by some GROUP BY
statements, for example, the view is not updateable.
The DBMS is able to trace back the rows and columns of the view to the corresponding rows and columns of
the source table.
So a view is updatable if :
13
An example
ER/CORP/CRS/DB07/003
Copyright © 2004, 14
Infosys Technologies Ltd Version No: 2.0
The newly inserted row, gets added to the source table subject to non-violation of other integrity
constraints. What is the result of a Select * from view_suppliers? It shows only the details of suppliers
belonging to Delhi. Why?
Reason is, the view is created to display only suppliers based at Delhi.
To ensure that the user of the view, view_supplier should not be able to add data for any other town
than "Delhi", check option can be used as follows:
14
Dropping Views
ER/CORP/CRS/DB07/003
Copyright © 2004, 15
Infosys Technologies Ltd Version No: 2.0
DROP VIEW ViewSupplier CASCADE then this view plus all other views that are based on this view
are deleted.
If you specify
DROP VIEW ViewSupplier RESTRICT then this view cannot be deleted if other views depend on it.
15
Advantages of views
Security
Query simplicity
Structural simplicity
ER/CORP/CRS/DB07/003
Copyright © 2004, 16
Infosys Technologies Ltd Version No: 2.0
Security: only a limited set of rows/ columns are viewable by certain users
Query simplicity: A view can derive data from many tables. So, subsequently we can use queries on
the view as single table queries rather than writing queries against the source tables as multi-table
queries
Structural simplicity: views can show only a portion of the table which is relevant to the user there by
keeping it simple.
16
Disadvantages of views
Performance
Restrictions
ER/CORP/CRS/DB07/003
Copyright © 2004, 17
Infosys Technologies Ltd Version No: 2.0
Performance: views based on joins are merely virtaul tables. Every time a query is placed against the
view, the query representing creation of the view has to be executed . So, complex joins may have to
be performed every time a query is placed against the view.
Restrictions: Not all views are updateable
17
Concept of an Index
18
What is an index?
ER/CORP/CRS/DB07/003
Copyright © 2004, 19
Infosys Technologies Ltd Version No: 2.0
An index is like the index page we see at the end of a book or like the index card used in a library. Let
us understand this …
Say you wish to know where you can find some description on “linkage editors” in a system software
book. Imagine how difficult it is if you have to go through all the pages of the book to locate this
information.
Instead, if you go through the index which is sorted based on alphabetical order, it is very easy to
locate a term called linkage editor under the letter L. Now against this term you will find the page
numbers where this information is present in the book. So, you can straightawy go to that page
number(s) and find your information. Apply the same principle to searching for a row in a database
table. If you want to locate those rows of the employee table where the department is finance, if you
have to search through the entire hard disk to locate this information, it would be extremely time
consuming. Instead, if we store an index in a specific block of the disk which contains something like
the following
Department address
Finance 2001f, 4005f,1002f
HRD 2000f, 3045f
Then you know that you have look for rows corresponding to finance dept only in three locations in
the hard disk. Here the index has been formed on the department column.
This is the benefit of having indexes.
19
Advantage
Speeds the execution of search queries
Disadvantages
ER/CORP/CRS/DB07/003
Copyright © 2004, 20
Infosys Technologies Ltd Version No: 2.0
20
Creation of index-Syntax
Creation:
Deletion:
ER/CORP/CRS/DB07/003
Copyright © 2004, 21
Infosys Technologies Ltd Version No: 2.0
21
Embedded SQL
1. As an interactive database language to issue queries against the database and get results online
2. As a programmatic language used along with some high level language for performing database
access
Based on this, commercial products support two flavors of using SQL with programming languages
a) Embedded SQL: directly writing SQL commands inside HLL (High level language) program
interspersed with the other HLL code. A precompiler would process this kind of a code, separate
out the programming language code and sql, a series of tools act on them and the executable is
produced
b) API: Application programming interface. The program uses some API function calls and passes
the sql as a parameter. This doesn’t require any precompiler
The following discussions on embedded SQL are purely from a theoretical point of view. As
far as this course is concerned, no practical is involved with respect to embedded SQL.
22
How does the DBMS process a Query
SQL Statement
Parse
Validate
Optimize
Generate
application plan
Execute plan
ER/CORP/CRS/DB07/003
Copyright © 2004, 23
Infosys Technologies Ltd Version No: 2.0
a) The first step in processing an SQL is Parsing. The statement is split into words and checked
against syntax. Syntax errors and spelling mistakes can be detected at this stage
b) The second step is Validation. Semantic errors are checked. It is verified as to whether the
tables referred in the query are present, whether column names are valid etc. The system
catalog is refereed for this purpose
c) The next step is optimization. RDBMS explores possibility of using an index, the order of
execution of join etc
d) The next step is to generate the ‘Application plan’. It is binary representation of the sequence of
steps to be executed by the DBMS in executing the query
e) The ‘Application plan’ is executed.
23
What is Embedded SQL
Interleaving SQL statements along with the other code in a host language
program
ER/CORP/CRS/DB07/003
Copyright © 2004, 24
Infosys Technologies Ltd Version No: 2.0
New SQL statements not found in interactive SQL are added to enable processing of query results.
24
Processing of an Embedded SQL Program
ER/CORP/CRS/DB07/003
Copyright © 2004, 25
Infosys Technologies Ltd Version No: 2.0
1. The Embedded SQL program is submitted to a precompiler. This is a language specific tool. Ir we have
separate precompiler for c, for
cobol etc.
2. The precompiler generates two files as output. One is the source file in which all SQL commands are
removed and replaced with calls to some special DBMS routines. These routines provide the necessary
run-time link with the DBMS. This is aut0-generated by the precompiler
The other file is the DBRM (Data Base Request Module). This contains all the SQL commands removed from
the program
3. Now, this source file is compiled by the compiler to generate the object file.
4. The linker links the object code with other library routines (which includes the DBMS library) and generates
the executable
5. parallely, the DBRM is submitted to a “Bind” program. This program parses each SQL statement, validates,
optimizes and generates the binary DBMS-executable form called the application plan. After all statements
are thus converted , the combined application plan is stored under the DBMS with the same name as the
application name from where the SQL statements were stripped off
6. The run-time communication between the executable form of source program and the Application plan is
totally hidden .
25
Using embedded SQL
EXEC SQL
Keyword indicates to the pre compiler that the next line of code is for the
SQL handling.
ER/CORP/CRS/DB07/003
Copyright © 2004, 26
Infosys Technologies Ltd Version No: 2.0
This depends on the host language . EXEC SQL is a common way to begin. But the way to end is
language specific.
26
Declaring host variables
EXEC SQL
INSERT INTO Supplier
VALUE (:Sup_No, :Sup_Name, :Sup_City);
ER/CORP/CRS/DB07/003
Copyright © 2004, 27
Infosys Technologies Ltd Version No: 2.0
The data type of the variable which is going to be used in a query should be compatible with the data type of the
column of the table for which it is going to be substituted/ compared with
For example in the query shown in the slide, we are passing values for supplier number , name and city
through the variables declared in the c program named: Sup_No, Sup_Name etc . If the data type of the column
SNO in the Supplier table is INTEGER then the datatype of the variable Sup_No should be long …
The variables declared in the host language are preceded with a : when they are used in a query.
27
Example of embedded SQL
EXEC SQL
SELECT name,addr,des,dept,sal
INTO :emp_name, :emp_addr,
:emp_des, :emp_dept, :emp_sal
FROM employee
WHERE eno = :emp_no;
Where are the values of the rows returned by SQL stored?
ER/CORP/CRS/DB07/003
Copyright © 2004, 28
Infosys Technologies Ltd Version No: 2.0
The below code snippet shows how a connection to a DBMS is established by supplying the userid
and password.
main()
{
exec sql whenever sqlerror goto sqlerrorlabel;
strcpy(username.arr,"pramodv");
username.len = strlen(username.arr);
strcpy(password.arr,"pramodv");
password.len=strlen(password.arr);
exec sql connect :username identified by :password;
The answer to the question in the slide lies in the next few slides..
28
Indicator variables
Variable to indicate whether the returned value is NULL.
ER/CORP/CRS/DB07/003
Copyright © 2004, 29
Infosys Technologies Ltd Version No: 2.0
The indicator variables are used to indicate the status of the value received into the host variable.
Zero Host variable has been assigned the retrieved value. Host variable can be used in
the application program.
Negative Retrieved value is NULL. Host variable value not reliable.
Positive Retrieved value is in host variable, but this indicates a warning, rounding off or
truncation for example.
29
A complete program example
Please double click the icon below
Text Document
ER/CORP/CRS/DB07/003
Copyright © 2004, 30
Infosys Technologies Ltd Version No: 2.0
30
CURSOR
Needed for select queries which return multiple rows of output from DBMS
The value of this variable will be each row, in turn, of that query’s output.
A cursor is used along with an SQL statement in an embedded SQL program, when the
SELECT statement returns multiple rows. A cursor is declared as follows:
31
Declaring Cursor
The query is not executed immediately;
This is only the definition.
EXEC SQL
DECLARE CURSOR SupplierCur
SELECT * FROM Supplier
Where City=‘BHU’;
ER/CORP/CRS/DB07/003
Copyright © 2004, 32
Infosys Technologies Ltd Version No: 2.0
The Declaration of the cursor is like a directive to the precompiler. It doesn’t call for any immediate
action
32
Opening Cursor - OPEN
EXEC SQL
OPEN CURSOR SupplierCur;
ER/CORP/CRS/DB07/003
Copyright © 2004, 33
Infosys Technologies Ltd Version No: 2.0
You may imagine a cursor to be like a buffer which receives query results and allows the application
to leisurely go through each row of result and process it.
33
Cursor’s FETCH command
Used to extract the values of OPEN CURSOR
EXEC SQL
FETCH SupplierCur
INTO :Sup_No, :Sup_Name,
:Sup_City, :Sup_Status;
ER/CORP/CRS/DB07/003
Copyright © 2004, 34
Infosys Technologies Ltd Version No: 2.0
The open statement positions the cursor on top of the query results. At this point, the cursor is not pointing at
any row
When the first fetch statement is encountered, the cursor is automatically positioned at the first row and
retrieves the same this goes on by automatically incrementing the cursor position for executing the fetch
statement each time until the end of rows is reached. After the last row has been retrieved, when the fetch
statement is executed again, an SQLWARNING is raised.
for(;;)
{
exec sql fetch emp into :emp_no, :emp_name, :emp_addr:addri, :emp_des:desi, :emp_dept:depti,
:emp_sal:sali;
emp_name.arr[emp_name.len] = '\0';
if (addri == -1)
emp_addr.arr[0] ='\0';
else
emp_addr.arr[emp_addr.len] = '\0';
if (desi == -1)
strcpy(emp_des," ");
if (depti == -1)
strcpy(emp_dept," ");
if (sali == -1)
emp_sal=0;
printf("%d\t%20s\t%20s\t%3s\t%3s\t%d\n", emp_no, emp_name.arr, emp_addr.arr, emp_des, emp_dept,
emp_sal);
34
Cursor’s CLOSE command
Closes an opened cursor
EXEC SQL
CLOSE SupplierCur
ER/CORP/CRS/DB07/003
Copyright © 2004, 35
Infosys Technologies Ltd Version No: 2.0
This closes the cursor. The query results represented by the cursor would not be available after this.
To get back the values, the cursor has to be opened again
35
A program using cursor
Refer to Notes page for an example
ER/CORP/CRS/DB07/003
Copyright © 2004, 36
Infosys Technologies Ltd Version No: 2.0
36
A program using cursor
Refer to Notes page ( contd.. From previous Notes page)
ER/CORP/CRS/DB07/003
Copyright © 2004, 37
Infosys Technologies Ltd Version No: 2.0
/* COMMENT BEGINS
The cursor must be first declared, then opened and then fetched before the records can be
accessed. The error not found will be raised when the last record has been fetched and then we try to
fetch another record.
Recall that the scope of the whenever command is from the point where it is declared upto another
whenever command. If the whenever condition is declared after the for loop, then when the cursor
tries to fetch the next record after all records have been fetched, the not found error is raised - but
since we have not handled this error, the program will come to a stop.
In this program, since the whenever statement is defined before the for loop, when the not found
error is raised, it will be handled in the manner that we have specified in the whenever command and
control moves to the label specified in the whenever condition.
COMMENT ENDS */
37
A program using cursor
Refer to Notes page ( contd.. From previous Notes page)
ER/CORP/CRS/DB07/003
Copyright © 2004, 38
Infosys Technologies Ltd Version No: 2.0
system("cls");
printf("\t\t List of employees\n\n");
printf("No\t\t\tName\t\t\tAddress\t Desig dept Salary\n\n");
for(;;)
{
exec sql fetch emp into :emp_no, :emp_name, :emp_addr:addri, :emp_des:desi, :emp_dept:depti,
:emp_sal:sali;
emp_name.arr[emp_name.len] = '\0';
if (addri == -1)
emp_addr.arr[0] ='\0';
else
emp_addr.arr[emp_addr.len] = '\0';
if (desi == -1)
strcpy(emp_des," ");
if (depti == -1)
strcpy(emp_dept," ");
if (sali == -1)
emp_sal=0;
printf("%d\t%20s\t%20s\t%3s\t%3s\t%d\n", emp_no, emp_name.arr, emp_addr.arr, emp_des, emp_dept, emp_sal);
}
end_of_fetch:
exec sql close emp;
exit(0);
sqlerrorlabel:
printf("\n %s \n", sqlca.sqlerrm.sqlerrmc);
exit(1);
}
38
Error handling
EXEC SQL
WHENEVER SQLERROR
goto sqlerrorlabel;
ER/CORP/CRS/DB07/003
Copyright © 2004, 39
Infosys Technologies Ltd Version No: 2.0
In embedded SQL programs, run-time errors are reported to the program by the DBMS in the form of some
error code. The DBMS communicates the error status information through an area of program storage
called “SQLCA” (SQL communications area)
This SQLCA is a data structure that contains error variables and status indicators. You might have observed a
statement like:
exec sql include sqlca;
In the program. This includes the SQLCA datastructure into the program. By checking the fileds in this
datastructure, the program can check the status of execution and act accordingly.
AS and when the DBMS executes an embedded SQL code, it updates the value of the SQLCA
According to the SQL2 standrad, programs can use an “SQLSTATE” error code to handle errors.This is one of
the fileds inside the SQLCA datastructure.
A code snippet making use of this would look something like this:
39
Error handling ...
EXEC SQL
WHENEVER NOT FOUND CONTINUE;
NOT FOUND is used when there are no records that the SQL can
return
It is not an error case
ER/CORP/CRS/DB07/003
Copyright © 2004, 40
Infosys Technologies Ltd Version No: 2.0
It is laborious task to check the error code after every sql statement. To simplify this process, there is
a WHENEVER statement. This is a directive that tells the precompiler what code code should be
included following every executable SQL statement
1) SQLERROR
2) SQLWARNING
3) NOT FOUND (when we try to fetch rows from a cursor while there are no more)
40
Error handling - syntax
WHENEVER
{NOT FOUND
| SQLERROR
| SQLWARNING}
{CONTINUE
| GO TO host-label}
ER/CORP/CRS/DB07/003
Copyright © 2004, 41
Infosys Technologies Ltd Version No: 2.0
This whenever is a positional command. It is in effect until the next such whenever statement is
encountered in the code.
41
Summary
Views create a window into the table thereby allowing restricted access
Index helps speed up the search process
Embedded SQL programs are written in some HLL in which SQL statements
are intermixed
A special processing separates the SQL , converts and generates executable
code
ER/CORP/CRS/DB07/003
Copyright © 2004, 42
Infosys Technologies Ltd Version No: 2.0
42
Thank You!
ER/CORP/CRS/DB07/003
Copyright © 2004, 43
Infosys Technologies Ltd Version No: 2.0
43