You are on page 1of 43


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



“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


What is a view?
A view is a kind of “virtual table”
Contents are defined by a query like:
Select Empno, Name, age from
Where designation=‘developer’;
As shown in the figure

Copyright © 2004,
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


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

Copyright © 2004,
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.


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. Infosys Technologies Ltd 5 ER/CORP/CRS/DB07/003 Version No: 2. the same name as used in the source table is used 5 . Copyright © 2004.Create a view CREATE VIEW ViewSupplier AS SELECT * FROM Supplier. 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.

This may be totally different from what has been used in the source table 6 . Infosys Technologies Ltd 6 ER/CORP/CRS/DB07/003 Version No: 2.SName.SNO.Assigning names to columns CREATE VIEW ViewSupplier AS SELECT S. S.0 We can assign names for the various columns in the view. Copyright © 2004.City FROM Supplier S WHERE City = ‘BHU’. S.

We will discuss them in detail in the following slides 7 .Types of views Horizontal views Vertical views Row/column subset views Grouped views Joined views Copyright © 2004. Infosys Technologies Ltd 7 ER/CORP/CRS/DB07/003 Version No: 2.0 Based on how the view is created.

Bgraders Employee Copyright © 2004. A private( virtual) table for each category can be created and given access to the person concerned 8 . Infosys Technologies Ltd 8 ER/CORP/CRS/DB07/003 Version No: 2. Very useful when data belonging to different categories are present in the table.Horizontal views Create view Bgraders as select * from employee where grade =‘B’.0 Here a horizontal subset of the source table is taken to create the view.

Infosys Technologies Ltd 9 ER/CORP/CRS/DB07/003 Version No: 2. 9 . Copyright © 2004. Age from Employee. grade etc.g: Create view Genemp as select Empno.Vertical views A view which selects only few columns of a table: Genemp For e. Name.0 Helps restricting access to sensitive information like salary.

City FROM Supplier S WHERE City = ‘BHU’.0 SQL standard doesn’t define any notion of horizontal or vertical views . 10 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2.Row/column subset views CREATE VIEW ViewSupplier AS SELECT S. 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.SName.SNO. Copyright © 2004. There could be a combination of these two concepts where a view selects a subset of rows and columns 10 . S. S.

Copyright © 2004.0 Grouped views are created based on a grouped query. 11 . 11 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2.Grouped views The query contains a group by clause CREATE VIEW Emp_Gradewise (grade . the rows in the view don’t have a one to one correspondence with the rows of the source table For this reason . count(*) FROM employee GROUP BY AS SELECT grade. grouped views cannot be updated. They group rows of data and produce one row in the result corresponding to each group So.

Part_id.NAME.Name.SNO=S. Partname.PNO=P.0 (Refer to the supplier.SP. Supplier_Name. 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 .DML) The advantage with this type of view is. Partname.SNO AND SP. QTY_Shipped) AS SELECT SP. Partname.g: SELECT Supplier_id.Joined views Created by specifying a two-table or three-table query in the view creation command CREATE VIEW Ship_View (Supplier_id. Would help extract data which is actually spread over more than one table 12 . For e.SNO.PNO Copyright © 2004. Parts P WHERE SP.PNO.P. 12 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2.SP.S. SUM(Qty) from SHIP_VIEW (Group by Supplier_id.Qty FROM Shipment sp. Suppliers shipment tables we have used in our earlier slides on DDL.

SNO. S. In still others. 13 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2.City FROM Supplier S WHERE City = ‘BHU’. for example. a view is updateable if it is the result of a simple query. Copyright © 2004. CREATE VIEW ViewSupplier AS SELECT S. In some cases. the view is not updateable. if it is defined by some GROUP BY statements. In some others a view is updateable if it is from one table. So a view is updatable if : DISTINCT is not specified in the query used to create the view The FROM clause specifies only one source table The select list doesn’t contain expressions/calculated columns The WHERE clause doesn’t include a subquery The query doesn’t include a GROUP BY or HAVING An example of a view which can’t be updated is given in the next slide 13 . S. all views are not updateable.SName.0 Depending on the commercial implementation being used. UPDATE VIEW ViewSupplier set SName=‘mnb’ where SNO=1000. According to ANSI/ISO standards.Updating a VIEW A view can be modified by the DML update command. views may or may not be updateable. else it is not. A view is updatable if The DBMS is able to trace back the rows and columns of the view to the corresponding rows and columns of the source table.

To ensure that the user of the view.0 The newly inserted row. check option can be used as follows: CREATE VIEW View_Supplier AS SELECT Suppnum. city F rom S u p plier W h ere C ity = " D elh i". 14 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2."Manekchand and co. the view is created to display only suppliers based at Delhi. su p p na m e. What is the result of a Select * from view_suppliers? It shows only the details of suppliers belonging to Delhi.An example C rea te view view _su p p lier As S elect S u p p n um . Subsequently if you execute SELECT * from View_Suppliers – What happens? Copyright © 2004. Suppname. ". Insert into view_supplier Values("sup04". Why? Reason is. view_supplier should not be able to add data for any other town than "Delhi". "Bhubaneswar"). City FROM Supplier WHERE City=‘Delhi’ WITH CHECK OPTION 14 . gets added to the source table subject to non-violation of other integrity constraints.

However.0 if some other views depend on this view. you must own a view in order to drop it. If you specify DROP VIEW ViewSupplier RESTRICT then this view cannot be deleted if other views depend on it. 15 . then if you say DROP VIEW ViewSupplier CASCADE then this view plus all other views that are based on this view are deleted. Copyright © 2004.Dropping Views Views are dropped similar to the way in which the tables are dropped. DROP VIEW <view name>. DROP VIEW ViewSupplier. 15 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2.

16 . 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 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2.Advantages of views Security Query simplicity Structural simplicity Copyright © 2004.0 Security: only a limited set of rows/ columns are viewable by certain users Query simplicity: A view can derive data from many tables.

the query representing creation of the view has to be executed . So.Disadvantages of views Performance Restrictions Copyright © 2004. 17 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2. Restrictions: Not all views are updateable 17 . complex joins may have to be performed every time a query is placed against the view.0 Performance: views based on joins are merely virtaul tables. Every time a query is placed against the view.

Concept of an Index 18 .

if you go through the index which is sorted based on alphabetical order.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. it would be extremely time consuming. if we store an index in a specific block of the disk which contains something like the following Department address Finance 2001f. Now against this term you will find the page numbers where this information is present in the book. Here the index has been formed on the department column. If you want to locate those rows of the employee table where the department is finance. it is very easy to locate a term called linkage editor under the letter L. Apply the same principle to searching for a row in a database table. So. 4005f. 19 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2. Imagine how difficult it is if you have to go through all the pages of the book to locate this information. you can straightawy go to that page number(s) and find your information. Let us understand this … Say you wish to know where you can find some description on “linkage editors” in a system software book.1002f HRD 2000f. This is the benefit of having indexes. Instead.What is an index? Physical storage structure Provides rapid access to rows of a table Mostly created on the primary key column Can be created on any other column also Transparent to the user Copyright © 2004. 19 . if you have to search through the entire hard disk to locate this information. Instead. 3045f Then you know that you have look for rows corresponding to finance dept only in three locations in the hard disk.

0 20 .Advantage Speeds the execution of search queries Disadvantages Consumes additional disk space Must be updated for every row insert into the table and also for every update of the key column Copyright © 2004. 20 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2.

g : CREATE UNIQUE INDEX Emp_index ON Employee (Empid). Deletion: DROP INDEX index-name E.g: DROP INDEX Emp_index.Creation of index-Syntax Creation: CREATE [unique] INDEX index-name ON Table-name (column-name) E. Copyright © 2004.0 21 . 21 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2.

A precompiler would process this kind of a code. no practical is involved with respect to embedded SQL. This doesn’t require any precompiler The following discussions on embedded SQL are purely from a theoretical point of view. The program uses some API function calls and passes the sql as a parameter. As an interactive database language to issue queries against the database and get results online 2. a series of tools act on them and the executable is produced b) API: Application programming interface. 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. As a programmatic language used along with some high level language for performing database access Based on this.Embedded SQL SQL can be used in two ways: 1. 22 . separate out the programming language code and sql. As far as this course is concerned.

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. the order of execution of join etc d) The next step is to generate the ‘Application plan’. It is verified as to whether the tables referred in the query are present. Semantic errors are checked. The system catalog is refereed for this purpose c) The next step is optimization.How does the DBMS process a Query SQL Statement Parse Validate Optimize Generate application plan Execute plan Copyright © 2004. 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. whether column names are valid etc. RDBMS explores possibility of using an index. 23 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2. 23 .0 a) The first step in processing an SQL is Parsing.

24 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2.0 Special variables are used to pass and receive “NULL” New SQL statements not found in interactive SQL are added to enable processing of query results.What is Embedded SQL Interleaving SQL statements along with the other code in a host language program Variables declared in the host program can be used in sql to send /receive values from/to the DBMS Copyright © 2004. 24 .

validates. Ir we have separate precompiler for c. for cobol etc.0 The Embedded SQL program is submitted to a precompiler. Now. 25 Infosys Technologies Ltd 1. The run-time communication between the executable form of source program and the Application plan is totally hidden . These routines provide the necessary run-time link with the DBMS. This program parses each SQL statement. 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. parallely. 4. this source file is compiled by the compiler to generate the object file. This is a language specific tool. 25 . ER/CORP/CRS/DB07/003 Version No: 2. optimizes and generates the binary DBMS-executable form called the application plan. the DBRM is submitted to a “Bind” program. The linker links the object code with other library routines (which includes the DBMS library) and generates the executable 5. This is aut0-generated by the precompiler The other file is the DBRM (Data Base Request Module). After all statements are thus converted . This contains all the SQL commands removed from the program 3.Processing of an Embedded SQL Program Copyright © 2004. 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 block of sql code is ended with a .0 This depends on the host language . EXEC SQL is a common way to begin. Copyright © 2004.Using embedded SQL EXEC SQL Keyword indicates to the pre compiler that the next line of code is for the SQL handling. 26 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2. 26 . But the way to end is language specific.

char emp_dept[3]. int emp_sal. EXEC SQL INSERT INTO Supplier VALUE (:Sup_No. 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. short emp_sali. short emp_addri. Compatible data types. varchar emp_name[20]. varchar emp_addr[20]. 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. exec sql end declare section. Sup_Name etc . short emp_depti. name and city through the variables declared in the c program named: Sup_No. :Sup_Name.Declaring host variables SQL DECLARE SECTION. short emp_desi.0 An example is as shown below: exec sql begin declare section. 27 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2. Preceded by a colon(:). Copyright © 2004. varchar username[20]. we are passing values for supplier number . char emp_des[3]. :Sup_City). 27 . varchar password[20]. int emp_no.

arr). password."pramodv").len = strlen(username. After this step."pramodv").des. 28 . :emp_des.addr. :emp_dept. The answer to the question in the slide lies in the next few slides. the remaining sql statements are written. :emp_addr.arr).dept. strcpy(username.0 The below code snippet shows how a connection to a DBMS is established by supplying the userid and password. :emp_sal FROM employee WHERE eno = :emp_no. strcpy(password.len=strlen(password. exec sql connect :username identified by :password.arr. main() { exec sql whenever sqlerror goto sqlerrorlabel. 28 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2. Where are the values of the rows returned by SQL stored? Copyright © 2004.arr.Example of embedded SQL EXEC SQL SELECT name.sal INTO :emp_name.. username.

Positive Retrieved value is in host variable. EXEC SQL SELECT name. short emp_sali. Host variable value not reliable. Zero Host variable has been assigned the retrieved value.dept. Negative Retrieved value is NULL. exec sql end declare section.0 The indicator variables are used to indicate the status of the value received into the host variable.addr. :emp_des:emp_desi. Copyright © 2004. short emp_depti. The following highlights the declaration of indicator variables exec sql begin declare section. :emp_addr:emp_addi. ……… short emp_addri.des. varchar username[20]. 29 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2. They are also used with a prefixed colon 29 . but this indicates a warning. :emp_sal FROM employee WHERE eno = :emp_no .Indicator variables Variable to indicate whether the returned value is NULL. short emp_desi.sal INTO :emp_name. varchar password[20]. :emp_dept. Host variable can be used in the application program. rounding off or truncation for example. Indicator variables are required only for NULLABLE columns.

30 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2.A complete program example Please double click the icon below Text Document Copyright © 2004.0 This example shows use of indicator variables. 30 . host variables etc.

Copyright © 2004. Another example follows in the next slide 31 .0 A cursor is used along with an SQL statement in an embedded SQL program. in turn.CURSOR Needed for select queries which return multiple rows of output from DBMS A kind of variable associated with a query. The value of this variable will be each row. 31 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2. of that query’s output. A cursor is declared as follows: exec sql declare emp cursor for select * from employee. when the SELECT statement returns multiple rows.

32 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2. EXEC SQL DECLARE CURSOR SupplierCur SELECT * FROM Supplier Where City=‘BHU’.Declaring Cursor The query is not executed immediately. Copyright © 2004. It doesn’t call for any immediate action 32 .0 The Declaration of the cursor is like a directive to the precompiler. This is only the definition.

Once opened.OPEN EXEC SQL OPEN CURSOR SupplierCur.Opening Cursor . 33 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2. Copyright © 2004. 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 . This opens the table of query results for the application’s use. the cursor remains open until it is explicitly closed or till the transaction ends.0 The cursor thus declaraed can be opened by saying: exec sql openSupplierCur.

:Sup_Name. 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. :emp_des:desi. if (depti == -1) strcpy(emp_dept.arr. :emp_dept:depti. printf("%d\t%20s\t%20s\t%3s\t%3s\t%d\n".arr[emp_name. :emp_name..arr[emp_addr. :emp_sal:sali. else emp_addr.len] = '\0'. 34 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2.arr[0] ='\0'. At this point. :emp_addr:addri. :Sup_Status. emp_addr. if (desi == -1) strcpy(emp_des. Copyright © 2004. emp_name.Cursor’s FETCH command Used to extract the values of OPEN CURSOR EXEC SQL FETCH SupplierCur INTO :Sup_No. emp_name. the cursor is not pointing at any row When the first fetch statement is encountered. emp_des. if (sali == -1) emp_sal=0.len] = '\0'." "). emp_sal).arr. :Sup_City. for(. if (addri == -1) emp_addr. 34 . when the fetch statement is executed again.) { exec sql fetch emp into :emp_no. an SQLWARNING is raised. emp_dept. emp_no. After the last row has been retrieved." ").0 The open statement positions the cursor on top of the query results.

the cursor has to be opened again 35 . To get back the values. The query results represented by the cursor would not be available after this.Cursor’s CLOSE command Closes an opened cursor EXEC SQL CLOSE SupplierCur Copyright © 2004.0 This closes the cursor. 35 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2.

char emp_des[3].sali. exec sql declare emp cursor for select * from char emp_dept[3]. This SELECT statement is executed only when the cursor is opened (see below). varchar username[20]. /* COMMENT BEGINS A cursor is declared for a SELECT statement. 36 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2.depti. varchar password[20]. int emp_no. int emp_sal. varchar emp_addr[20]. varchar emp_name[20]. short addri.A program using cursor Refer to Notes page for an example Copyright © 2004. exec sql end declare section. COMMENT ENDS */ 36 .0 exec sql begin declare section.

strcpy(password. exec sql whenever not found goto end_of_fetch. The error not found will be raised when the last record has been fetched and then we try to fetch another record. COMMENT ENDS */ 37 . username. then when the cursor tries to fetch the next record after all records have been fetched. the not found error is raised .. If the whenever condition is declared after the for loop. exec sql open emp.but since we have not handled this error. strcpy(username. From previous Notes page) Copyright © 2004."pramodv")."pramodv"). In this program. then opened and then fetched before the records can be accessed. when the not found error is raised.0 exec sql include sqlca.A program using cursor Refer to Notes page ( contd. main() { exec sql whenever sqlerror goto sqlerrorlabel. 37 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2. exec sql connect :username identified by :password.arr). the program will come to a stop. /* COMMENT BEGINS The cursor must be first declared. since the whenever statement is defined before the for loop.arr.len = strlen(username. 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.len=strlen(password.arr).arr. Recall that the scope of the whenever command is from the point where it is declared upto another whenever command. password.

emp_name. :emp_sal:sali.. 38 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2. :emp_des:desi. if (sali == -1) emp_sal=0. } end_of_fetch: exec sql close emp.0 system("cls").arr[emp_name.) { exec sql fetch emp into :emp_no. emp_dept." "). if (depti == -1) strcpy(emp_dept.len] = '\0'." "). emp_des. if (addri == -1) emp_addr. else emp_addr. emp_name. exit(1). From previous Notes page) Copyright © 2004. emp_no. exit(0). for(.arr[emp_addr.sqlerrm.arr. emp_addr.A program using cursor Refer to Notes page ( contd. printf("No\t\t\tName\t\t\tAddress\t Desig dept Salary\n\n").arr. emp_sal). :emp_dept:depti. printf("%d\t%20s\t%20s\t%3s\t%3s\t%d\n". :emp_name. } 38 ..arr[0] ='\0'.len] = '\0'. if (desi == -1) strcpy(emp_des. :emp_addr:addri.sqlerrmc). printf("\t\t List of employees\n\n"). sqlca. sqlerrorlabel: printf("\n %s \n".

programs can use an “SQLSTATE” error code to handle errors. WHENEVER is a positional command. it updates the value of the SQLCA According to the SQL2 standrad. By checking the fileds in this datastructure. the program can check the status of execution and act accordingly. Any SQL error the controls go to the label.sqlstate. In the program.Error handling EXEC SQL WHENEVER SQLERROR goto sqlerrorlabel. 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. 39 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2. This includes the SQLCA datastructure into the program. AS and when the DBMS executes an embedded SQL code. run-time errors are reported to the program by the DBMS in the form of some error code. You might have observed a statement like: exec sql include sqlca.0 In embedded SQL programs.This is one of the fileds inside the SQLCA datastructure. 39 .”00000”) Goto error_lablel. Copyright © 2004. If(strcmp(sqlca. SQLSTATE consists of two parts: a) b) An error-class that identifies the type of error An error subclass that identifies the specific type of error A code snippet making use of this would look something like this: Exec sql delete * from emp where sal < 3000.

EXEC SQL WHENEVER NOT FOUND CONTINUE. 40 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2.0 It is laborious task to check the error code after every sql statement.Error handling .. To simplify this process. there is a WHENEVER statement. NOT FOUND is used when there are no records that the SQL can return It is not an error case Copyright © 2004.. This is a directive that tells the precompiler what code code should be included following every executable SQL statement This statement can be used to handle three types of errors 1) SQLERROR 2) SQLWARNING 3) NOT FOUND (when we try to fetch rows from a cursor while there are no more) WHENEVER/GOTO: to generate a branch to the given label WHENEVER/CONTINUE to alolow the normal flow to continue This is summarised in the following slide 40 .

41 . It is in effect until the next such whenever statement is encountered in the code.Error handling .0 This whenever is a positional command. 41 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2.syntax WHENEVER {NOT FOUND | SQLERROR | SQLWARNING} {CONTINUE | GO TO host-label} Copyright © 2004.

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 . 42 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2. converts and generates executable code Copyright © 2004.0 42 .

0 43 . 43 Infosys Technologies Ltd ER/CORP/CRS/DB07/003 Version No: 2.Thank You! Copyright © 2004.