Sunteți pe pagina 1din 74

DATABASE MANAGEMENT SYSTEM

LAB MANUAL

VERSION 2012.08.01

PREFACE

To write a manual for a lab as exciting as Data base management system both a challenging and exciting task. Challenging because what to leave and what to include. Before you begin, let me tell you that this manual is not to cover each and every aspect of DBMS , neither to bombard you with lots of technical details . Rather focus is to impart tool independent database principles and to learn recent trends in DBMS. If we look at the evolution of the information processing technologies, we can see that while the first generation of client/server systems brought data to desktop, not all of this data was easy to understand , unfortunately, and as such , it was not very useful to end users. As a result , a number of new technologies have emerged that are focused on improving the data content of the data to empower the knowledge workers of today and tomorrow. In some ways, these technologies are the manifestation of the maturity of the client /server computing model and its applicability to a wide variety of business problems. Therefore this manual is about the need, the value, and the technological means of acquiring and using information in the information age.

AJAY KAUSHIK ASSISTANT PROFESSOR


DEPARTMENT OF INORMATION TECHNOLOGY

MAIT

ERRATA AND SUGGESTIONS Errors in this manual and suggestions to improve the quantity and quality of this manual are welcomed on my mail inbox Ajayk08@yahoo.com Ajayk08@gmail.com

Lab Notes Adding the Constraints


Constraint types:
3

NOT NULL
A column in a table can be specified not null. It's not possible to insert a null in such a column. The default is null. So, in the following create table statement, a null can be inserted into the column named c. create table ri_not_null ( a number not null, b number null, c number ); insert into ri_not_null values ( 1, null, null); insert into ri_not_null values ( 2, 3, 4); insert into ri_not_null values (null, 5, 6); The first to records can be inserted, the third cannot, throwing a ORA01400: cannot insert NULL into ("RENE"."RI_NOT_NULL"."A"). The not null/null constraint can be altered with alter table ri_not_null modify a null; After this modification, the column a can contain null values. //ALTER TABLE mytable //ADD CONSTRAINT your_constraint_name_here CHECK(mynumber IS NOT NULL) ;

UNIQUE KEY
The unique constraint doesn't allow duplicate values in a column. If the unique constraint encompasses two or more columns, no two equal combinations are allowed. create table ri_unique ( a number unique, b number ); However, if a column is not explicitely defined as not null, nulls can be inserted multiple times: insert insert insert insert insert insert into into into into into into ri_unique ri_unique ri_unique ri_unique ri_unique ri_unique values values values values values values (4, 5); (2, 1); (9, 8); (6, 9); (null,9); (null,9); 4

Now: trying to insert the number 2 again into a: insert into ri_unique values (2,7); This statement issues a ORA-00001: unique constraint (RENE.SYS_C001463 violated). Every constraint, by the way, has a name. In this case, the name is: RENE.SYS_C001463. In order to remove that constraint, an alter table ... drop constraint ... is needed: alter table ri_unique drop constraint sys_c001463; Of course, it is also possible to add a unique constraint on an existing table: alter table ri_unique add constraint uq_ri_b unique (b); A unique constraint can be extended over multiple columns: create table ri_3 ( a number, b number, c number, unique (a,b) ); It is possible to name the constraint. The following example creates a unique constraint on the columns a and b and names the constraint uq_ri_3. create table ri_3 ( a number, b number, c number, constraint uq_ri_3 unique (a,b) );

LIKE
Declaring Variables LIKE Columns If you use the LIKE clause, the database server assigns the variable the same data type as a specified column in a table, synonym, or view. The data types of variables that are defined as database columns are resolved at runtime; therefore, column and table do not need to exist at compile time. You can use the LIKE keyword to declare that a variable is like a serial column. This declares an INTEGER variable if the column is of the SERIAL data type, or an INT8 variable if the column is of the SERIAL8 data type. For example, if the column serialcol in the mytab table has the SERIAL data type, you can create the following SPL function:

CREATE FUNCTION func1() DEFINE local_var LIKE mytab.serialcol; RETURN; END FUNCTION; The variable local_var is treated as an INTEGER variable. Create Check Constraint with LIKE ALTER TABLE <table_name> ADD CONSTRAINT <constraint_name> CHECK (<column_name> LIKE <condition>); ALTER TABLE person ADD CONSTRAINT cc_person_ssn CHECK (ssn LIKE '___-__-____'); SELECT constraint_name, constraint_type, search_condition FROM user_constraints WHERE table_name = 'PERSON'; INSERT INTO person (person_id, last_name, per_age, ssn) VALUES (1, 'Morgan', 54, '333-22-4444'); INSERT INTO person (person_id, last_name, per_age, ssn) VALUES (2, 'Cline', 57, '22-333-4444'); INSERT INTO person (person_id, last_name, per_age, ssn) VALUES (3, 'Scott', 39, 'Oops'); ALTER TABLE uclass ADD CONSTRAINT cc_uclass_class_name CHECK (class_name LIKE 'Ora%'); 6

SELECT constraint_name, constraint_type, search_condition FROM user_constraints WHERE table_name = 'UCLASS'; INSERT INTO uclass VALUES (101, 'Oracle'); INSERT INTO uclass VALUES (201, 'Orxcle'); Create Check Constraint with NOT LIKE ALTER TABLE <table_name> ADD CONSTRAINT <constraint_name> CHECK (<column_name> NOT LIKE <condition>); ALTER TABLE uclass ADD CONSTRAINT cc_uclass_class_name CHECK (class_name NOT LIKE '%O%'); INSERT INTO uclass VALUES (101, 'Basic Oracle'); INSERT INTO uclass VALUES (201, 'Oracle SQL'); INSERT INTO uclass VALUES (301, 'oracle SQL');

PRIMARY KEY
On a technical level, a primary key combines a unique and a not null constraint. Additionally, a table can have at most one primary key. After creating a primary key, it can be referenced by a foreign key. create table ri_primary_key ( a number primary key, b number ); Primary keys can explicitely be named. The following create table statement creates a table with a primary key whose name is pk_name. create table ri_primary_key_1 ( a number, b number, c number, constraint pk_name primary key (a, b) );

FOREIGN KEY
A foreign key constraint (also called referential integrity constraint) on a column ensures that the value in that column is found in the primary key of another table. If a table has a foreign key that references a table, that referenced table can be dropped with a drop table .. cascade constraints. It is not possible to establish a foreign key on a global temporary table. If tried, Oracle issues a ORA-14455: attempt to create referential integrity constraint on temporary table. Check A check constraint allows to state a minimum requirement for the value in a column. If more complicated requirements are desired, an insert trigger must be used. The following table allows only numbers that are between 0 and 100 in the column a; create table ri_check_1 ( a number check (a between 0 and 100), b number ); Check constraints can be added after a table had been created: alter table ri_check_1 add constraint ch_b check (b > 50); It is also possible to state a check constraint that check the value of more than one column. The following example makes sure that the value of begin_ is smaller than the value of end_. create table ri_check_2 begin_ number, end_ number, value_ number, check (begin_ < end_) );

DEFAULT VALUES
A column can be assigned a default value. When a new row is created and no values are specified for some of the columns, the columns will be filled with their respective default values. A data manipulation command can 8

also request explicitly that a column be set to its default value, without knowing what this value is. (Details about data manipulation commands are in Chapter 3.) If no default value is declared explicitly, the null value is the default value. This usually makes sense because a null value can be thought to represent unknown data. In a table definition, default values are listed after the column data type. For example: CREATE TABLE products ( product_no integer PRIMARY KEY, name text, price numeric DEFAULT 9.99 ); The default value may be a scalar expression, which will be evaluated whenever the default value is inserted (not when the table is created).

ORDER BY (Clauses)
The syntax for an ORDER BY statement is as follows: SELECT "column_name" FROM "table_name" [WHERE "condition"] ORDER BY "column_name" [ASC, DESC] The [] means that the WHERE statement is optional. However, if a WHERE clause exists, it comes before the ORDER BY clause. ASC means that the results will be shown in ascending order, and DESC means that the results will be shown in descending order. If neither is specified, the default is ASC. It is possible to order by more than one column. In this case, the ORDER BY clause above becomes ORDER BY "column_name1" [ASC, DESC], "column_name2" [ASC, DESC] Assuming that we choose ascending order for both columns, the output will be ordered in ascending order according to column 1. If there is a tie for the value of column 1, we the sort in ascending order by column 2. For example, we may wish to list the contents of Table Store_Information by dollar amount, in descending order: we key in, SELECT store_name, Sales, Date FROM Store_Information ORDER BY Sales DESC Result: 9

store_name Los Angeles Boston

Sales Date $1500 Jan-05-1999 $700 JaExample

To drop the "Address" column in the "Person" table: ALTER TABLE Person DROP COLUMN Address Result: LastName Pettersen San Francisco San Diego FirstName City Kari n-08-1999 $300 Jan-08-1999 $250 Jan-07-1999

In addition to column name, we may also use column position (based on the SQL query) to indicate which column we want to apply the ORDER BY clause. The first column is 1, second column is 2, and so on. In the above example, we will achieve the same results by the following command: SELECT store_name, Sales, Date FROM Store_Information ORDER BY 2 DESC

GROUP BY
The GROUP BY keyword is used when we are selecting multiple columns from a table (or tables) and at least one arithmetic operator appears in the SELECT statement. When that happens, we need to GROUP BY all the other selected columns, i.e., all columns except the one(s) operated on by the arithmetic operator. SELECT "column_name1", SUM("column_name2") FROM "table_name" GROUP BY "column_name1" Let's illustrate using the following table, Table Store_Information store_name Sales Date Los Angeles $1500 Jan-05-1999 San Diego $250 Jan-07-1999 Los Angeles $300 Jan-08-1999 Boston $700 Jan-08-1999 We want to find total sales for each store. To do so, we would key in, SELECT store_name, SUM(Sales) FROM Store_Information 10

GROUP BY store_name Result: store_name Los Angeles San Diego Boston> SUM(Sales) $1800 $250 $700

11

JOIN
JOIN operation
The JOIN operations, which are among the possible Table Expressions in a FROM clause, perform joins between two tables. (You can also perform a join between two tables using an explicit equality test in a WHERE clause, such as "WHERE t1.col1 = t2.col2".) Syntax
JOIN operation

The JOIN operations are:

INNER JOIN

Specifies a join between two tables with an explicit join clause. See INNER JOIN .

LEFT OUTER JOIN

Specifies a join between two tables with an explicit join clause, preserving unmatched rows from the first table. See LEFT OUTER JOIN.

RIGHT OUTER JOIN

Specifies a join between two tables with an explicit join clause, preserving unmatched rows from the second table. See RIGHT OUTER JOIN. In all cases, you can specify additional restrictions on one or both of the tables being joined in outer join clauses or in the WHERE clause.

INNER JOIN
An INNER JOIN is a JOIN operation that allows you to specify an explicit join clause. Syntax
TableExpression [ INNER ] JOIN TableExpression { ON booleanExpression } }

12

You can specify the join clause by specifying ON with a boolean expression. The scope of expressions in the ON clause includes the current tables and any tables in outer query blocks to the current SELECT. In the following example, the ON clause refers to the current tables:
SELECT * FROM SAMP.EMPLOYEE INNER JOIN SAMP.STAFF` ON EMPLOYEE.SALARY < STAFF.SALARY;

The ON clause can reference tables not being joined and does not have to reference either of the tables being joined (though typically it does). Examples
-- Join the EMP_ACT and EMPLOYEE tables -- select all the columns from the EMP_ACT table and -- add the employee's surname (LASTNAME) from the EMPLOYEE table -- to each row of the result SELECT SAMP.EMP_ACT.*, LASTNAME FROM SAMP.EMP_ACT JOIN SAMP.EMPLOYEE ON EMP_ACT.EMPNO = EMPLOYEE.EMPNO; -- Join the EMPLOYEE and DEPARTMENT tables, -- select the employee number (EMPNO), -- employee surname (LASTNAME), -- department number (WORKDEPT in the EMPLOYEE table and DEPTNO in the -- DEPARTMENT table) -- and department name (DEPTNAME) -- of all employees who were born (BIRTHDATE) earlier than 1930. SELECT EMPNO, LASTNAME, WORKDEPT, DEPTNAME FROM SAMP.EMPLOYEE JOIN SAMP.DEPARTMENT ON WORKDEPT = DEPTNO AND YEAR(BIRTHDATE) < 1930; -- Another example of "generating" new data values, -- using a query which selects from a VALUES clause (which is an -- alternate form of a fullselect). -- This query shows how a table can be derived called "X" -- having 2 columns "R1" and "R2" and 1 row of data SELECT * FROM (VALUES (3, 4), (1, 5), (2, 6)) AS VALUESTABLE1(C1, C2) JOIN (VALUES (3, 2), (1, 2), (0, 3)) AS VALUESTABLE2(c1, c2) ON VALUESTABLE1.c1 = VALUESTABLE2.c1; This results in: C1 |C2 |C1 |2 ----------------------------------------------3 |4 |3 |2 1 |5 |1 |2 -- List every department with the employee number and -- last name of the manager SELECT DEPTNO, DEPTNAME, EMPNO, LASTNAME FROM DEPARTMENT INNER JOIN EMPLOYEE ON MGRNO = EMPNO; -- List every employee number and last name -- with the employee number and last name of their manager

13

SELECT E.EMPNO, E.LASTNAME, M.EMPNO, M.LASTNAME FROM EMPLOYEE E INNER JOIN DEPARTMENT INNER JOIN EMPLOYEE M ON MGRNO = M.EMPNO ON E.WORKDEPT = DEPTNO;

LEFT OUTER JOIN


A LEFT OUTER JOIN is one of the JOIN operations that allow you to specify a join clause. It preserves the unmatched rows from the first (left) table, joining them with a NULL row in the shape of the second (right) table. Syntax
TableExpression LEFT [ OUTER ] JOIN TableExpression { ON booleanExpression }

The scope of expressions in either the ON clause includes the current tables and any tables in query blocks outer to the current SELECT. The ON clause can reference tables not being joined and does not have to reference either of the tables being joined (though typically it does). Examples
--match cities to countries SELECT CITIES.COUNTRY, REGION FROM Countries LEFT OUTER JOIN Cities ON CITY_ID=CITY_ID WHERE REGION = 'Asia'; -- use the synonymous syntax, RIGHT JOIN, to achieve exactly -- the same results as in the example above SELECT COUNTRIES.COUNTRY, REGION FROM Countries LEFT JOIN Cities ON CITY_ID=CITY_ID; -- Join the EMPLOYEE and DEPARTMENT tables, -- select the employee number (EMPNO), -- employee surname (LASTNAME), -- department number (WORKDEPT in the EMPLOYEE table -- and DEPTNO in the DEPARTMENT table) -- and department name (DEPTNAME) -- of all employees who were born (BIRTHDATE) earlier than 1930 SELECT EMPNO, LASTNAME, WORKDEPT, DEPTNAME FROM SAMP.EMPLOYEE LEFT OUTER JOIN SAMP.DEPARTMENT ON WORKDEPT = DEPTNO AND YEAR(BIRTHDATE) < 1930; -- List every department with the employee number and -- last name of the manager, -- including departments without a manager SELECT DEPTNO, DEPTNAME, EMPNO, LASTNAME FROM DEPARTMENT LEFT OUTER JOIN EMPLOYEE ON MGRNO = EMPNO;

14

RIGHT OUTER JOIN


A RIGHT OUTER JOIN is one of the JOIN operations that allow you to specify a JOIN clause. It preserves the unmatched rows from the second (right) table, joining them with a NULL in the shape of the first (left) table. A LEFT OUTER JOIN B is equivalent to B RIGHT OUTER JOIN A, with the columns in a different order. Syntax
TableExpression RIGHT [ OUTER ] JOIN TableExpression { ON booleanExpression }

The scope of expressions in the ON clause includes the current tables and any tables in query blocks outer to the current SELECT. The ON clause can reference tables not being joined and does not have to reference either of the tables being joined (though typically it does). Examples
-- get all countries and corresponding cities, including -- countries without any cities SELECT CITY_NAME, CITIES.COUNTRY FROM CITIES RIGHT OUTER JOIN COUNTRIES ON CITIES.COUNTRY_ISO_CODE = COUNTRIES.COUNTRY_ISO_CODE; -- get all countries in Africa and corresponding cities, including -- countries without any cities SELECT CITY_NAME, CITIES.COUNTRY FROM CITIES RIGHT OUTER JOIN COUNTRIES ON CITIES.COUNTRY_ISO_CODE = COUNTRIES.COUNTRY_ISO_CODE; WHERE Countries.region = 'frica'; -- use the synonymous syntax, RIGHT JOIN, to achieve exactly -- the same results as in the example above SELECT CITY_NAME, CITIES.COUNTRY FROM CITIES RIGHT JOIN COUNTRIES ON CITIES.COUNTRY_ISO_CODE = COUNTRIES.COUNTRY_ISO_CODE WHERE Countries.region = 'Africa'; -- a TableExpression can be a joinOperation. Therefore -- you can have multiple join operations in a FROM clause -- List every employee number and last name -- with the employee number and last name of their manager SELECT E.EMPNO, E.LASTNAME, M.EMPNO, M.LASTNAME FROM EMPLOYEE E RIGHT OUTER JOIN DEPARTMENT RIGHT OUTER JOIN EMPLOYEE M ON MGRNO = M.EMPNO ON E.WORKDEPT = DEPTNO;

15

SQL Subqueries
It is possible to embed a SQL statement within another. When this is done on the WHERE or the HAVING statements, we have a sub-query construct. Syntax: SELECT "column_name1" FROM "table_name1" WHERE "column_name2" [Comparison Operator] (SELECT "column_name3" FROM "table_name2" WHERE [Condition]) [Comparison Operator] could be equality operators such as =, >, <, >=, <=. It can also be a text operator such as "LIKE." Example: Store_Information store_name Los Angeles San Diego Los Angeles Boston Geography region_name East East West West Sales $1500 $250 $300 $700 Date Jan-05-1999 Jan-07-1999 Jan-08-1999 Jan-08-1999

store_name Boston New York Los Angeles San Diego

Query: Find the sales of all stores in the West region. SELECT SUM(Sales) FROM Store_Information WHERE Store_name IN (SELECT store_name FROM Geography WHERE region_name = 'West') 16

Result: SUM(Sales) 2050 In this example, instead of joining the two tables directly and then adding up only the sales amount for stores in the West region, we first use the subquery to find out which stores are in the West region, and then we sum up the sales amount for these stores. User-Defined Variables You can store a value in a user-defined variable and then refer to it later. This enables you to pass values from one statement to another. User-defined variables are connection-specific. That is, a user variable defined by one client cannot be seen or used by other clients. All variables for a given client connection are automatically freed when that client exits. User variables are written as @var_name, where the variable name var_name may consist of alphanumeric characters from the current character set, ., _, and $. The default character set is latin1 (cp1252 West European). This may be changed with the --default-character-set option to mysqld. See Section 5.11.1, The Character Set Used for Data and Sorting. A user variable name can contain other characters if you quote it as a string or identifier (for example, @'my-var', @"my-var", or @`my-var`). Note: User variable names are case sensitive before MySQL 5.0 and not case sensitive in MySQL 5.0 and up. Syntax: One way to set a user-defined variable is by issuing a SET statement: SET @var_name = expr [, @var_name = expr] ... For SET, either = or := can be used as the assignment operator. The expr assigned to each variable can evaluate to an integer, real, string, or NULL value. However, if the value of the variable is selected in a result set, it is returned to the client as a string. You can also assign a value to a user variable in statements other than SET. In this case, the assignment operator must be := and not = because = is treated as a comparison operator in non-SET statements. Example: mysql> SET @t1=0, @t2=0, @t3=0; mysql> SELECT @t1:=(@t2:=1)+@t3:=4,@t1,@t2,@t3; +----------------------+------+------+------+ | @t1:=(@t2:=1)+@t3:=4 | @t1 | @t2 | @t3 | +----------------------+------+------+------+ | 5| 5| 1| 4| +----------------------+------+------+------+ -----------------------------------------------------------------------------------------------------------

Index
An index is a performance-tuning method of allowing faster retrieval of records. An index 17

creates an entry for each value that appears in the indexed columns. By default, Oracle creates B-tree indexes. Create an Index: syntax: CREATE [UNIQUE] INDEX index_name ON table_name (column1, column2, . column_n) [ COMPUTE STATISTICS ]; UNIQUE indicates that the combination of values in the indexed columns must be unique. COMPUTE STATISTICS tells Oracle to collect statistics during the creation of the index. The statistics are then used by the optimizer to choose a "plan of execution" when SQL statements are executed. example: CREATE INDEX supplier_idx ON supplier (supplier_name); In this example, we've created an index on the supplier table called supplier_idx. It consists of only one field - the supplier_name field. We could also create an index with more than one field as in the example below: CREATE INDEX supplier_idx ON supplier (supplier_name, city); We could also choose to collect statistics upon creation of the index as follows: CREATE INDEX supplier_idx ON supplier (supplier_name, city) COMPUTE STATISTICS;

DROP INDEX statement DROP INDEX removes the specified index. Syntax
DROP INDEX index-Name

Examples
DROP INDEX OrigIndex DROP INDEX DestIndex

DROP DATABASE 18

Syntax DROP {DATABASE | SCHEMA} [IF EXISTS] db_name DROP DATABASE drops all tables in the database and deletes the database. Be very careful with this statement! To use DROP DATABASE, you need the DROP privilege on the database. DROP SCHEMA is a synonym for DROP DATABASE as of MySQL 5.0.2. Important: When a database is dropped, user privileges on the database are not automatically dropped. See Section 13.5.1.3, GRANT Syntax. IF EXISTS is used to prevent an error from occurring if the database does not exist. If you use DROP DATABASE on a symbolically linked database, both the link and the original database are deleted. DROP DATABASE returns the number of tables that were removed. This corresponds to the number of .frm files removed.

19

ASSIGNMENT # 1
1. Table creation
Write a query to create a table student with following attributes: - name , character type , size-10 - roll_no, numeric type, size-3 - branch character type, size-10
Query: SQL> create table student ( name varchar2(10), roll_no number(3), branch varchar2(10) ); Output: Table created.

2. Adding data into tables


Add data to all the attributes in the order mentioned during table creation: add a record in student table
a. Query: SQL> insert into student values('Anjali',101,'IT'); 20

Output: 1 row created.

Add data to all the attributes in the different order: add a record in studnt table
b. Query: SQL> insert into student(roll_no,branch,name) values(102,'IT','Sanjay'); Output: 1 row created

Add data to few attributes: add a record to student table (only to roll number and name)
c. Query: SQL> insert into student(roll_no,name) values(103,'John'); Output: 1 row created.

3. Adding multiple rows using one query


Add multiple rows to student table using one query:
Query: SQL> insert into student values('&name',&roll,'&branch'); Enter value for name: Smith Enter value for roll: 104 Enter value for branch: IT old 1: insert into student values('&name',&roll,'&branch') new 1: insert into student values('Smith',104,'IT') Output: 1 row created. SQL> / Enter value for name: Siya Enter value for roll: 201 Enter value for branch: CSE old 1: insert into student values('&name',&roll,'&branch') new 1: insert into student values('Siya',201,'CSE') 21

Output: 1 row created. SQL> / Enter value for name: Amit Enter value for roll: 202 Enter value for branch: CSE old 1: insert into student values('&name',&roll,'&branch') new 1: insert into student values('Amit',202,'CSE') Output: 1 row created. SQL> / Enter value for name: tripti Enter value for roll: 203 Enter value for branch: CSE old 1: insert into student values('&name',&roll,'&branch') new 1: insert into student values('tripti',203,'CSE') Output: 1 row created. SQL> / Enter value for name: tripti Enter value for roll: 203 Enter value for branch: CSE old 1: insert into student values('&name',&roll,'&branch') new 1: insert into student values('tripti',203,'CSE') Output: 1 row created.

4. Viewing data of a table


a. All columns and all rows to view all the details of all the students from student table
Query: SQL> select * from student; Output: NAME ---------ROLL_NO ---------BRANCH ---------22

Anjali Sanjay John Smith Siya Amit tripti tripti

101 102 103 104 201 202 203 203

IT IT IT CSE CSE CSE CSE

8 rows selected.

b. All columns and selected rows to view all the details of all the students in IT branch from student table
Query: SQL> select * from student where branch='IT'; Output: NAME ---------Anjali Sanjay Smith ROLL_NO ---------101 102 104 BRANCH ---------IT IT IT

c. Selected columns and all rows to view roll number and name of all the students from student table
Query: SQL> select roll_no, name from student; Output: ROLL_NO ---------101 102 103 104 201 202 203 203 8 rows selected. NAME ---------Anjali Sanjay John Smith Siya Amit tripti tripti

d. Selected columns and selected rows to view roll number and name of all the students in IT branch from student table
Query: 23

SQL> select roll_no, name from student where branch='IT'; Output: ROLL_NO ---------101 102 104 NAME ---------Anjali Sanjay Smith

5. Eliminating duplicate rows when using select statement :


To view the distinct branch names from student table
Query: SQL> select distinct(branch) from student; Output: BRANCH ---------IT CSE

6.

To view the data in sorted form

a. Sorted in ascending order to view the details of all the students order by name in ascending order:
Query: SQL> select * from student order by name; Output: NAME ROLL_NO ---------- ---------Amit 202 Anjali 101 John 103 Sanjay 102 Siya 201 Smith 104 tripti 203 tripti 203 BRANCH ---------CSE IT IT CSE IT CSE CSE 24

8 rows selected.

OR
Query: SQL> select * from student order by name asc; Output: NAME ROLL_NO ---------- ---------Amit 202 Anjali 101 John 103 Sanjay 102 Siya 201 Smith 104 tripti 203 tripti 203 8 rows selected. BRANCH ---------CSE IT IT CSE IT CSE CSE

b. Sorted in descending order to view the details of all the students order by name in ascending order:
Query: SQL> select * from student order by name desc; Output: NAME ROLL_NO ---------- ---------tripti 203 tripti 203 Smith 104 Siya 201 Sanjay 102 John 103 Anjali 101 Amit 202 8 rows selected. BRANCH ---------CSE CSE IT CSE IT IT CSE

7.

Creating a table from an existing table :

Create a table student1 from student table with following attributes: - sname - sroll
25

- sbranch:
Query: SQL> create table student1(sname,sroll,sbranch) as select name,roll_no, branch from student; Output: Table created. Note: The above query automatically set the datatype and size of different attributes as of the existing tables attributes and this query also copies the contents of the student (if any) to student1 table.

8.

Adding data into a table from an existing table

First create a table student2 with following attributes: - s_name character type, size-10, - s_roll numeric type, size-3, - s_branch character type, size 10 After creating this table copy the data from existing table as follows:
Query: SQL> create table student2 ( s_name varchar2(10), s_roll number(3), s_branch varchar2(10) ); Output: Table created. Queryto add data from existing table: SQL> insert into student2 select name,roll_no,branch from student; Output: 8 rows created.

26

ASSIGNMENT # 2
1. Deleting records or rows from a table
a. Deleting few rows: Status before deletion
Query: SQL> select * from student2; Output: S_NAME S_ROLL S_BRANCH ------------------- ---------Anjali 101 IT Sanjay 102 IT John 103 Smith 104 IT Siya 201 CSE Amit 202 CSE tripti 203 CSE tripti 203 CSE 8 rows selected.

Delete query: delete all the details of roll number 101 from student2 table:
Query: SQL> delete from student2 where s_roll=101; Output: 1 row deleted.

Status after deletion


Query: SQL> select * from student2; Output: S_NAME ---------Sanjay John Smith Siya Amit tripti tripti S_ROLL ---------102 103 104 201 202 203 203 S_BRANCH ---------IT IT CSE CSE CSE CSE 27

7 rows selected.

b.

Deleting all the rows:

Status before deletion


Query: SQL> select * from student2; Output: S_NAME ---------Sanjay John Smith Siya Amit tripti tripti S_ROLL ---------102 103 104 201 202 203 203 S_BRANCH ---------IT IT CSE CSE CSE CSE

7 rows selected.

Delete query : to delete all the records of student 2 table


Query: SQL> delete from student2; Output: 7 rows deleted.

Status after deletion


Query: SQL> select * from student2; Output: no rows selected

2. Updating the contents of a table:


(a) Updation using where clause: update the name of a student from Riya to Siya in student table: Status of student table before updation:
Query: SQL> select * from student; Output: 28

NAME ---------Anjali Sanjay John Smith Siya Amit tripti tripti

ROLL_NO ---------101 102 103 104 201 202 203 203

BRANCH ---------IT IT IT CSE CSE CSE CSE

8 rows selected. Update query: SQL> update student set name='Riya' where name='Siya'; Output: 1 row updated.

Status of student table after updation


Query: SQL> select * from student; Output: NAME ---------Anjali Sanjay John Smith Riya Amit tripti tripti 8 rows selected. ROLL_NO ---------101 102 103 104 201 202 203 203 BRANCH ---------IT IT IT CSE CSE CSE CSE

Updation without where clause: Add 100 to roll number of all the students in student table:
(b)

Status of student table before updation:


Query: 29

SQL> select * from student; Output: NAME ---------Anjali Sanjay John Smith Riya Amit tripti tripti 8 rows selected. Update query: SQL> update student set roll_no=roll_no+100; Output: 8 rows updated. ROLL_NO ---------101 102 103 104 201 202 203 203 BRANCH ---------IT IT IT CSE CSE CSE CSE

Status of student table after updation:


Query: SQL> select * from student ; Output: NAME ---------Anjali Sanjay John Smith Riya Amit tripti tripti 8 rows selected. ROLL_NO ---------201 202 203 204 301 302 303 303 BRANCH ---------IT IT IT CSE CSE CSE CSE

3. Modifying the structure of a table

30

a. Adding new columns to a table: Add contact (numeric, size-10) to student table Status of student table before adding the new column
Query: SQL> select * from student ; Output: NAME ---------Anjali Sanjay John Smith Riya Amit tripti tripti 8 rows selected. Query to add new column: Query: SQL> alter table student add (contact number(10)); Output: Table altered. ROLL_NO ---------201 202 203 204 301 302 303 303 BRANCH ---------IT IT IT CSE CSE CSE CSE

Status of student table after adding new column


Query: SQL> select * from student ; Output: NAME ---------Anjali Sanjay John Smith Riya Amit tripti tripti ROLL_NO ---------201 202 203 204 301 302 303 303 BRANCH CONTACT ------------------IT IT IT CSE CSE CSE CSE 31

b. Deleting existing column of a table : delete the contact attribute from student table Status of student table before deleting contact attribute
Query: SQL> select * from student ; Output: NAME ---------Anjali Sanjay John Smith Riya Amit tripti tripti ROLL_NO ---------201 202 203 204 301 302 303 303 BRANCH CONTACT ------------------IT IT IT CSE CSE CSE CSE

8 rows selected. Query to delete contact column: SQL> alter table student drop column contact; Output: Table altered.

Status of student table after dropping the contact attribute:


Query: SQL> select * from student ; Output: NAME ---------Anjali Sanjay John Smith Riya Amit tripti tripti ROLL_NO ---------201 202 203 204 301 302 303 303 BRANCH ---------IT IT IT CSE CSE CSE CSE 32

8 rows selected.

c. Modifying the column datatype or size: change the branch attribute datatype from varchar2 to char and size from 10 to 12.
Query: SQL> alter table student modify (branch char(12)); Output: Table altered. Note: Alter command cannot do following: (i) change the name of a table (ii) change the name of a column (iii) decrease the size of a datatype if existing data contents are larger than the new size (iv) changing of non compatible datatypes if data exists.

4. Renaming a table:
Change the name of table student1 to s1:
Query: SQL> rename student1 to s1; Output: Table renamed.

5. Truncating a table :
Truncate table s1: Status of s1 before truncate command
Query: SQL> select * from s1; Output: SNAME SROLL ---------- ---------Anjali 101 Sanjay 102 John 103 Smith 104 Siya 201 SBRANCH ---------IT IT IT CSE 33

Amit tripti tripti

202 203 203

CSE CSE CSE

8 rows selected. Truncate query: SQL> truncate table s1; Output: Table truncated.

Status of s1 after truncate command


Query: SQL> select * from s1; Output: no rows selected Note: Truncate command is equivalent to the delete command in the sense that it deletes all the rows of a table but these commands are different. Difference between truncate command and delete command: (i) Truncate is combination of drop and automatically recreation of a table. (j) Truncate is DDL command whereas delete is DML command. (k) Truncate command does not return the number of rows deleted whereas delete command does. 6.

Destroying tables: destroy s1 table:

Query: SQL> drop table s1; Output: Table dropped.

7. Finding out the table/s created by a user


Query: SQL> select * from tab; Output: TNAME TABTYPE CLUSTERID ------------------------------ ------- ---------34

STUDENT STUDENT2 S S2 CUSTOMER 5 rows selected.

TABLE TABLE TABLE TABLE TABLE

8. Displaying the table structure:


Query: SQL> desc student; Output: Name Null? Type ----------------------------------------- -------- ---------------------------NAME ROLL_NO BRANCH VARCHAR2(10) NUMBER(3) CHAR(12)

OR
Query: SQL> describe student; Output: Name Null? Type ----------------------------------------- -------- ---------------------------NAME ROLL_NO BRANCH VARCHAR2(10) NUMBER(3) CHAR(12)

ASSIGNMENT # 3
DATA CONSTRAINTS:

Primary key Foreign key Unique Not null Check


35

I Setting constraints during the table creation


1. Primary key a.
Query: SQL> create table student ( roll_no number(3) primary key, name varchar2(10), branch varchar2(10) ); Output: Table created.

Primary key declaration at column level

b.
Query:

Primary key declaration at table level

SQL> create table student1 ( roll_no number(3), name varchar2(10), branch varchar2(10), primary key(roll_no) ); Output: Table created.

2. Foreign key a.
Query: SQL> create table result ( roll_no number(3) references student(roll_no), maths number(3), science number(3), english number(3) ); Output: 36

Foreign key declaration at column level

Table created.

b.
Query:

Foreign key declaration at table level

SQL> create table result1 ( roll_no number(3), maths number(3), science number(3), english number(3), foreign key(roll_no) references student1(roll_no) ); Output: Table created.

3. Unique constraint a.
Query: SQL> create table emp ( e_id varchar2(4) primary key, e_name varchar2(10), e_contact number(10) unique ); Output: Table created.

Unique constraint declaration at column level

b.
Query:

Unique constraint declaration at table level

SQL> create table emp1 ( e_id varchar2(4) primary key, e_name varchar2(10), e_contact number(10), unique(e_contact) ); Output: Table created. 37

4. Not null constraint (can only be declared at column level)

Not null constraint at column level


Query: SQL> create table emp2 ( e_id varchar2(4) primary key, e_name varchar2(10) not null, e_contact number(10) ); Output: Table created.

5. Check constraint a.
Query: SQL> create table emp3 ( e_id varchar2(4) primary key check(e_id like E%), e_name varchar2(10) not null check(e_name=upper(e_name)), e_deptt varchar2(3) check(deptt in(IT,CSE,EEE,ECE,MAE)) ); Output: Table created.

Check constraint declaration at column level

b.
Query:

Check constraint declaration at table level

SQL> create table emp4 ( e_id varchar2(4) primary key, e_name varchar2(10) not null, e_deptt varchar2(3), check(e_id like E%), check(e_name=upper(e_name)), check(deptt in(IT,CSE,EEE,ECE,MAE)) ); Output: Table created.

II. Naming the constraints during table creation


38

1. Assigning names to primary key, not null, unique, check at column level
Query: SQL> create table student ( roll number(3) constraint pk primary key, name varchar2(10) constraint ck check(name=initcap(name)), branch varchar2(10) constraint nn not null, contact number(10) constraint u unique ); Output: Table created.

2.
Query:

Assigning names to primary key, unique, check at table level

SQL> create table student1 ( roll number(3), name varchar2(10), branch varchar2(10), contact number(10), constraint pk1 primary key(roll), constraint ck1 check(name=initcap(name)), constraint u1 unique(contact) ); Output: Table created.

3.
Query:

Assigning name to foreign key at column level

SQL> create table result ( roll number(3) constraint fk references student(roll), maths number(3), science number(3), english number(3) ); Output: Table created.

4.
Query:

Assigning name to foreign key at table level

39

SQL> create table result1 ( roll number(3), maths number(3), science number(3), english number(3), constraint fk1 foreign key(roll)references student1(roll) ); Output: Table created.

III Setting constraints using alter command


First of all create tables student, student1, result,result1 as follows:
Query to create student table: SQL> create table student ( roll number(3), name varchar2(10), branch varchar2(10), contact number(10) ); Output: Table created. Query to create student1 table: SQL> create table student1 ( roll number(3), name varchar2(10), branch varchar2(10), contact number(10) ); Output: Table created. Query to create result table : SQL> create table result ( roll number(3), maths number(3), science number(3), english number(3) ); 40

Output: Table created. Query to create result1 table : SQL> create table result1 ( roll number(3), maths number(3), science number(3), english number(3) ); Table created.

1.
a. Query

Primary key, unique & check constraints Assigning constraint without name

SQL> alter table student add ( primary key(roll), check(name=upper(name)), unique(contact) ); Output: Table altered. b. Query SQL> alter table student1 add( constraint pk2 primary key(roll), 41

Adding constraint with name

constraint ck2 check(name=upper(name)), constraint u unique(contact) ); Output: Table altered.

2. Not null
a. Query SQL> alter table student modify (branch not null); Output: Table altered b. Query SQL> alter table student1 modify (branch constraint nn not null); Output: Table altered

Adding null constraint without name

Adding null constraint with name

3. Foreign key
a. Query SQL> alter table result add foreign key(roll) references student(roll); Output: Table altered b. Query SQL> alter table result1 add constraint fk2 foreign key(roll) references student(roll); Output: 42

Adding foreign keyconstraint without name

Adding foreign key constraint with name

Table altered Note: - Oracle will not allow constraints defined using the alter table to be applied to the table if data previously placed in the table violates such constraints. - If a primary key constraint was being applied to a table & the column has duplicate values in it, the primary key constraint will not be set to that column.

IV Dropping constraints
1. Foreign key

Dropping foreign key using constraint name


Query SQL> alter table result1 drop constraint fk2; Output: Table altered

2. a.
Query

Primary key Dropping primary key without using constraint name

SQL> alter table student drop primary key; Output: Table altered

b.
Query

Dropping primary key using constraint name

SQL> alter table student1 drop constraint pk2; Output: Table altered

3. a.
Query

Unique Dropping unique without using constraint name

SQL> alter table student drop unique(contact); 43

Output: Table altered

b.
Query

Dropping unique using constraint name

SQL> alter table student1 drop constraint u; Output: Table altered

4.

Check

Dropping check using constraint name


Query SQL> alter table student1 drop constraint ck2; Output: Table altered

5. a.
Query

Not null Dropping not null without using constraint name

SQL> alter table student modify(branch null); Output: Table altered

b.
Query

Dropping not null using constraint name

SQL> alter table student1 drop constraint nn ; Output: Table altered

44

ASSIGNMENT # 4
Create a table called 'EMPLOYEE' with the following structure: +--------------+-------------+------+-----+ | Field | Type | Null | Key | +--------------+-------------+------+-----+ | Emp_No | number(5) | NO | PRI | | Emp_Name | varchar(30) | YES | | | Designation | varchar(10) | YES | | | Date_of_Join | date | YES | | | Salary | float | YES | | | Dept_No | number(11) | YES | | +--------------+-------------+------+-----+ Create another table called 'DEPARTMENT' with the following structure: +-----------+----------------+ | Field | Type | +-----------+----------------+

45

| Dept_No | number(11)(PRI)| | Dept_Name | varchar(30) | | Dept_Loc | varchar(20) | +-----------+----------------+ Create another table called 'ALLOWANCE' with the following structure: +--------------+-------------+ | Field | Type | +--------------+-------------+ | Designation | varchar(10) | | Sp_Allowance | float | | Conveyance | float | +--------------+-------------+ Insert data into these tables as shown below: EMPLOYEE TABLE +--------+----------+-------------+--------------+--------+---------+ | Emp_No | Emp_Name | Designation | Date_of_Join | Salary | Dept_No | +--------+----------+-------------+--------------+--------+---------+ | 10001 | Robert | Officer | 01-dec-1985 | 1000 | 10 | | 10002 | Allan | Clerk | 14-may-1982 | 5000 | 10 | | 10003 | Martin | Manager | 23-dec-1984 | 3500 | 20 | | 10004 | James | Analyst | 22-jul-1990 | 5000 | 30 | | 10005 | John | Analyst | 22-jul-1990 | 4900 | 30 | | 10006 | Jones | Clerk | 16-apr-1986 | 950 | 30 | +--------+----------+-------------+--------------+--------+---------+

DEPARTMENT TABLE +---------+------------+----------+ | Dept_No | Dept_Name | Dept_Loc | +---------+------------+----------+ | 10 | Marketing | London | | 20 | Accounts | America | | 30 | Sales | New York | | 40 | Software | Boston | | 50 | Production | Boston | +---------+------------+----------+ ALLOWANCE TABLE +-------------+--------------+------------+ | Designation | Sp_Allowance | Conveyance | +-------------+--------------+------------+ | Manager | 1000 | 500 | | Officer | 800 | 400 |

46

| Analyst | 1200 | 500 | | Clerk | 500 | 300 | +-------------+--------------+------------+

Questions:
Q1. List the Employees belonging to department 20. Q2. List the Employees who are earning more than 1200 but less than 4000. Q3. List the Employees who have joined after 1st Jan 84 in the order of the joining date. Q4. List the Employees who are either in Officer or Manager position. Q5. List the Employees who are located at 'New York'. Q6. List the Employees who are in the Sales department. Q7. List the Departments that do not have any Employees. Q8. List the Employees who are earning more than the Robert. Q9. Find out how many employees are there in the organization. Q10. Find out how many employees are working in Sales department. Q11. Find out the total salaries paid to the Employees. Q12. What is the average salary paid to the Employees? Q13. What is the minimum salary paid in department 30? Q14. Display names and grades of Employees based on their designation. Designation Grade Manager A Officer B Analyst C Clerk D Q15. Display Employee names and date of join. Joining date should be displayed in the following format: 26, January 1998 Q16. Find out how long an employee has worked in the organization in terms of number of: - Year - Months - Days Q17. Display the total salaries department wise. Q18. Display the maximum salaries in each department. Along with the name of the department. The column headings should be like this: Dept_Name Max(sum) Q19. Display the total salary (salary + sp_allowance - conveyance) of each Employee in the order of total salary. Q20. Give the details of the employee with second highest salary. Q21. Display the details of those employees who earn greater than average of their

department.
Q22. Update the salaries of all employees in marketing department & hike it by 15%.

Solution of Assignment 4
SQL> create table employee (emp_no number(5), emp_name varchar(30), designation varchar(10), date_of_join date, dept_no number(11)); 47

Table created. SQL> alter table employee modify emp_no constraint pkey primary key; Table altered. SQL> desc employee Name Null? Type ----------------------------------------- -------- ---------------------------EMP_NO EMP_NAME DESIGNATION DATE_OF_JOIN DEPT_NO NOT NULL NUMBER(5) VARCHAR2(30) VARCHAR2(10) DATE NUMBER(11)

SQL> create table department (dept_no number(11) primary key, dept_name varchar(30), dept_loc varchar(20)); Table created. SQL> create table allowance (designation varchar(10), sp_allowance float, conveyance float); Table created. SQL> desc department; Name Null? Type ----------------------------------------- -------- ---------------------------DEPT_NO DEPT_NAME DEPT_LOC NOT NULL NUMBER(11) VARCHAR2(30) VARCHAR2(20)

SQL> desc allowance; Name Null? Type ----------------------------------------- -------- ---------------------------DESIGNATION SP_ALLOWANCE CONVEYANCE VARCHAR2(10) FLOAT(126) FLOAT(126)

SQL> alter table employee add salary float; Table altered. SQL> desc employee; Name Null? Type ----------------------------------------- -------- ---------------------------EMP_NO NOT NULL NUMBER(5) EMP_NAME VARCHAR2(30) DESIGNATION VARCHAR2(10) DATE_OF_JOIN DATE DEPT_NO NUMBER(11) SALARY FLOAT(126) SQL> insert into employee values(1001, 'robert', 'officer', '01-dec-1985',1000,10); 48

1 row created. SQL> insert into employee values(1002, 'allan', 'clerk', '14-may-1982',5000,10); 1 row created. SQL> insert into employee values(1003,'martin', 'manager', '23-dec-1984',3500,20); 1 row created. SQL> insert into employee values(1004,'james', 'analyst', '22-july-1990',5000,30); 1 row created. SQL> insert into employee values(1005,'john', 'analyst', '22-july-1990',4900,30); 1 row created. SQL> insert into employee values(1006,'jones', 'clerk', '16-apr-1986',950,30); 1 row created. SQL> select * from employee; EMP_NO EMP_NAME DESIGNATIO DATE_OF_J ---------- ------------------------------ ---------- --------- ---------SALARY ---------1001 robert officer 01-DEC-85 1000 10 1002 allan 10 clerk 14-MAY-82 5000 DEPT_NO

1003 martin manager 23-DEC-84 3500 20 EMP_NO EMP_NAME DESIGNATIO DATE_OF_J ---------- ------------------------------ ---------- --------- ---------SALARY ---------1004 james analyst 22-JUL-90 5000 30 1005 john 30 1006 jones 30 analyst clerk 22-JUL-90 16-APR-86 4900 950

DEPT_NO

6 rows selected. SQL> insert into department values(10,'marketing','london'); 1 row created. SQL> insert into department values(20,'account','america'); 1 row created. SQL> insert into department values(30,'sales','new york'); 1 row created. 49

SQL> insert into department values(40,'software','boston'); 1 row created. SQL> insert into department values(50,'production','boston'); 1 row created. SQL> select * from department; DEPT_NO DEPT_NAME DEPT_LOC --------- ------------------------------ -------------------10 marketing london 20 account america 30 sales new york 40 software boston 50 production boston SQL> insert into allowance values('manager',1000,500); 1 row created. SQL> insert into allowance values('officer',800,400); 1 row created. SQL> insert into allowance values('analyst',1200,500); 1 row created. SQL> insert into allowance values('clerk',500,300); 1 row created. SQL> select * from allowance; DESIGNATIO SP_ALLOWANCE CONVEYANCE ---------- ------------ ---------manager 1000 500 officer 800 400 analyst 1200 500 clerk 500 300 SQL> select * from employee where dept_no=20; EMP_NO EMP_NAME DESIGNATION DATE_OF_J ---------- ------------------------------ -------------------- --------SALARY DEPT_NO ---------- ---------1003 martin manager 23-DEC-84 3500 20 SQL> select * from employee where salary>1200 and salary<4000; EMP_NO EMP_NAME DESIGNATION DATE_OF_J ---------- ------------------------------ -------------------- --------SALARY DEPT_NO ---------- ---------1003 martin manager 23-DEC-84 3500 20 SQL> select * from employee where date_of_join>'01-jan-1984'; 50

EMP_NO EMP_NAME DESIGNATION ---------- ------------------------------ -------------------- --------SALARY DEPT_NO ---------- ---------1001 robert officer 01-DEC-85 1000 10 1003 martin 3500 20 manager 23-DEC-84

DATE_OF_J

1004 james analyst 22-JUL-90 5000 30 EMP_NO EMP_NAME DESIGNATION ---------- ------------------------------ -------------------- --------SALARY DEPT_NO ---------- ---------1005 john analyst 22-JUL-90 4900 30 1006 jones 950 30 clerk 16-APR-86

DATE_OF_J

SQL> select * from employee where designation='officer' or designation='manager'; EMP_NO EMP_NAME DESIGNATION DATE_OF_J ---------- ------------------------------ -------------------- --------SALARY DEPT_NO ---------- ---------1001 robert officer 01-DEC-85 1000 10 1003 martin 3500 20 manager 23-DEC-84

SQL> select * from employee, department where employee.dept_no=department.dept_n o and dept_loc='new york'; EMP_NO EMP_NAME DESIGNATION DATE_OF_J ---------- ------------------------------ -------------------- --------SALARY DEPT_NO DEPT_NO DEPT_NAME ---------- ---------- ---------- -----------------------------DEPT_LOC -------------------1004 james analyst 22-JUL-90 5000 30 30 sales new york 1005 john analyst 22-JUL-90 4900 30 30 sales new york EMP_NO EMP_NAME DESIGNATION ---------- ------------------------------ -------------------- --------SALARY DEPT_NO DEPT_NO DEPT_NAME ---------- ---------- ---------- -----------------------------51

DATE_OF_J

DEPT_LOC -------------------1006 jones 950 30 new york clerk 30 sales 16-APR-86

SQL> select * from employee, department where employee.dept_no=department.dept_n o and dept_name='sales'; EMP_NO EMP_NAME DESIGNATION DATE_OF_J ---------- ------------------------------ -------------------- --------SALARY DEPT_NO DEPT_NO DEPT_NAME ---------- ---------- ---------- -----------------------------DEPT_LOC -------------------1004 james analyst 22-JUL-90 5000 30 30 sales new york 1005 john analyst 22-JUL-90 4900 30 30 sales new york EMP_NO EMP_NAME DESIGNATION ---------- ------------------------------ -------------------- --------SALARY DEPT_NO DEPT_NO DEPT_NAME ---------- ---------- ---------- -----------------------------DEPT_LOC -------------------1006 jones 950 30 new york clerk 30 sales 16-APR-86

DATE_OF_J

SQL> select* from employee where salary>1000; EMP_NO EMP_NAME DESIGNATION DATE_OF_J ---------- ------------------------------ -------------------- --------SALARY DEPT_NO ---------- ---------1002 allan clerk 14-MAY-82 5000 10 1003 martin manager 23-DEC-84 3500 20 1004 james analyst 22-JUL-90 5000 30 EMP_NO EMP_NAME DESIGNATION ---------- ------------------------------ -------------------- --------SALARY DEPT_NO ---------- ---------1005 john analyst 22-JUL-90 4900 30 52

DATE_OF_J

SQL> select count(emp_no) from employee; COUNT(EMP_NO) ------------6 SQL> select count(emp_no) from employee,department where employee.dept_no=depart ment.dept_no and dept_name='sales'; COUNT(EMP_NO) ------------3 SQL> select sum(salary) from employee; SUM(SALARY) ----------20350 SQL> select avg(salary) from employee; AVG(SALARY) ----------3391.66667 SQL> select min(salary) from employee where dept_no=30; MIN(SALARY) ----------950 SQL> alter table employee add grade varchar(1); Table altered. SQL> update employee set grade=case 2 when designation='manager' then 'a' 3 when designation='officer' then 'b' 4 when designation='analyst' then 'c' 5 else 'd'end; 6 rows updated. SQL> select emp_name, grade from employee; EMP_NAME G ------------------------------ robert b allan d martin a james c john c jones d 6 rows selected. SQL> update employee set date_of_join='01, december 1985' where emp_no=1001; 1 row updated. 53

SQL> update employee set date_of_join='14, may 1982' where emp_no=1002; 1 row updated. SQL> update employee set date_of_join='23, december 1984' where emp_no=1003; 1 row updated. SQL> update employee set date_of_join='22, july 1990' where emp_no=1004; 1 row updated. SQL> update employee set date_of_join='22, july 1990' where emp_no=1005; 1 row updated. SQL> update employee set date_of_join='22, april 1990' where emp_no=1006; 1 row updated. SQL> select emp_name, date_of_join from employee; EMP_NAME DATE_OF_J ------------------------------ --------robert 01-DEC-85 allan 14-MAY-82 martin 23-DEC-84 james 22-JUL-90 john 22-JUL-90 jones 22-APR-90 6 rows selected. SQL> select dept_name , sum(salary) from employee, department where employee.dep t_no=department.dept_no group by dept_name; DEPT_NAME SUM(SALARY) ------------------------------ ----------account 3500 sales 10850 marketing 6000 SQL> select dept_name , max(salary) from employee, department where employee.dep t_no=department.dept_no group by dept_name; DEPT_NAME MAX(SALARY) ------------------------------ ----------account 3500 sales 5000 marketing 5000 SQL> select sum(salary + sp_allowance - conveyance) from employee, allowance wh ere employee.designation=allowance.designation group by emp_no; SUM(SALARY+SP_ALLOWANCE-CONVEYANCE) ----------------------------------4000 1150 1400 5200 5700 5600 54

6 rows selected. SQL> update employee set salary=salary*1.15 where dept_no=10; 2 rows updated. SQL> select salary,emp_name from employee, department where department.dept_no=e mployee.dept_no and dept_name='marketing'; SALARY EMP_NAME ---------- -----------------------------1150 robert 5750 allan

Assignment-5 (Based on constraints,join and groupby clause) Publisher(pub_id varchar(6) primary key,pub_name varchar(10) not null,contact_no char(12),address varchar(50)) Book(book_id char(6) primary key, pub_id char(6),title varchar(25) not null,category varchar(20),price number(10)) Student(student_id varchar(6) primary key, name varchar(10) not null,department varchar(10),semester varchar(5),contact_no char(12)) Author(auth_id char(6) primary key,auth_name varchar(10) not null,contact_no char(12),address varchar(50)) Issue(book_id char(6),student_id char(6),issue_date char(10) not null,return_date char(10),finenumber(10)) Writes((book_id char (6),auth_id char(6))primary key,foreign key(book_id) refernces book,foreign key(auth_id)references author); Answer the following queries based on above table. 1. 2. 3. 4. List the details of authors of the book DBMS. List the details of book which are currently issued to student with idST-04. List details of all books which have been issued to student with id ST-01 yet. List the books which are not in library (issued to students).Also give the details of students to whom these book are issued. List the students who are having more than one book. 5. List the details of students who issued the book from library with book id BK-03. 6. Find out publication of which library is having maximum numbers of books.

55

DBMS VIVA QUESTION WITH ANSWERS 1. What is database? A database is a logically coherent collection of data with some inherent meaning, representing some aspect of real world and which is designed, built and populated with data for a specific purpose. 2. What is DBMS? It is a collection of programs that enables user to create and maintain a database. In other words it is general-purpose software that provides the users with the processes of defining, constructing and manipulating the database for various applications. 3. What is a Database system? The database and DBMS software together is called as Database system. 4. What are the advantages of DBMS? 1. 2. 3. 4. 5. Redundancy is controlled. Unauthorised access is restricted. Providing multiple user interfaces. Enforcing integrity constraints. Providing backup and recovery.

5. What are the disadvantage in File Processing System? 1. 2. 3. 4. 5. 6. Data redundancy and inconsistency. Difficult in accessing data. Data isolation. Data integrity. Concurrent access is not possible. Security Problems.

56

6. Describe the three levels of data abstraction? The are three levels of abstraction:

1. 2. 3.

Physical level: The lowest level of abstraction describes how data are stored. Logical level: The next higher level of abstraction, describes what data are stored in database and what relationship among those data. View level: The highest level of abstraction describes only part of entire database.

7. Define the "integrity rules"? There are two Integrity rules.

1. 2.

Entity Integrity: States that "Primary key cannot have NULL value" Referential Integrity: States that "Foreign Key can be either a NULL value or should be Primary Key value of other relation.

8. What is extension and intension?

1. 2.

Extension: It is the number of tuples present in a table at any instance. This is time dependent. Intension: It is a constant value that gives the name, structure of table and the constraints laid on it.

9. What is System R? What are its two major subsystems? System R was designed and developed over a period of 1974-79 at IBM San Jose Research Center. It is a prototype and its purpose was to demonstrate that it is possible to build a Relational System that can be used in a real life environment to solve real life problems, with performance at least comparable to that of existing system. Its two subsystems are 1. 2. Research Storage System Relational Data System.

10. How is the data structure of System R different from the relational structure? Unlike Relational systems in System R 1. 2. 3. 4. Domains are not supported Enforcement of candidate key uniqueness is optional Enforcement of entity integrity is optional Referential integrity is not enforced

11. What is Data Independence? Data independence means that "the application is independent of the storage structure and access strategy of data". In other words, The ability to modify the schema definition in one level should not affect the schema definition in the next higher level. Two types of Data Independence:

57

1. 2.

Physical Data Independence: Modification in physical level should not affect the logical level. Logical Data Independence: Modification in logical level should affect the view level.

NOTE: Logical Data Independence is more difficult to achieve 12. What is a view? How it is related to data independence? A view may be thought of as a virtual table, that is, a table that does not really exist in its own right but is instead derived from one or more underlying base table. In other words, there is no stored file that direct represents the view instead a definition of view is stored in data dictionary. Growth and restructuring of base tables is not reflected in views. Thus the view can insulate users from the effects of restructuring and growth in the database. Hence accounts for logical data independence. 13. What is Data Model? A collection of conceptual tools for describing data, data relationships data semantics and constraints. 14. What is E-R model? This data model is based on real world that consists of basic objects called entities and of relationship among these objects. Entities are described in a database by a set of attributes. 15. What is Object Oriented model? This model is based on collection of objects. An object contains values stored in instance variables with in the object. An object also contains bodies of code that operate on the object. These bodies of code are called methods. Objects that contain same types of values and the same methods are grouped together into classes. 16. What is an Entity? It is a 'thing' in the real world with an independent existence. 17. What is an Entity type? It is a collection (set) of entities that have same attributes. 18. What is an Entity set? It is a collection of all entities of particular entity type in the database. 19. What is an Extension of entity type? The collections of entities of a particular entity type are grouped together into an entity set. 20. What is Weak Entity set? An entity set may not have sufficient attributes to form a primary key, and its primary key compromises of its partial key and primary key of its parent entity, then it is said to be Weak Entity set. 21. What is an attribute? It is a particular property, which describes the entity. 22. What is a Relation Schema and a Relation?

58

A relation Schema denoted by R(A1, A2, ..., An) is made up of the relation name R and the list of attributes Ai that it contains. A relation is defined as a set of tuples. Let r be the relation which contains set tuples (t1, t2, t3, ..., tn). Each tuple is an ordered list of n-values t=(v1,v2, ..., vn). 23. What is degree of a Relation? It is the number of attribute of its relation schema. 24. What is Relationship? It is an association among two or more entities.

25. What is Relationship set? The collection (or set) of similar relationships. 26. What is Relationship type? Relationship type defines a set of associations or a relationship set among a given set of entity types. 27. What is degree of Relationship type? It is the number of entity type participating. 28. What is DDL (Data Definition Language)? A data base schema is specifies by a set of definitions expressed by a special language called DDL. 29. What is VDL (View Definition Language)? It specifies user views and their mappings to the conceptual schema. 30. What is SDL (Storage Definition Language)? This language is to specify the internal schema. This language may specify the mapping between two schemas. 31. What is Data Storage - Definition Language? The storage structures and access methods used by database system are specified by a set of definition in a special type of DDL called data storage-definition language. 32. What is DML (Data Manipulation Language)? This language that enable user to access or manipulate data as organised by appropriate data model.

1. 2.

Procedural DML or Low level: DML requires a user to specify what data are needed and how to get those data. Non-Procedural DML or High level: DML requires a user to specify what data are needed without specifying how to get those data.

33. What is DML Compiler? It translates DML statements in a query language into low-level instruction that the query evaluation engine can understand.

59

34. What is Query evaluation engine? It executes low-level instruction generated by compiler. 35. What is DDL Interpreter? It interprets DDL statements and record them in tables containing metadata. 36. What is Record-at-a-time? The Low level or Procedural DML can specify and retrieve each record from a set of records. This retrieve of a record is said to be Record-at-a-time. 31. What is Data Storage - Definition Language? The storage structures and access methods used by database system are specified by a set of definition in a special type of DDL called data storage-definition language. 32. What is DML (Data Manipulation Language)? This language that enable user to access or manipulate data as organised by appropriate data model.

1. 2.

Procedural DML or Low level: DML requires a user to specify what data are needed and how to get those data. Non-Procedural DML or High level: DML requires a user to specify what data are needed without specifying how to get those data.

33. What is DML Compiler? It translates DML statements in a query language into low-level instruction that the query evaluation engine can understand. 34. What is Query evaluation engine? It executes low-level instruction generated by compiler. 35. What is DDL Interpreter? It interprets DDL statements and record them in tables containing metadata. 36. What is Record-at-a-time? The Low level or Procedural DML can specify and retrieve each record from a set of records. This retrieve of a record is said to be Record-at-a-time.

43. What is Lossless join property? It guarantees that the spurious tuple generation does not occur with respect to relation schemas after decomposition. 44. What is 1 NF (Normal Form)? The domain of attribute must include only atomic (simple, indivisible) values. 45. What is Fully Functional dependency?

60

It is based on concept of full functional dependency. A functional dependency X Y is full functional dependency if removal of any attribute A from X means that the dependency does not hold any more. 46. What is 2NF? A relation schema R is in 2NF if it is in 1NF and every non-prime attribute A in R is fully functionally dependent on primary key. 47. What is 3NF? A relation schema R is in 3NF if it is in 2NF and for every FD X A either of the following is true 1. 2. X is a Super-key of R. A is a prime attribute of R.

In other words, if every non prime attribute is non-transitively dependent on primary key. 48. What is BCNF (Boyce-Codd Normal Form)? A relation schema R is in BCNF if it is in 3NF and satisfies an additional constraint that for every FD X A, X must be a candidate key. 49. What is 4NF? A relation schema R is said to be in 4NF if for every Multivalued dependency X Y that holds over R, one of following is true. 1.) X is subset or equal to (or) XY = R. 2.) X is a super key. 50. What is 5NF? A Relation schema R is said to be 5NF if for every join dependency {R1, R2, ..., Rn} that holds R, one the following is true 1.) Ri = R for some i. 2.) The join dependency is implied by the set of FD, over R in which the left side is key of R. 51. What is Domain-Key Normal Form? A relation is said to be in DKNF if all constraints and dependencies that should hold on the the constraint can be enforced by simply enforcing the domain constraint and key constraint on the relation. 52. What are partial, alternate,, artificial, compound and natural key?

1. 2. 3. 4. 5.

Partial Key: It is a set of attributes that can uniquely identify weak entities and that are related to same owner entity. It is sometime called as Discriminator. Alternate Key: All Candidate Keys excluding the Primary Key are known as Alternate Keys. Artificial Key: If no obvious key, either stand alone or compound is available, then the last resort is to simply create a key, by assigning a unique number to each record or occurrence. Then this is known as developing an artificial key. Compound Key: If no single data element uniquely identifies occurrences within a construct, then combining multiple elements to create a unique identifier for the construct is known as creating a compound key. Natural Key: When one of the data elements stored within a construct is utilized as the primary key, then it is called the natural key.

53. What is indexing and what are the different kinds of indexing?

61

Indexing is a technique for determining how quickly specific data can be found. Types: 1. 2. 3. 4. 5. Binary search style indexing B-Tree indexing Inverted list indexing Memory resident table Table indexing

54. What is system catalog or catalog relation? How is better known as? A RDBMS maintains a description of all the data that it contains, information about every relation and index that it contains. This information is stored in a collection of relations maintained by the system called metadata. It is also called data dictionary. 55. What is meant by query optimization? The phase that identifies an efficient execution plan for evaluating a query that has the least estimated cost is referred to as query optimization. 56. What is durability in DBMS? Once the DBMS informs the user that a transaction has successfully completed, its effects should persist even if the system crashes before all its changes are reflected on disk. This property is called durability. 57. What do you mean by atomicity and aggregation?

1. 2.

Atomicity: Either all actions are carried out or none are. Users should not have to worry about the effect of incomplete transactions. DBMS ensures this by undoing the actions of incomplete transactions. Aggregation: A concept which is used to model a relationship between a collection of entities and relationships. It is used when we need to express a relationship among relationships.

58. What is a Phantom Deadlock? In distributed deadlock detection, the delay in propagating local information might cause the deadlock detection algorithms to identify deadlocks that do not really exist. Such situations are called phantom deadlocks and they lead to unnecessary aborts. 59. What is a checkpoint and When does it occur? A Checkpoint is like a snapshot of the DBMS state. By taking checkpoints, the DBMS can reduce the amount of work to be done during restart in the event of subsequent crashes. 60. What are the different phases of transaction? Different phases are 1.) Analysis phase, 2.) Redo Phase, 3.) Undo phase. 61. What do you mean by flat file database? It is a database in which there are no programs or user access languages. It has no cross-file capabilities but is user-friendly and provides user-interface management. 62. What is "transparent DBMS"? It is one, which keeps its Physical Structure hidden from user.

62

63. What is a query? A query with respect to DBMS relates to user commands that are used to interact with a data base. The query language can be classified into data definition language and data manipulation language. 64. What do you mean by Correlated subquery? Subqueries, or nested queries, are used to bring back a set of rows to be used by the parent query. Depending on how the subquery is written, it can be executed once for the parent query or it can be executed once for each row returned by the parent query. If the subquery is executed for each row of the parent, this is called a correlated subquery. A correlated subquery can be easily identified if it contains any references to the parent subquery columns in its WHERE clause. Columns from the subquery cannot be referenced anywhere else in the parent query. The following example demonstrates a non-correlated subquery. Example: Select * From CUST Where '10/03/1990' IN (Select ODATE From ORDER

Where CUST.CNUM = ORDER.CNUM)


65. What are the primitive operations common to all record management systems? Addition, deletion and modification. 66. Name the buffer in which all the commands that are typed in are stored? 'Edit' Buffer. 67. What are the unary operations in Relational Algebra? PROJECTION and SELECTION. 68. Are the resulting relations of PRODUCT and JOIN operation the same? No. PRODUCT: Concatenation of every row in one relation with every row in another. JOIN: Concatenation of rows from one relation and related rows from another. 69. What is RDBMS KERNEL? Two important pieces of RDBMS architecture are the kernel, which is the software, and the data dictionary, which consists of the system-level data structures used by the kernel to manage the database You might think of an RDBMS as an operating system (or set of subsystems), designed specifically for controlling data access; its primary functions are storing, retrieving, and securing data. An RDBMS maintains its own list of authorized users and their associated privileges; manages memory caches and paging; controls locking for concurrent resource usage; dispatches and schedules user requests; and manages space usage within its table-space structures. 70. Name the sub-systems of a RDBMS. I/O, Security, Language Processing, Process Control, Storage Management, Logging and Recovery, Distribution Control, Transaction Control, Memory Management, Lock Management. 71. Which part of the RDBMS takes care of the data dictionary? How? Data dictionary is a set of tables and database objects that is stored in a special area of the database and maintained exclusively by the kernel. 72. What is the job of the information stored in data-dictionary?

63

The information in the data dictionary validates the existence of the objects, provides access to them, and maps the actual physical storage loca 73. How do you communicate with an RDBMS? You communicate with an RDBMS using Structured Query Language (SQL). 74. Define SQL and state the differences between SQL and other conventional programming Languages. SQL is a nonprocedural language that is designed specifically for data access operations on normalized relational database structures. The primary difference between SQL and other conventional programming languages is that SQL statements specify what data operations should be performed rather than how to perform them. 75. Name the three major set of files on disk that compose a database in Oracle. There are three major sets of files on disk that compose a database. All the files are binary. These are 1.) Database files 2.) Control files 3.) Redo logs The most important of these are the database files where the actual data resides. The control files and the redo logs support the functioning of the architecture itself. All three sets of files must be present, open, and available to Oracle for any data on the database to be useable. Without these files, you cannot access the database, and the database administrator might have to recover some or all of the database using a backup, if there is one. 76. What is database Trigger? A database trigger is a PL/SQL block that can defined to automatically execute for insert, update, and delete statements against a table. The trigger can e defined to execute once for the entire statement or once for every row that is inserted, updated, or deleted. For any one table, there are twelve events for which you can define database triggers. A database trigger can call database procedures that are also written in PL/SQL. 77. What are stored-procedures? And what are the advantages of using them? Stored procedures are database objects that perform a user defined operation. A stored procedure can have a set of compound SQL statements. A stored procedure executes the SQL commands and returns the result to the client. Stored procedures are used to reduce network traffic. 78. What is Storage Manager? It is a program module that provides the interface between the low-level data stored in database, application programs and queries submitted to the system. 79. What is Buffer Manager? It is a program module, which is responsible for fetching data from disk storage into main memory and deciding what data to be cache in memory. 80. What is Transaction Manager? It is a program module, which ensures that database, remains in a consistent state despite system failures and concurrent transaction execution proceeds without conflicting. 81. What is File Manager?

64

It is a program module, which manages the allocation of space on disk storage and data structure used to represent information stored on a disk. 82. What is Authorization and Integrity manager? It is the program module, which tests for the satisfaction of integrity constraint and checks the authority of user to access data. 83. What are stand-alone procedures? Procedures that are not part of a package are known as stand-alone because they independently defined. A good example of a stand-alone procedure is one written in a SQL*Forms application. These types of procedures are not available for reference from other Oracle tools. Another limitation of stand-alone procedures is that they are compiled at run time, which slows execution. 84. What are cursors give different types of cursors? PL/SQL uses cursors for all database information accesses statements. The language supports the use two types of cursors 1.) Implicit 2.) Explicit 85. What is cold backup and hot backup (in case of Oracle)?

1.

Cold Backup: It is copying the three sets of files (database files, redo logs, and control file) when the instance is shut down. This is a straight file copy, usually from the disk directly to tape. You must shut down the instance to guarantee a consistent copy. If a cold backup is performed, the only option available in the event of data file loss is restoring all the files from the latest backup. All work performed on the database since the last backup is lost.

2.

Hot Backup: Some sites (such as worldwide airline reservations systems) cannot shut down the database while making a backup copy of the files. The cold backup is not an available option.

86. What is meant by Proactive, Retroactive and Simultaneous Update.

1. 2. 3.

Proactive Update: The updates that are applied to database before it becomes effective in real world. Retroactive Update: The updates that are applied to database after it becomes effective in real world. Simulatneous Update: The updates that are applied to database at the same time when it becomes effective in real world.

PL/SQL TUTORIAL

PL/SQL (Procedural Language/Structured Query Language) is Oracle Corporation's procedural extension language for SQL and the Oracle relational database. PL/SQL is a blocked programming language. Program units can be named or unnamed blocks. Unnamed blocks are known as anonymous blocks because its not going to be saved in the database, so it will never have a name. We typically use anonymous blocks when building scripts to seed data or perform one-time processing activities. They are also effective when we want to nest activity in another PL/SQL blocks execution section. BEGIN

65

DBMS_OUTPUT.put_line ('Hello world!'); END; Basic anonymous block. The BEGIN reserved word starts the exception block, and END word ends it. The dbms_output.put_line procedure allows us to write data to flat file or to direct our PL/SQL output to a screen. The basic anonymous-block structure must contain an execution section. We can also put optional declaration section. DECLARE var1 INTEGER; -- here we can declare variables BEGIN var1 := 5; DBMS_OUTPUT.put_line ('Hello world!'); /* this is an executable section */ END; Single-line comments start with a double-dash ( --). Multiline comments start with a slash and asterisk ( /*) and end with an asterisk and slash ( */). The declaration block lets us define datatypes, structures, and variables. Defining a variable means that we give it a name, a datatype and, optionaly, a value. Variable names begin with letters and can contain alphabetical characters, ordinal numbers (0 to 9), the $, _, and # symbols. Variables have local scope only. The execution block lets us process data. The execution block can contain variable assignments, comparisons, conditional operations, and iterations. Also, the execution block is where we access other named program units (e.g. functions, procedures). We can also nest anonymous-block programs inside the execution block. Assignment statement sets the current value of a variable. The assignment operator in PL/SQL is a colon plus an equal sign (:=) DECLARE var1 varchar2(6) := 'world!'; BEGIN DBMS_OUTPUT.put_line ('Hello ' || var1); END; String literals are delimited by single quotes. Concatenation operator (||) allows us to concatenate two or more strings together. Basic datatypes: VARCHAR2(size) - variable-length character string having maximum length size bytes. Maximum size is 4000, and minimum is 1. You must specify size for VARCHAR2. NVARCHAR2(size) - variable-length character string having maximum length size characters or bytes, depending on the choice of national character set. Maximum size is determined by the number of bytes required to store each character, with an upper limit of 4000 bytes. You must specify size for NVARCHAR2. NUMBER(p,s) - number having precision p and scale s. The precision p can range from 1 to 38. The scale s can range from -84 to 127.

66

LONG - character data of variable length up to 2 gigabytes, or 231 -1 bytes. DATE - valid date range from January 1, 4712 BC to December 31, 9999 AD. RAW(size) - raw binary data of length size bytes. Maximum size is 2000 bytes. You must specify size for a RAW value. ROWID - hexadecimal string representing the unique address of a row in its table. This datatype is primarily for values returned by the ROWID pseudocolumn. CHAR(size) - fixed-length character data of length size bytes. Maximum size is 2000 bytes. Default and minimum size is 1 byte. NCHAR(size) - fixed-length character data of length size characters or bytes, depending on the choice of national character set. Maximum size is determined by the number of bytes required to store each character, with an upper limit of 2000 bytes. Default and minimum size is 1 character or 1 byte, depending on the character set. CLOB - a character large object containing single-byte characters. Both fixed-width and variable-width character sets are supported, both using the CHAR database character set. Maximum size is 4 gigabytes. BLOB - A binary large object. Maximum size is 4 gigabytes. BFILE- contains a locator to a large binary file stored outside the database. Enables byte stream I/O access to external LOBs residing on the database server. Maximum size is 4 gigabytes. There are many sub-types, which are derived from a type and usually add a constraint to a type. For example, an INTEGER is a sub-type of NUMBER and only whole numbers are allowed. If we want to convert values to different data types, we should use conversion functions: to_char( value, [ format_mask ] ) - converts a number or date to a string. VALUE can either be a number or date that will be converted to a string, FORMAT_MASK is optional, this is the format that will be used to convert value to a string. to_number( string1, [ format_mask ]) - converts a string to a number, string1 is the string that will be converted to a number. format_mask is optional. This is the format that will be used to convert string1 to a number. to_date( string1, [ format_mask ] ) - converts a string to a date. string1 is the string that will be converted to a date. format_mask is optional. This is the format that will be used to convert string1 to a date. DECLARE num_var NUMBER (4, 2) := 11.25; int_var INTEGER := 5; date_var DATE := TO_DATE ('11/03/2012', 'dd/mm/yyyy'); string_var VARCHAR2 (50) := 'string 1'; string_no_var VARCHAR2 (50) := '5.30'; char_var CHAR (50) := 'string 2'; BEGIN DBMS_OUTPUT.put_line ('num_var value: ' || num_var); DBMS_OUTPUT.put_line ('int_var value: ' || int_var); DBMS_OUTPUT.put_line ('date_var value: ' || date_var); DBMS_OUTPUT.put_line ('string_var value: ' || string_var); DBMS_OUTPUT.put_line ('char_var value: ' || char_var); DBMS_OUTPUT.put_line ('We can convert numeric value to a string: ' || TO_CHAR (num_var)); DBMS_OUTPUT.put_line ('... or string value to a number: ' || TO_NUMBER (string_no_var, '9.99')); END; Example of use data types and converting functions. Sometimes we need to have a special mechanism with which a variable should find the data type automatically at runtime. To achieve that, we can use the %TYPE or %ROWTYPE attribute, which lets use the datatype of a table field.

67

DECLARE emp_name employees.NAME%TYPE; emp_surname employees.surname%TYPE; BEGIN SELECT NAME, surname INTO emp_name, emp_surname FROM employees WHERE employeeid = 5; DBMS_OUTPUT.put_line (emp_name || ' ' || emp_surname); END; "emp_name" is declared as being of type "employees.name%type." It means that the data type of "emp_name" would be the same as the data type of the "name" column in the "employees" table. Similarly, the other variable, "emp_surname," is also declared. The SELECT INTO statement retrieves data from one or more database tables, and assigns the selected values to variables or collections. DECLARE employee_rec employees%ROWTYPE; BEGIN SELECT * INTO employee_rec FROM employees WHERE employeeid = 5; DBMS_OUTPUT.put_line ('name: ' || employee_rec.NAME); DBMS_OUTPUT.put_line ('surname: ' || employee_rec.surname); DBMS_OUTPUT.put_line ('boss id: ' || employee_rec.bossid); END; The %ROWTYPE attribute provides a record type that represents a row in a database table. The record can store an entire row of data selected from the table or fetched from a cursor or cursor variable. Variables declared using %ROWTYPE are treated like those declared using a datatype name. You can use the %ROWTYPE attribute in variable declarations as a datatype specifier. Conditional structures DECLARE var1 INTEGER := 5; BEGIN IF var1 = 5 THEN DBMS_OUTPUT.put_line ('var1 value is equal to 5'); ELSE DBMS_OUTPUT.put_line ('var1 value is not equal to 5'); END IF; END; An explicit assignment declares a variable with a not-null value. We can use the default value or assign a new value in the execution block. A declaration of a number variable without an explicit assignment makes

68

its initial value null. The IF-THEN-ELSE statement checks a Boolean value or expression and if true, executes the statements in the THEN clause. If the condition is false, the statements in the THEN clause are skipped and ELSE statement is executed. There are three different syntaxes for this statement. IF condition THEN {...statements...} END IF; or IF condition THEN {...statements...} ELSE {...statements...} END IF; or IF condition THEN {...statements...} ELSIF condition THEN {...statements...} ELSE {...statements...} END IF; DECLARE var1 INTEGER := 5; BEGIN case when var1 < 5 then DBMS_OUTPUT.put_line ('var1 value is less than 5'); when var1 = 5 then DBMS_OUTPUT.put_line ('var1 value is equal to 5'); when var1 > 5 then DBMS_OUTPUT.put_line ('var1 value is greater than 5'); else DBMS_OUTPUT.put_line ('var1 value is unknown'); END CASE; END; We can use the case statement within an SQL statement. It has the functionality of an IF-THEN-ELSE statement. The syntax for the case statement is: CASE [ expression ] WHEN condition_1 THEN result_1 WHEN condition_2 THEN result_2 WHEN condition_n THEN result_n ELSE result END CASE expression is optional. It is the value that you are comparing to the list of conditions. (ie: condition_1, condition_2, ... condition_n) condition_1 to condition_n must all be the same datatype. Conditions are evaluated in the order listed. Once a condition is found to be true, the case statement will return the result and not evaluate the conditions any further. result_1 to result_n must all be the same datatype. This is the value returned once a condition is found to be true.

69

Iterative structures Basic loop DECLARE i INTEGER := 0; BEGIN LOOP i := i + 1; DBMS_OUTPUT.put_line ('The index value is ' || i); EXIT WHEN i >= 10; END LOOP; END; The program prints index values from 1 to 10. Simple loops are explicit structures. They require that you manage both loop index and exit criteria. The simple loops have a variety of uses. Typically, this loops are used in conjunction with locally defined cursor statements and reference cursors. WHILE loop WHILE condition LOOP {.statements.} END LOOP; The WHILE loop, also called a conditional loop, evaluates a condition before each loop executes, and if false, the loop is terminated. If the expression is false when the program reaches the WHILE loop, the loop code is jumped and never executed. Use a WHILE loop when the condition test is required at the start of the loop or if you are not sure how many times you will execute the loop body. Since the WHILE condition is evaluated before entering the loop, it is possible that the loop body may not execute even once. DECLARE i INTEGER := 1; BEGIN WHILE i <= 10 LOOP DBMS_OUTPUT.put_line ('The index value is ' || i); i := i + 1; END LOOP; END; FOR loop PL/SQL supports numeric and cursor FOR loops. The numeric FOR loop iterates across a defined range, while the cursor FOR loop iterates across rows returned by a SELECT statement. FOR loops manage how they begin and end implicitly. We can override the implicit END LOOP phrase by using an explicit CONTINUE or EXIT statement to respectively skip an iteration

70

or force a premature exit from the loop. FOR i IN starting_number..ending_number LOOP statement; END LOOP; The starting_number and ending_number must be integers. The loop index is the i variable, and the loop index scope is limited to the FOR loop. The index variable is a PLS_INTEGER datatype number. FOR i IN (select_statement) LOOP statement; END LOOP; BEGIN FOR i IN 1 .. 10 LOOP DBMS_OUTPUT.put_line ('The index value is ' || i); END LOOP; END; The program prints index values from 1 to 10. BEGIN FOR i IN (SELECT surname FROM employees WHERE depid = 2) LOOP DBMS_OUTPUT.put_line ('Department 1: ' || i.surname); END LOOP; END; The program prints employees from department 2. The index variable is not a PLS_INTEGER number in a cursor FOR loop. It is a reference to the record structure returned by the select statement. We combine the index variable and column name with a dot, also known as the component selector. The component selector lets us select a column from the row returned by the select statement.

71

72

73

74

S-ar putea să vă placă și