Sie sind auf Seite 1von 109

INTRODUCTION TO ORACLE

The introductory chapter highlights the key features of Oracle and its products, and emphasises the technologies to be learnt. The chapter also explains the basic principles of relational database. WHAT IS ORACLE ? Oracle consists of a comprehensive set of application building and end-user products, aimed at providing complete information technology solutions. Oracle applications are portable across a wide range of platforms and operating systems, from personal computers to a large parallel processors. Oracle provides a flexible Database Management System (DBMS) the Oracle Server for storage and management of information used by applications. The Oracle7 Server, manages a database with all the advantages of a relational structure, plus the ability to store and execute database objects such as stored procedures and database. About Oracle Server The Oracle Server comprises a Relational DBMS model that controls : - Storage of data in designated database areas - Retrieval of data for applications, using appropriate optimisation techniques - Database security, and the tasks permitted for specific users - Consistency and protection of data, including achieving tasks and locking mechanisms - Communication and integrity of data, where databases are distributed across a network

Oracle applications may run on the same computer as the Oracle Server. Alternatively, applications and the tools supporting them may be run on a client personal computer, while accessing data that is conveniently managed by an Oracle Server on a central computer. ORACLE PRODUCTS CDE TOOLS Oracle Reports Oracle Graphics Oracle Forms Oracle Books

OTHER PRODUCTS Oracle Case SQL *Plus

SQL AND PL/SQL Oracle Server Options In addition to Standard Oracle 7, which provides a comprehensive set of database facilities, there are several options extras available. These include : Procedural Option : Provides a PL/SQL Version 2 engine within Oracle Server, which includes the ability to store database procedures, functions and triggers for use by applications. Distributed Option : Support transactions which update data across more than one database in a distributed network, employing two phase commit.

Parallel Server Option : Trusted Oracle :

Supports loosely coupled systems Provides a set of additional high security features.

Oracle Products Among the many application development and end-user products available within the Oracle family, there is a common ability to access the database. Whether directly or indirectly, this is achieved through the Structure Query Language (SQL). Oracle products include: Oracle Text Retrieval : A technology that adds fully functional text retrieval capabilities to an Oracle database. Oracle CASE : A family of tools to aid the analysis, design and generation of Oracle application. SQL *Plus : A tool that allows direct and interactive use of the SQL language to access the Oracle Server, using ad-hoc commands or by running command files. The Cooperative Development Environment (CDE) The main application development tools from a closely integrated set called the Cooperative Development Environment. The crore elements of the CDE include Oracles procedural language, PL/SQL, graphics facilities and of communication between products.

The main CDE tools are : Oracle Forms V4 : Allows sophisticated screen-based applications to be built quickly and easily and enables the user to query and manipulate data in a convenient form structure, as well as displaying visual images, and accessing facilities provided by other CDE products. Oracle Reports V2 : A powerful report writing tool (formally SQL *Report writer) for building and executing sophisticated reports with multiple text font images. SQL, SQL *PLUS AND PL/SQL SQL, SQL *Plus and PL/SQL are the Oracle facilities that we will be discussing in this course. It is important to understand in each case their differences, purposes and place in the Oracle family. SQL - Is the language used to access a relational database, including Oracle. - May be used with each of the Oracle tools, where access to the database is required. PL/SQL - Is Oracles Procedural language for writing application logic and for manipulation data outside the database. - May include a subset of SQL commands, where access to the database is required. - Is available in each of the CDE products. Also available in the Oracle Server itself (if the procedural option is installed).

SQL *Plus - Is an Oracle Product with which SQL and PL/SQL languages may be used. - Also has its own command language for controlling the behaviour of the product, and for formatting the output from SQL queries. In summary, SQL and PL/SQL are languages that are used in a number of Oracle products, SQL*Plus is just one of the products supporting them. We will now discuss the basic principles of relational database, of which Oracle is an example. THE RELATIONAL APPROACH The principles of the relational model were first laid down by Dr. E.F. Codd, who in June 1970 published a paper called A Relational Model of Data for Large Shared Data Banks. In this paper Dr. Codd proposed the Relational model for database systems. The relational database is perceived by its users as a collection of two dimensional tables which are easy to understand. There are just 4 concepts to grasp Table Columns Rows Fields The relational model mimics the processes of a branch of mathematics known as Relational Algebra. These processes involve:

A collection of objects knows as Relations A set of operators which act on relations to provide new relations A Relation can be thought of as a table. Data retrieval is achieved by means of relational operations on tables RELATIONAL OPERATORS The relational operators are defined below Relational RESTRICTION Description Is an operation that gets and displays data from the relation. It is possible to display all rows, or just rows that meet a condition or many conditions. This is sometimes called a horizontal subset. PROJECTION Is an operation that displays certain columns from the relation, and is therefore often called a vertical subset. PRODUCT Is the result when rows from two sets of data are concatenated. All rows in the first set are concatenated with rows in the second set. Often produces a very large new set. UNION Displays all rows that appear in either or both of two Relations. INTERSECTION Displays all rows that appear in both of two relations.

DIFFERENCE

Displays rows that appear in one relation only. (SQL uses operator minus).

Properties of a Relational Database: A Relational database appears as a collection of relations (tables) to the user. The column/row format of a table is a familiar means of visualising data. There is a set of operators for partitioning and combining relations (Selection, difference). There are no explicit pointers; connectors are made purely on the basis of the data. The language used to query the database is non-procedural and English-like. The user does not specify the access route and does not need to know how the data is arranged physically. The commands for data retrieval and those for making changes to the database are all included within a single language , SQL. There is full data independence. (The data is the same regardless of the access path used, or the application using it). Properties of Tabular Relations A Single table has the following properties: There are no duplicate rows There are no duplicate columns names Row order is insignificant Column order is insignificant Values are atomic (non decomposable). Projection, product, join, union, intersection,

CREATING AND DEFINING TABLE STRUCTURES In this chapter, we discuss the logical aspects of tables and columns, and the commands necessary to build tables with integrity constraints. This is the first of two units that cover the subset of SQL commands known as Data Definition Language (DDL). Oracle Data Structures On this course we will discuss the logical aspects of creating tables. Physical considerations are covered on other courses. Although tables may be created without giving physical placement information, it should be noted that an oracle user must have been assigned some table space in order to create tables. Generally, Oracle data structures can be summarized as follows Tables can be created at any time, even with user still online using the database. There is no need to specify the size of any table. This is ultimately defined by how much space has been allocated to the database as a whole. It is important, however, to estimate how much space a table will use over time. Table structures can be modified online. Tables may acquire more space automatically if the initial size if filled up. DATA DEFINITATION LANGUAGE (DDL) DDL is the subset of SQL commands used to create, modify or remove Oracle database structures, including tables. These commands

have an immediate effect on the database, and also record information in the Data Dictionary (this is discussed later) Naming a Table : The name you choose for a table must follow the standard rules for naming an ORACLE database object. 1. The name must begin with a letter , A-Z or a-z. 2. It may contain letters, numerals, and the special character_(underscore). The characters $ and # are also legal, but their use is discouraged. 3. The name is the same whether upper or lowercase letters are used, for example, EMP, emp and eMp are all the same table. 4. It may be up to 30 characters in length. 5. The name must not duplicate the same of another object in your account. 6. The name must not be a SQL reserved word NAME EMP85 85EMP FIXED_ASSETS FIXED ASSETS UPDATE : : : : : VALID? Yes No :does not begin with a letter Yes No : contains a blank space No: SQL reserved word

You should use descriptive names for tables and other database objects. Use the same name to describe the same entity across different

tables. For example, the department number column is called DEPTNO in both EMP and DEPT. CREATING A TABLE You create a new table using the CREATE TABLE command. On of the simplest forms of this command is where the basic information for each column is defined, together with their data types and sizes. Syntax : CREATE TABLE table-name (column_name type(size), column_name type(size), ); Example : CREATE TABLE DEPT (DEPTNO NUMBER(2), DNAME LOC VARCHAR2(12), VARCHAR2(12);

Column names within one table must be unique. COLUMN TYPES When you create a table, you need to specify each columns data type. The table below shows the most important data types: The data type may be followed by one or more numbers in parentheses which give information about the columns width. The columns width determines the maximum width that values in the column may have. VARCHAR2 columns must have a size specified. NUMBER and CHAR columns may be given a size, but defaults are available. The table below sows the main data types in Oracle 7.

DATA TYPE VARCHAR2(W) :

DESCRIPTION Variable length character values upto width W. Maximum width is 2000 characters.

CHAR(W)

Fixed length character values of width W. Default width is 1. Maximum width is 255.

NUMBER

Floating point number with precision of 38 significant digits.

NUMBER (W,S)

Numbers with a precision W and Scales S. Precision represents the maximum significant digits allowed, which may not exceed 38. Scale is the number of decimal places recorded to the right of the point.

DATE

Date values from January 1,4712 BC to December 1,4712 AD. Time information is also stored.

LONG

Variable, length character values upto 2 gigabytes, or 2(13)-1. Only the LONG columns allowed per table.

RAW AND LONG RAW :

Equivalent to VARCHAR2 and LONG respectively, but used for storing byteoriented or binary data such as graphics images (or) digital sound.

Notes: The Oracle 7 data type VARCHAR2 is synonymous with version 6 data types VARCHAR and CHAR. Oracle uses non-padded comparison semautics if a VARCHAR2 value is used in a comparison. (Refer to chapter 2 for details) If a value written to a column exceeds the columns scale, then rounding will occur. The table below shows examples of column specifications: NUMBER(4) : May contain whole numbers up to 4 digits NUMBER(8,3) : May contain up to 8 digits, 3 of which may be to the right of the decimal point. VARCHAR2(1000) : Values may contain up to 1000 characters. CHAR (80) : Fixed length values of 80 characters, Shorter values are blank-padded. Creation of the EMP table Our demonstration table, EMP, might have been created by CREATE TABLE command like the one below: CREATE TABLE EMP (EMP NO NUMBER (4) NOT NULL, ENAME JOB VARCHAR2 (10), VARCHAR2 (10),

MGR SAL COMM

NUMBER (4) NUMBER (77,2), NUMBER (7,2)

HIREDATE DATE,

DEPTNO NUMBER (2) NOT NULL); The SQL* Plus command DESCRIBE can be used to list details of the columns created in a table: DESCRIBE EMP The NOTNULL Constraint In the above example, you will notice that the definitions for the EMPNO and DEPTNO columns are followed by NOT NULL. This ensures that NULL values are not permitted for these columns, since they serve as keys for operations on this table. Columns without he NOTNULL constraint allow null values NOTNULL is one of several integrity constraints that may be defined for table. The DEFAULT Option: A column may be given a default value through the default option. This prevents nulls from occurring (or errors, NOT NULL is specified) if a row is inserted without a value for the column. The default may be littorals, an expression, but not the name of another column. Functions such as SYSDATE and USER are valid. For example: HIREDATE DATE DEFAULT SYSDATE, SAL NUMBER (7,2) DEFAULT 0

INTEGRITY CONSTRAINTS Oracle allows integrity constraints to be defined for tables an columns to enforce certain rules, either within a table or between tables. Constraints are used: By the Oracle 7 server to enforce rules at table level whenever a row is inserted, updated or deleted from the table. The constraint must be satisfied for the operation to succeed. To prevent the deletion of a table if there are dependencies from other tables. By certain Oracle tools, such as Oracle forms, to provide rules for use in an application. Constraints are classed as either: Table Constraints These may reference one or more columns and are defined SEPERATELY from the definitions of the columns in the table. Column constraints These reference a single column and are defined WITHIN the specification for the owning column. Constraints may be added to a table after its creation and also temporarily disabled (see the ALTER TABLE command in the following unit). All details of constraints are stored in the Data Dictionary. Each constraint is assigned a name; it is easier if you supply one yourself so that it may be easily referenced later, but if not then a name is automatically generated of the form: SYS_Cn

Where n is a unique number. The keyword CONSTRAINTS allows you to name a new constraint yourself. Constraints types

You may define the following constraint types: NULL/NOT NULL UNIQUE PRIMARY KEY FOREIGN KEY(REFERENTIAL INTEGRITY) CHECK UNIQUE Constraint: This designates a column or combination of columns as a unique key. No two rows in the table can have the same value for this key. NULLS are allowed if the Unique Key is based on a single column. Table constraint syntax:

[CONSTRAINT constraints_name] UNIQUE (column, column;)

Column constraint syntax: [CONSTRAINT constraint_name] UNIQUE For example, to ensure that there are never two indentical department names at a single location: CREATE TABLE DEPT (DEPTNO NUMBER, DNAME VARCHAR2 (9), LOC VARCHAR 2(10), CONSTRAINT UNQ_DEPT_LOC UNIQUE (DNAME.LOC)

In the above example, the constraint UNQ_DEPT_LOC is a table constraint. Note the comma preceding its details. A unique constraint causes Oracle to create a unique index to handle the rule. Indexes are discussed later. Primary Key Constraints As with unique keys, a primary key enforces uniqueness of the column or column combinations involved and a unique index is created to manage this. There may, however, only be one primary key per table, and this is known as the definitive key through which rows in the table are individually indentified. Null a are allowed in primary key columns. Table constraints syntax: [CONSTRAINT constraint_name] PRIMARY KEY (column, column,)

Column constraint syntax:

[CONSTRAINT constraint_name] PRIMARY KEY

Note that the same combination of column may not be used for both a primary key and a unique key. The following example defines DEPTNO as primary key using a column constraint; CREATE TABLE DEPT (DEPTNO NUMBER (2) CONSTRAINT DEPT_PRIM PRIMARY KEY,)

Foreign Key Constraint Foreign key provide referential integrity rules either within a table or between tables. A foreign key is used in a relationship with either a primary or unique key elsewhere and could be used, for example, to prevent deletion of a department in DEPT if employees exist with the same department number in EMP. Table constraint syntax:

[CONSTRAINT constraint_name] REFERENCES table (column, column,) REFERENCES table (column, column,) Column constraint syntax: [CONSTRAINT constraint_name] references table (column, column)

Note that the words FOREIGN KEY are not used in the column constraint version of the syntax. Example 1: DEPT DEPTNO EMP (child) (parent)

To establish the relationship between EMP and DEPT in such a way that EMP.DEPTNO is the foreign key, and each employee must have a valid department number that is known in DEPT: CONSTRAINT FK_DEPTNO FOREIGNKEY (DPETNO) REFERENCES DEPT (DEPTNO)

ON DELETE CASCADE OPTION As a result of the above table constraint, (with could equally have been defined as a column constraint), department in DEPT could not be deleted if rows exist in EMP with the same DEPTNO value. Alternative, you may request that corresponding employees are deleted automatically if the parent department in DEPT is deleted. This is achieved by adding the clause ON DELETE CASCADE: CONSTRAINT FK_DEPTNO FOREIGNKEY (DPETNO) REFERENCES DEPT (DEPTNO) ON DELETE CASCADE To ensure that each employee row in EMP is given a manager number (MGR) for a valid existing employee: CREATE TABLE EMP (EMPNO NUMBER (4) PRIMARY KEY. MGR NUMBER (4) CONSTRAINT EMP_MGR REFERENCES EMP (EMPNO) Check constraint The CHECK constraint explicitly defines a condition that each row must satisfy (or make unknown due to a NULL). The condition may use to same constructs as those in a query restriction, with the following exceptions: Sub queries are not allowed References to pseudo columns such as SYSDATE are not allowed Syntax: [CONSTRAINT constraint_name] CHECK (condition) Note that whether defined as a table constraint or a column constraint, check may reference several columns within the table. For example: CHECK (SAL + COMM <=5600)

Other Constraints Options DISABLE Adding DISABLE to a constraint definition means that Oracle does not enforce it. The constraint can still be read by Oracle tools to construct rules in an application, and you can ENABLE the constraint later via the ALTER TABLE command. EXCEPTIONS Identifies an existing table where information about rows that INTO Table name violate the constraint is placed. Finally, note that tables referenced in a constraint must exist in the same database. If they belong to a different user then the owner must be specified as a prefix. Here is a complete example of building the EMP table with constraints: CREATE TABLE EMP (EMPNO NUMBER (4) ENAME VARCHAR2 (10) JOB VARCHAR2 (10), MGR NUMBER (4) CONSTRAINT EMP (EMPNO). HIREDATE DATE DEFAULT SYSDATE, SAL NUMBER (7,2), DEPTNO NUMBER (2) CONSTRAINT CONSTRAINT SAL_CONS NOT NULL CONSTRAINT DEPTNO_CONS NOT NULL. EMP_DEPT FOREIGN KEY (DEPTNO) EMP_MGR REFERENCES CONSTRAINT EMP_PRIM PRIMARY KEY, CONSTRAINT ENAME_CONS CHECK (ENAME=UPPER(ENAME).

REFERENCES DEPT (DEPTNO))

Creating a table with rows from another table There is a second form of CREATE TABLE statement in which the table is created with rows in place, derived from another table: CREATE TABLE DEPT [(column-name,)] AS SELECT statement The table will be created with the specified columns and the rows are retrieved by the SELECT statement inserted into it. Constraint information is inherited from the selected table If all the columns in the SELECT statement have well-defined names, (that is, no expressions, and so on), the column specifications may be omitted. if column specifications are given, the number of columns must equal the number of items in the SELECT list. To create a table dept 30 holding the employee numbers, names, jobs and salaries of employees in department 30, enter: CREATE TABLE DEPT 30 AS SELECT FROM WHERE EMPNO. ENAME, JOB, SAL EMP DEPTNO = 30:

Table created.

To see the description of DEPT 30, enter: DESC DEPT 30: Name ------------EMPNO ENAME JOB SAL Null? ------NOT NULL Type ------ --NUMBER (4) CHAR (10) CHAR(9) NUMBER(7,2)

To create a table holding employee name, salary and grade details, enter: CREATE TABLE EMP_SALS (NAME, SALSRY, GRADE) AS SELECT FROM WHERE Table Created. DESC EMP_SALS; Name ------------NAME SALARY GRADE Null? ------Type ------CHAR (10) NUMBER (7,2) NUMBER ENAME, SAL, GRADE EMP, SALGRADE EMP. SAL BETWEEN LOSAL AND HISAL;

To display the contents of the EMP SALS table, enter:

SELECT FROM NAME --------KNR CSR BAR SNK ISR

* EMP_SALS; SALARY -------800 950 1150 1250 1250 GRADE ------1 1 2 3 3

TABLE MANAGEMENT AND THE DATA DICTIONARY In this second section on Data Definition Language we shall see the commands for altering and removing tables and their constraints. Also, we shall see how information about the database can be extracted from the Data Dictionary. ALTERING A TABLE Use the ALTER TABLE command to change the definition of a table. Syntax: ALTER TABLE table name ADD clause MODIFY DROP options TO ADD clause DISABLE clause (column_spec[column_constraint]) ENABLE

Use the add keyword to add a column and/or constraints to an existing table. To add a column to the EMP tables that will hold the name of an employees spouse, enter: ALTER TABLE EMP ADD (SPOUSES_NAME CHAR (10); Table altered. To see a description of the revised table, enter: DESCRIBE EMP Name -----------EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO SPOUSE_NAME Null? ------NOT NULL Type ------NUMBER (4) CHAR (25) CHAR (9) NUMBER (4) DATE NUMBER (7,2) NUMBER (7,2) NUMBER (2) CHAR (10)

To add a table constraint to an existing table, which specifies that the monthly salary must not exceed $5000 enter: ALTER TABLE EMP ADD (CHECK (SAL <=5000));

THE MODIFY CLAUSE: Use the MODIFY keyword to modify the definition of an existing column. ALTER TABLE name. MODIFY (column type [NULL].) To change the width of ENAME to 25 characters, enter: ALTER TABLE EMP MODIFY (ENAME CHAR (25)); DESCRIBE EMP Name EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO SPOUSE_NAME Null? NOT NULL Type ------NUMBER (4) CHAR (10) CHAR (9) NUMBER (4) DATE NUMBER (7,2) NUMBER (7,2) NUMBER (2) CHAR (10)

------------ -------

There are four changes that you cannot make: 1. You may not change a column containing nulls from NULL to NOT NULL.

2. You may not add a new column that is NOTNULL. Make it null, fill it completely and then change it to NOTNULL. 3. You may not decrease the size of a column or change its data type, unless it contains no data. 4. You may not use the MODIFY option to define constraints on a column except for NULL/NOT NULL. To modify other constraints you must drop them and then add them specifying changes. THE DROP CLAUSE Use the DROP clause to remove a constraint from a table. Syntax: ALTER TABLE table name DROP CONSTRAINT constraint_name [cascad: PRIMARY KEY UNIQUE (column, column,) For example: ALTER TABLE EMP DROP CONSTRAINT EMP_MGR; ALTER TABLE EMP DROP PRIMARY KEY; THE CASCADE OPTION (IN DROP CLAUSE) The CASCADE option of the DROP clause causes any dependent constraints also to be dropped. For example: ALTER TABLE DEPT DROP PRIMARY KEY CASCADE;

Would also cause the foreign key constraints on EMP.DEPTNO to be dropped. THE ENABLED/DISABLE CLAUSE This clause of the ALTAR TABLE command allows constraints to be enabled or disabled without dropping them or recreating them. Syntax: DISABLE UNIQUE (COLUMN, COLUMN,)[CASCADE] ENABLE PRIMARY KEY Constant constraint_name As with the DROP Clause, adding the keyword CASCADE means that dependent constraints are also effected. For example: ALTER TABLE DEPT DISABLE CONSTRAINT DEPT, PRIM CASCADE: OTHER DDL COMMANDS Dropping Table To remove the definition of an Oracle table use the DROP TABLE command. Syntax: DROP TABLE TABLE_NAME [CASCADE CONSTRAINTS] For example: DROP TABLE EMP;

Dropping a table loses all the data in it and all the indexes associated with it. The CASCADE CONSTRAINTS option will also remove dependent referential integrity constraints. Notes: All data will also be deleted from table. Any VIEWS or SYNONYMS will remain, but they become invalid Any pending transactions are committed. Only the creator of the table or DBA can DROP it. DATA MANIPULATION LANGUAGE This unit explains how to make changes to rows in a table, add new rows or delete them. The concept of a transaction is introduced. Read constantly. Read consistency is also discussed. INSERT NEW ROWS INTO A TABLE The INSERT command is used to add rows to a table. Syntax: INSERT INTO table name [(column, column,)] VALUES (value, value,..); It is possible to insert a new row with values in each column, in which case the column list is not required. It is recommended that the COLUMN LIST is ALWAYS specified. If the list is not specified, your software will require modification whenever the table definition if altered. To insert a new department, enter: INSERT VALUES INTO DEPT (DEPTNO, DNAME, LOC) (50,MARKETING,SAN JOSE);

Note that this command adds only one row at a time to table. To enter a new department omitting department name, the column list must be specified :

INSERT INTO DEPT(DEPTNO,LOC) VALUES (50,SAN JOSE); Alternatively if the department name is not known, a NULL could be specified : INSERT VALUES INTO DEPT (DEPTNO,DNAME,LOC) (50,NULL,SAN JOSE);

CHARACTER and DATE values must be enclosed in single quotes: Using Substitution Variables to INSERT Rows. As previously mentioned, INSERT is a one-row-at-a-time command. Using substitution variables it is possible to speed up input: INSERT VALUES INTO DEPT (DEPTNO,DNAME,LOC) (&D_NUMBER,&D_NAME,&LOCATION);

When the command is run, values are prompted for every time. INSERTING DATE AND TIME INFORMATION When inserting a DATE value, the format DD-MON-YY is usually used. With this format the century defaults to the 20th century (19nn). The date also contains time information, which is not specified defaults to midnight(00:00:00). If a DATE needs to be entered in another century and a specified time is also required, use the TO_DATE function: INSERT INTO EMP

(EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) VALUES (7658,MASON,ANALYST,7566,TO_DATE(24/06/2084 9:30, DD/MM/YYYY HH:MI),

3000, NULL 20); COPYING ROWS FROM ANOTHER TABLE INSERT INTO table [(column,column,.)] SELECT select-list FROM table(s); This form of the insert statement allows you to insert several rows into a table where the values are derived from the contents of existing tables in the database. To copy all information on department 10 into the D10 HISTORY table, enter; INSERT INTO D10HISTORY (EMPNO,ENAME,SAL,JOB,HIREDATE) SELECT EMPNO,ENAME,SAL,JOB,HIREDATE FROM EMP WHERE DEPTNO=10; Note the keyword VALUES is not used here.

UPDATING ROWS The UPDATE statement allows you to change values in rows in a table: UPDATE SET [WHERE table[alias] column [,column]={expression,subquery} condition];

For example : To UPDATE Scotts row, enter: UPDATE EMP SET JOB=SALESMAN, HIREDATE=SYSDATE, SAL=SAL*1.1 WHERE ENAME = SCOTT; 1 Record updated. If the WHERE clause is omitted, all rows in the table will be updated. It is possible to use nested sub queries and correlated sub queries in the UPDATE statement. Suppose you had a table of new commission figures for certain employees. For example, the COMMISSION table below is to be used to update certain rows at the EMP table:

COMMISSION EMPNO 7499 7654 7844 7844 7844 COMM 1100 500 500 2000 1500

EMP EMPNO 7499 7654 7844 COMM 300 1400 0

The changes in the COMMISSION table can be applied to the EMP

table using a correlated sub query and a nested sub query as shown below: Example 1: UPDATE SET COMM = (SELECT COMM FROM COMMISSION C WHERE C.EMPNO = EMP.EMPNO) WHERE EMPNO IN (SELECT EMPNO FROM COMMISSION); 3 Records updated. JOINING OF TABLES It is a nothing but a method to access data from more than one table. Generally, the tables are joined by using the following common method: Joins the first row in first table with all rows in second table. Second row in first table with all rows in second table and so on. The total rows retrieved from joining of tables is total rows from first table * total rows from second table.

METHODS OF JOINING Equi joins Cartesian joins Outer joins Self joins Non-Equi joins Set operators: Combines the results of multiple queries into a single result. Union Intersection Minus

Equi joins An equi join links rows from tables based on the equality of a common attribute, such as a department number which occurs as DEPTNO in both the EMP and DEPT tables. Syntax: SELECT Columns from tables named in the from clause FROM table1, tbale2, WHERE table1. Column = table2, column Eg: For each employee, show the name of the department and its location. SQL> SELECT ENAME, JOB, EMP.DEPTNO, DNAME, LOC FROM EMP, DPET WHERE EMP. DEPTNO = DEPT.DEPTNO; (OR) SQL> SELECT ENAME, JOB, DEPT.DEPTNO, DNAME, LOC FROM EMP, DPT WHERE EMP.DEPTNO = DEPT. DEPTNO; Equi joins with row selection conditions The WHERE clause may be used to specify row selection conditions as well as join columns. Eg: List the name job, department number, department name, and location of all clerks. SQL> SELECT ENAME, JOB, DEPT .* FROM EMP, DEPT WHERE EMP. DEPT NO = DEPT.DEPTNO AND JOB = CLERK;

Join guidelines The tables to be joined are specified in the FROM clause. The WHERE clause specifies how to join or merge the tables together, as well search criteria as seen with single tables queries. Columns from either table may be names in the SELECT clause. Columns which have the same name in multiple tables named in the FROM clause must be uniquely identified by specifying TABLE NAME COLUMN NAME TABLE* is a shorthand notation for all columns of a joined table. If the columns are uniquely named across the tables, it is not necessary to specify tables name column name in the WHERE or SELECT clause. As many tables as desired may be joined together. Columns specified in join conditions should be indexed. More than one pair of columns may be used to specify the join condition between any two tables. When n tables are joined, it is necessary to have at least n-1 twotable join conditions to avoid the Cartesian product (four table join requires specification of join criteria for three pairs of tables) Cartesian Joins If you omit the join clause, a Cartesian join is performed. A Cartesian product matches every row of one table to every row of the other table. Eg: SQL> SELECT ENAME, LOC FROM DEPT, EMP WHERE JOB= CLERK; Outer Joins The outer join operator is a plus sign enclosed in parentheses (+). It forces a row containing null values to be generated to match every value of the second table for which there would normally to no match.

Syntax: Select From Where Eg: List the locations of all departments and the employees working at those locations. Include departments without employees. SQL> SELECT LOC, ENAME FROM EMP, DEPT WHERE EMP. DEPT NO (+) = DEPT.DEPTNO; Outer Join Guidelines

columns table1, table2 table1, column (+) = tbale2, column

If a row in one of the tables of a join does not satisfy the join

condition, that row ordinarily will not appear in the querys result. For example, department 40 in the table DEPT has no matching employees in the table EMP without an outer join, the result will not include department 40.

To include rows in a join result even when they have no match An outer join causes SQL to supply to dummy

in a joined table, use an outer join

row for rows not meeting the join condition.

No data is actually added or altered in the table; the dummy Use the notation (+) after the table/column combination in the

rows exist only for the purposes of the outer join.

WHERE clause that needs the dummy rows (for example, WHERE EMP.DEPTNO (+) = DEPT. DEPTNO).

If multiple columns are required to match for the join, all or none

of the columns in a tables join predicates should have the (+)

Only one of the tables in a join relation can be outer joined (that A table can only be outer joined to one other table Rows that do not have a match on the join condition but which

is, you cannot put the (+) on both tables)


are returned because of the outer join may be located by searching for rows with the NULL condition. Self Joins A self-join is used to match and retrieve rows that have a matching value in different columns of the same table. Syntax: SELECT FROM WHERE Eg: List the number, name, job of each employee, and the number, name and job of the employees manager. SQL> SELECT WORKER.EMPNO, WORKER, ENAME, WORKER.JOB, WORKER, MGR, MANAGER.EMPNO MGRNO. MANAGER.ENAME MGRNAME, MANAGER.JOB MGRJOB FROM EMP WORKER, EMP MANAGER WHERE WORKER.MGR=MANAGER.EMPNO; Self Join Guidelines

alias 1. Column alias2.column,. table alias1, table alias2 alias1. Column = alias 2.column

A table can be joined with itself as though it were two separate Self-join is useful to join one row in a table to another in the As with any other join, the join is on columns that contains the

tables.

same table.

same type of information.

The table must be given an alias to synchronize which columns

are coming from which table. Non-Equi Joins Most joins are based on the equality of values in the joined tables; therefore, we call them Equi-joins. Non-equi joins can be performed using the operators. !=< < = > >= BETWEEN DELETING ROWS FROM A TABLE The DELETE command allows you to remove one or more rows from a table. DELETE [WHERE FROM table condition];

To delete all information about department 10 from the EMP table, enter: DELETE WHERE FROM EMP DEPTNO = 10;

If the WHERE clause is omitted, all rows will be deleted. TRANSACTION PROCESSING : What is a Transaction ? A transaction is an operation against the database which comprises a series of changes to one or more tables. There are two classes of transactions. DML transactions which can consist of any number of DML statements and which ORACLE treats as a

single entity or logical unit of work, and DDL transactions which can only consist of one DDL statement. There can be no half-way situation during the execution of the transaction, where some changes specified within the transaction are made to the database and others are not made. For every transaction either all the changes made the database are made permanent, or none of the changes are carried out (they are all discarded). A transaction begins when the first executable DML or DDL command is encountered and ends when one of the following occurs : COMMIT / ROLL BACK DDL command is issued CERTAIN errors (such as deadlock) Log off (EXIT from SQL*Plus) Machine failure A DDL statement is automatically committed and therefore implicity ends a transaction. After one transaction ends, the next executable SQL statement will automatically start the next transaction. Making Changes Permanent In order for changes to become permanent, they must be committed to the database. The COMMIT command makes database changes permanent; ROLLBACK allows us to discard or abandon changes. The change, or changes, made to the database between two commit commands therefore make up a transaction. Until a transaction is committed, none of its changes are visible to other users.

Removing Unwanted Changes Uncommitted changes may be abandoned by typing ROLLBACK. ROLLBACK will return the data to the state it was in immediately after your last COMMIT by discarding all changes made since the last commit. System Failures When a transaction is interrupted by a serious error, for example a system failure, the entire transaction is automatically rolled back. This prevents the error from causing unwanted changes to your data, and returns your tables to their status at the time of the last commit. In this way SQL *Plus protects the integrity of your tables. An automatic rollback is most often caused by a system failure, such as an uninentional system reset or power blackout. Errors n entering commands, such as misspelling a column name or trying to perform an unauthorised operation on another users table, do not interrupt a transaction or cause an automatic rollback. This is because the errors are detected at parse time (when the SQL statement is scanned and checked), not during execution time. A new transaction is started following a commit or rollback that is when the first executable DML or DDL statements is encountered. THE SIGNIFICANCE OF TRANSACTION ORACLE ensures data consistency based on transactions.

Transactions give you more flexibility and control when working with data, and assures data consistency in the event of user process failure or system failure. Transactions should consist of only those DML commands that comprises one consistent change to the data. For example, a transfer of funds (say $ 1000) between two accounts should include the debit to one

account of $ 1000 and the credit to another account of & 1000. Both actions should either fall or succeed together. The credit should not be committed without the debit. CONTROLLING TRANSACTIONS WITH SQL STATEMENTS The following SQL statements are used to control when commit or rollback occur: COMMIT [WORK] SAVEPOINT savepoint_name ROLLBACK[WORK] to [SAVEPOINT] savepoint_name Note that COMMIT and ROLLBACK are SQL statements. The three SQL statements used to control transactions are summarised below: COMMIT [WORK] Syntax: COMMIT [WORK]; Makes changes in the current transaction permanent Erases all save points in the transaction (covered below) Ends the transaction Releases the transactions locks (covered in the next unit). The keyword WORK is optional. You should explicitly end transactions in application programs using the COMMIT (or FOOLBACK) statement. If you do not explicitly commit the transaction and the program terminates abnormally, the last uncommited transaction will be rolled back.

Implicit (automatic) commits occur in the following situations: Before a DDL command After a DDL statement At normal disconnect from the database

DDL statements always cause commits at the time they are executed. If you enter a DDL statements after entering several DML statements, the DDL statement causes a commit to occur prior to its own execution, ending the current transaction. Then, if the DDL statement executes successfully, it too is committed. SAVE POINT Syntax: SAVE POINT savepoint_name For example: SAVE POINT updates_done

Can be used to divide a transaction into smaller portions Savepoints allow you to arbitrarily hold your work at any point in time, with the option of later committing that work or undoing all or a portion of it. Thus, for a long transaction, you can save parts of it as you proceed, finally committing or rolling back. If you make an error, you need not resubmit every statement. If you create a second savepoint with the same name as an earlier save point, the earlier savepoint is deleted. The maximum number of savepoints per user process defaults to 5. This limit can be changed.

ROLL BACK[WORK] to [SAVEPOINT] savepoint_name The ROLLBACK statement is used to undo work The keyword work is optional. Rolling back to a SAVEPOINT is also optional. If you use ROLLBACK without a TOSAVEPOINT CLAUSE, it: - Ends the transaction - Undoes all changes in current transaction - Erases all savepoints in that transaction - releases the transactions locks STATEMENT LEVEL ROLLBACK Part of a transaction me be discarded. If a single DML statement fails, ORACLE V6 will rollback that statement only. This feature is known as STATEMENT LEVEL ROLLBACK. Statement level rollback means that if a single DML statement fails during execution of a transaction, its effect is undone, but the changes made by previous DML statements in the transaction will not be discarded and may be commited or rolled back explicitely by the user. If the statement id a DDL statement, the commit which immediately preceded it is not undone (its change has already been made permanent). ORACLE performs statement level rollback by creating an implicit savepoint before executing any DML command. You cannot refer to this savepoint directly. So, if you ROLLBACK to a SAVEPOINT, you: rollback a portion of your transaction retain the savepoint rolled back to, but lose all savepoints created after the named savepoint. Release table and row locks.

Implicit Rollback Implicit rollbacks occur if abnormal termination occurs (For example user process aborts). Implicit statement level rollbacks occur on statement execution error. It is recommended that you explicity end transactions using either COMMIT [WORK] or ROLLBACK[WORK]. The following example, demonstrates the use of a savepoint, ROLLBACK and COMMIT statements. INSERT INTO DEPT VALUES (50, TESTING LAS VEGAS); SAVEPOINT UPDATE DEPT SET DNAME = MARKETING; insert_done;

ROLLBACK to insert_done (update statement discarded); UPDATE DEPT, SET DNAME = MARKETING (revised update COMMAND) WHERE DNAME = SALES; COMMIT; AUTOCOMMIT

COMMIT/ROLLBACK may be issued manually or automatically by using the AUTOCOMMIT option of the SET command. The AUTOCOMMIT option controls when database changes are made permanent. There are two settings:

Command SET AUTO [COMMIT] ON

Description COMMIT issued automatically when each INSERT,UPDATE or DELETE command issued.

SET AUTO [COMMIT] OFF COMMIT command can be issued explicitely by the user. Also COMMIT is issued if <control> Z (VAX specific) is pressed, when a DROP, ALTER or CREATE command is issued, or if you exit from SQL*Plus. ROLLBACK can be issued explicitely by the user, to reinstate the database.

INTRODUCTION TO SQL
This chapter provides an introduction to the query language used to access an ORACLE database. The SQL command set is outlined as well as the basic query block. In particular, we discuss the SQL statements used to: Perform calculations Handle multi values correctly Specify alternative column headings Concatenate columns Sort rows Enter search criteria(s)

OVER VIEW OF SQL A database management system requires a query language to enable users to access data. Structured Query Language (SQLpronounced sequel) is the language used by most relational database systems. The SQL language was developed in a prototype relational database management system- System R- By IBM in the mid-1970s, in 1979, Oracle Corporation introduced the first commercially available implementation of SQL. Features of SQL SQL is an English-like language. It uses words such as select, insert, delete as part of its command set. SQL is a non-procedural language: you specify what information you require, not how to get it. In other words, SQL does not require you to specify the access method to the data. All SQL statements use the query optimizer- a part of the RDBMS- to determine the fastest means of retrieving the specified data. This feature makes it easier for you to concentrate on obtaining the desired result. SQL processes sets of records rather than a single record at a time. The most common form of a set of records is a table. SQL can be used by a range of users including DBAs, application programmers, management personnel, and many other types of end users. SQL provides commands for a variety of tasks including: Querying data Inserting, updating and deleting rows in a table Creating, modifying and deleting database objects Controlling access to the database and database objects Guaranteeing database consistency.

Earlier database management systems often used a separate language for each of the above categories. SQL unifies all these tasks in a single language. SQL has become the de facto industry standard language for relational databases. The American National Standards Institute (ANSI) adopted SQL as the standard language for RDBMS in 1986. The International Standards Organisation (ISO) has also adopted SQL as the standard languages for RDBMS. All major RDBMS support some form of SQL and most RDBMS vendors intend to comply with the ANSI standard. The SQL Command Set COMMAND SELECT DESCRIPTION This is the most commonly used command; it is used to retrieve data from the database. INSERT UPDATE DELETE These three commands are used to enter new rows, change existing rows and remove unwanted rows from tables in the database respectively. (They are sometimes collectively known as DML or Data Manipulation Language commands). CREATE ALTER DROP GRANT These three commands are used dynamically To set up, change and remove any data Structure for example, tables, views, indexes. (They are sometimes collectively known as DDL or Data Definition Language

REVOKE

commands)

N.B. There are more SQL commands. Refer to the SQL Language References Manual. WRITING SQL COMMANDS When writing SQL commands, it is important to remember a few simple rules and guidelines in order to construct valid statements that are easy to read and edit. SQL commands may be on one or many lines. Clauses are usually placed on Separate lines Tabulation can be used Command words cannot be split across lines SQL commands are not case sensitive (unless indicated otherwise). An SQL command is entered at the SQL prompt and a subsequent lines are numbered. This is called the SQL buffer. Only one statement can be current at any time within the buffer, and it can be run in a number of ways: Place a semi-colon(;) at the end of last clause. Place a semi-colon / forwards slash on the last line Place a forward slash at the SQL prompt Issue a R(UN) command at the SQL prompt.

in the buffer.

Any one of the following statements is valid: SELECT * FROM EMP; SELECT *FROM EMP;

SELECT* FROM EMP; In this manual, SQL commands are split into clauses in the interests of clarity. THE BASIC QUERY BLOCK The SELECT statement retrieves information from the database, implementing all the operators of Relational Algebra. In its simplest form, it must include: 1. A SELECT clause, which lists the columns to be displayed i.e. it is essentially a PROJECTION. 2. A FROM clause, which specifies the table involved. To list all department numbers, employee names and manager numbers in the EMP table you enter the following: SELECT FROM DEPTNO 20 30 30 20 30 30 10 20 10 30 DEPTNO, ENAME, MGR EMP; ENAME SMITH ALLEN WARD CONES MARTIN BLAKE KNR SCOTT KING TURNER 7698 MGR 7902 7698 7698 7839 7698 7839 7839 7566

Note that column names are separated by a comma OTHER ITEMS ON THE SELECT CLAUSE It is possible to include other items in the SELECT Clause. Arithmetic expressions Column aliases Concatenated columns Literals All of these options allow the user to query data and manipulates it for query purposes; for example, performing calculations, joining columns together, or displaying literal text strings. ARITHMETIC EXPRESSIONS An expression is a combination of one or more values, operators and functions which evaluate to a value. Arithmetic expressions may contain column names, constant numeric values and the arithmetic operators: OPERATORS + * / SELECT DESCRIPTION ADD SUBSTRACT MULTIPLY DIVIDE ENAME, SAL * 12, COMM

FROM

EMP;

If your arithmetic expression contains more than one operator, the priority is *,/ first, then +,- second (left to right if there are several operators with the same priority). In the following example, the multiplication (250*12) is evaluated first; then the salary value is added to the result of the multiplication (3000). So far Smiths row : 800 + 3000 = 3800. SELECT FROM ENAME, SAL+250+12 EMP;

Parentheses may be used to specify the order in which operators are executed, if, for example, addition is required before multiplication. SELECT FROM COLUMN ALIASES When displaying the result of a query , SQL * Plus normally uses the selected columns name as the heading. In many cases it may be cryptic or meaningless. You can change a columns heading by using an Alias. A column alias gives a column an alternative heading on output. Specify the alias after the column in the select list. By default, alias headings will be forced to uppercase and cannot contain blank spaces, unless the alias is enclosed in double quotes ( ). To display the column heading ANNSAL for annual Salary instead of SAL * 12, use a column alias: ENAME, (SAL+250)*12 EMP;

SELECT FROM

ENAME, SAL*12 ANNSAL, COMM EMP;

Once defined, an alias can be used with SQL * Plus commands which are dealt with in Units 10 and 11. Note: Within a SQL statement, a column alias can only be used in the SELECT clause. THE CONCATENATION OPERATOR The concatenation operator (//) allows columns to be linked to other columns, arithmetic expressions or constant values to create a character expression. Columns on either side of the operator are combined to make one single column. To combine EMPNO and ENAME and give the alias EMPLOYEE to the expression, enter: SELECT FROM EMPLOYEE SMITH 7499 7521 7566 7788 LITERALS A literal is any character, expression, number included on the SELECT list which is not a column name or a column name or a column alias. KNR ALLEN MARTIN SCOTT EMPNO//ENAME EMP; EMPLOYEE

A literal in the SELECT list is output for each row returned. Literal strings of free format text can be included in the query result, and are treated like a column in the select list. Data and character literals must be enclosed within single quotes (); number literals do not need single quotes. The following statement contains literals selected with concatenation and a column alias : SELECT EMPNO // - // ENAME DEPTNO, FROM EMP; WORKS IN DEPARTMENT WORKS IN DEPARTMENT WORKS IN DEPARTMENT WORKS IN DEPARTMENT WORKS IN DEPARTMENT WORKS IN DEPARTMENT WORKS IN DEPARTMENT DEPTNO 20 30 30 20 30 30 EMPLOYEE, WORKS IN DEPARTMENT ,

EMPLOYEE 7369 SMITH 7499 ALLEN 7521 KNR 7566 JONES 7654 CSR 7698 BLAKE HANDLING NULL VALUES

If a row lacks a data value for a particular column, that value is said to be null. A null value is a value which is either unavailable, unassigned, unknown or inapplicable. A null value is not the same as zero. Zero is a number. Null values take up one byte of internal storage overhead. Null values are handled correctly by SQL

If any column values in an expression are null, the result is null. In the following statement, only Salesmen have a remuneration result. SELECT FROM ENAME SMITH ALLEN KNR JONES MARTIN 16400 19500 15500 ENAME, SAL * 12 + COMM ANNUAL_SAL EMP; ANNUAL_SAL

In order to achieve a result for all employees, it is necessary to convert the null, value to a number. We use the NVL function to convert a null value to a non-null value. Use the NVL function to convert null values from the previous statement to zero. SELECT FROM ENAME SMITH ALLEN WARD KNR MARTIN BLAKE CLARK SCOTT ENAME,SAL*12+NVL(COMM,0)ANNUAL_SAL EMP; ANNUALSAL 9600 19500 15500 37700 16400 34200 29400 36000

CSR TURNER

60000 18000 1. 2. An expression A non-null value.

NVL expects two arguments :

Note that you can use the NVL function to convert a null number, date or even character string to another number, date or character string, as long as the data types match. NVL (DATECOLUMN,01-JAN-88) NVL (NUMBERCOLUMN,9) NVL (CHARCOLUMN,STRING) PREVENTING THE SELECTION OF DUPLICATE ROWS Unless you indicate otherwise, SQL *Plus displays the results of a query without eliminating duplicate entries. To list all department numbers in the EMP table, enter : SELECT FROM DEPTNO 20 30 30 20 30 THE DISTINCT CLAUSE To eliminate duplicate values in the result, include the DISTINCT qualifier in the SELECT command DEPTNO EMP;

To eliminate the duplicate values displayed in the previous example, enter : SELECT FROM DEPTNO 10 20 30 Multiple columns may be specified after the DISTINCT qualifier and the DISTINCT affects all selected columns. To display distinct values of DEPTNO and JOB, enter : SELECT FROM DISTINCT DEPTNO, JOB EMP; DISTINCT DEPTNO EMP;

DEPTNO JOB 10 10 10 20 20 20 CLERCK MANAGER PRESIDENT ANALYST CLERK MANAGER

This displays a list of all the different combinations of jobs and department numbers. Note that the DISTINCT qualifier can only be referred to once and must immediately follow the SELECT command word. THE ORDER BY CLAUSE

Normally the order of rows returned in a query result is undefined. The ORDER by clause may be used to sort the rows. If used, ORDER BY must always be the last clause in the SELECT statement. To sort by ENAME, enter : SELECT FROM ORDER BY ENAME CLARK ALLEN KNR CSR JOB CLERK SALESMAN MANAGER MANAGER ENAME,JOB,SAL*12,DEPTNO EMP ENAME; SAL*12 13200 19200 34200 29400 DEPTNO 20 30 30 10

DEFAULT ORDERING OF DATA The default sort order is ASCENDING: Numeric values lowest first Date values earliest first Character values alphabetically REVERSING THE DEFAULT ORDER To reverse this order, the command word DESC is specified after the column name in the ORDER BY clause. To reverse the order of the HIREDATE column, so that the latest dates are displayed first, enter: SELECT FROM ORDER BY ENAME JOB ENAME, JOB,HIREDATE EMP HIREDATE DESC; HIREDATE

JAMES KING BLAKE ADAMS CLARK

CLERK PRESIDENT MANAGER CLERK MANAGER

23-JUL-84 09-JUL-84 11-JUN-84 04-JUN-84 04-JUN-84 14-MAY-84

TURNER SALESMAN

ORDERING BY MANY COLUMNS It is possible to ORDER BY more than one column. The limit is the number of columns on the table. In the ORDER BY clause. Specify the columns to order by, separated by commas. If any or all are to be reversed, specify DESC after any or each column. To order two columns, and display in reverse order of salary, enter: SELECT FROM ORDER BY DEPTNO 10 10 10 20 20 20 20 20 30 30 DEPTNO, JOB ENAME EMP DEPTNO, SAL DESC; JOB PRESIDENT MANAGER CLERK ANALYST ANALYST MANAGER CLERK CLERK MANAGER CLERK ENAME KING CLARK MILLER SCOTT FORD JONES ADAMS SMITH BLAKE JAMES

To order by a column, it is not necessary to have SELECTed it.

ORDER BY AND NULL VALUES In version 6 of the ORACLE RDBMS, Null values are displayed last for ascending sequence, and are reported first when rows are sorted in descending order. WARNING The ORDER BY clause is used in a query when you want to display the rows in a specific order. Without the ORDER BY clause, the rows are returned in an order convenient to ORACLE, and you should not rely on the ORACLE determined order being consistent from query to query. Also note that the display order of rows does not affect the internal order of the rows as they are actually stored within a table. THE WHERE CLAUSE The WHERE clause corresponds to the Restriction operator of Relational Algebra. It contains a condition that rows must meet in order to be displayed The WHERE clause, if used, must follow the FORM clause: SELECT FROM WHERE Columns table certain conditions are met

The WHERE clause may compare values in columns, literal values, arithmetic expressions or functions. The WHERE clause expects 3 elements: 1. A column name 2. A comparison operator 3. A column name, constant or list of values

Comparison Operators are used on the WHERE clause and can be dividend into two categories, Logical and SQL. LOGICAL OPERATORS These logical operators will test the following conditions : Operator = > >= < <= Meaning Equal to Greater than Greater than or equal to Less than Less than or equal to

CHARACTER STRINGS AND DATES IN THE WHERE CLAUSE : ORACLE columns may be : Character, Number or Date Character strings and dates in the WHERE clause must be enclosed in single quotation marks. Character strings must match case with the column value unless modified by a function. Refer to Character Functions in Unit 4. To list the names, numbers, job and departments of all clerks, enter: SELECT FROM WHERE ENAME SMITH ADAMS JAMES ENAME,EMPNO,JOB,DEPTNO, EMP JOB=CLERK EMPNO 7369 7876 7900 JOB CLERK CLERK CLERK DEPTNO 20 20 30

MILLER

7934

CLERK

10

To find all department names with department numbers greater than 20, enter : SELECT FROM WHERE DNAME SALES OPERATIONS DNAME,DEPTNO DEPT DEPTNO>20; DEPTNO 30 40

COMPARING ONE COLUMN WITH ANOTHER IN THE SAME ROW You can compare a column with another column in the same row, as well as with a constant value. For example, suppose you want to find those employees whose commission is greater than their salary, enter : SELECT FROM WHERE ENAME MARTIN ENAME,SAL,COMM EMP COMM>SAL; SAL 1250.00 COMM 1400.00

SQL OPERATORS There are four SQL operators which operate with all data types: Operator Meaning

BETWEEN AND Between two values (inclusive) IN (list) LIKE IS NULL The BETWEEN Operator Tests for values between and inclusive of low and high range. Suppose we want to see those employees whose salary is between 1000 and 2000: SELECT FROM WHERE ENAME ALLEN WARD MARTIN ADAMS MILLER ENAME,SAL EMP SAL BETWEEN 1000 TO 2000; SAL 1600.00 1250.00 1250.00 1100.00 1300.00 Match any of a list of values Match a character pattern Is a null value

TURNER 1500.00

Note that values specified are inclusive, and the lower limit must be specified first. THE IN OPERATOR Tests for values in a specified list. To find all employees who have one of three MGR numbers, enter :

SELECT FROM WHERE EMPNO 7369 7788 7876 7902

EMPNO, ENAME,SAL,MGR EMP MGR IN (7902,7566,7788) ENAME SMITH SCOTT ADAMS FORD SAL 800.00 3000.00 1100.00 3000.00 MGR 7902 7566 7788 7576

If characters or dates are used in the list they must be enclosed in single quotes ( ). THE LIKE OPERATOR Sometimes you may not know the exact value to search for. Using the LIKE operator, it is possible to select rows that match a character pattern. The character pattern matching operation may be referred to as a wild-card search. Two symbols can be used to construct the search string. Symbol % Represents Any sequence of zero or more characters Any single character To list all employees whose name starts with an S, enter: SELECT FROM WHERE ENAME SMITH ENAME EMP ENAME LIKE S%;

SCOTT The - can be used to search for a specific number of characters. For example to list all employees who have a name exactly 4 characters in length SELECT FROM WHERE ENAME WARD KING FORD The % and - may be used in any combination with literal characters. IS NULL Operator The IS NULL operator specifically tests for values that are NULL. So to find all employees who have no manager, you are testing for a NULL value. SELECT FROM WHERE ENAME KING Negating Expressions ENAME,MGR EMP MGR IS NULL; MGR ENAME EMP ENAME LIKE ----

The following operators are negative tests: OPERATOR != ^= <> NOT COLNAME= NOT COLNAME> SQL OPERATORS OPERATOR NOT BETWEEN NOT IN NOT LIKE IS NOT NULL DESCRIPTION Not between two given values Not in given list of values Not like string Is not a null value DESCRIPTION Not equal to (VAX,UNIX,PC) Not equal to (IBM) Not equal to (all o/s) Not equal to Not greater than

To find employees whose salary is not between a range, enter : SELECT FROM WHERE ENAME SMITH JONES BLAKE CLARK SCOTT KING JAMES ENAME,SAL EMP SAL NOT BETWEEN 1000 AND 2000 SAL 800.00 2975.00 2950.00 2450.00 3000.00 5000.00 950.00

FORD SELECT FROM WHERE

3000.00 ENAME, JOB EMP JOB NOT LIKE M%;

ENAME SMITH KNR WARD MARTIN SCOTT KING ADAMS

JOB CLERK ANALYST SALESMAN ANALYST CLERK PRESIDENT ANALYST

To find all employees who have a manager (MGR), enter: SELECT FROM WHERE ENAME SMITH ALLEN KNR JONES CLARK SCOTT TURNER ENAME, MGR EMP MGR IS NOT NULL; MGR 7902 7698 7698 7839 7566 7839 7782

Note: If a NULL value is used in a comparison, then the comparison operator should be either IS or IS NOT NULL. If these operators are not used and NULL values are compared, the result is always FALSE. For example, COMM!= NULL is always FALSE. The result is false because a NULL value may not be either equal or unequal to any other value, even another NULL. Note than an error is not raised, the result is simply always false. QUERYING DATA WITH MULTIPLE CONDITIONS The AND and OR operators may be used to make compound logical expressions The AND predicate will expect both conditions to be true; whereas the OR predicate will expect wither condition to be true. In the following two examples, the conditions are the same, the predicate is different. See how the result is dramatically changed. To find all clerks who earn between 1000 and 2000, enter : SELECT FROM WHERE AND EMPNO 7876 7934 EMPNO,ENAME,JOB,SAL EMP SAL BETWEEN 1000 AND 2000 JOB = CLERK; ENAME ADAMS MILLER JOB CLERK CLERK SAL 1,100.00 1,300.00

To find all employees who are either and/or all employees who earn between 1000 and 2000, enter :

SELECT FROM WHERE OR EMPNO 7369 7499 7521 7844

EMPNO,ENAME,JOB,SAL EMP SAL BETWEEN 1000 AND 2000 JOB = CLERK; ENAME SMITH ALLEN WARD KNR JOB CLERK SALESMAN SALESMAN CLERK SAL 800.00 1,600.00 1,250.00

1,100.00

You may combine AND and OR in the same logical expression. When AND and OR appear in the same WHERE clause, all the ANDs are performed first then all the Ors are performed. We say that AND has a higher precedence than OR. Since AND has a higher precedence than OR, the following SQL statement returns all managers with salaries over $1500, and all salesmen. SELECT FROM WHERE AND OR EMPNO 7499 7521 7566 7654 7782 EMPNO,ENAME,JOB,SAL,DEPTNO EMP SAL>1500 JOB = MANAGER JOB = SALESMAN; ENAME ALLEN CSR JONES MARTIN KNR JOB SALESMAN SALESMAN MANAGER SALESMAN MANAGER SAL 1,600.00 1,250.00 2,975.00 1,250.00 2,450.00 DEPTNO 30 30 20 30 10

If you wanted to select all managers and salesmen with salaries over $1500 you would enter: SELECT FROM WHERE EMPNO,ENAME,JOB,SAL,DEPTNO EMP SAL > 1500 =SALESMAN); EMPNO 7499 7566 7698 7782 ENAME ALLEN JONES BLAKE CLARK JOB SALESMAN MANAGER MANAGER MANAGER SAL 1,600.00 2,975.00 2,850.00 2,450.00 DEPTNO 30 20 10 10 AND (JOB=MANAGER OR JOB

The parentheses specify the order in which the operators should be evaluated. In the second example, the OR operator is evaluated before the AND operator. CHARACTER DATATYPES AND CONDITIONS The basic types of data stored in an Oracle table are character, number or date values. We shall discuss the variants in detail later. However, the results of a condition involving character data may vary depending on the type of column; Oracle provides column type CHAR for fixed length values and type VARCHAR2 for variable length values in a column. For VARCHAR2 columns, Oracle does not pad the comparison string and would therefore only retrieve an exact math. In the first example opposite, only one row is returned for the condition: WHERE ENAME=SCOTT

Since the other stored row in the ENAME column has more characters than the comparison string. For CHAR columns, however, Oracle adds padding when column values are initially stored, making them all the same length. The same condition would return both rows for SCOTT, regardless of how many trailing spaces were supplied when the values were stored in the table. Oracle blank pads the comparison string in this second case so that the stored spaces are insignificant. OPERATOR PRECEDENCE All operators are arranged in a hierarchy that determines their precedence. In an expression, operations are performed in order of their precedence, from highest to lowest. Where operators of equal precedence are used next to each other, they are performed from left to right. 1. All of the comparison and SQL operators have equal precedence: =, !=, <, >, <=, >=, BETWEEN.AND, IN, LIKE, IS NULL 2. NOT (to reverse a logical expressions result ie. WHERE not (SAL>2000) 3. AND 4. OR Whenever you are in doubt about which of two operations will be performed first when an expression is evaluated, feel free to use parentheses to clarify your meaning and ensure that SQL * Plus does what you intended. Suppose you want to find all the managers, in any department, and all the clerks in Department 10 only. SELECT *

FROM WHERE

EMP JOB= MANAGER OR (JOB = CLERK AND DEPRTNO = 10)

The above parentheses are unnecessary, since and has a higher precedence than or but they clarity the meaning of the expression. SELECT SUMMARY So far the following clauses have been covered in the SELECT command. SELECT FROM WHERE ORDER BY SELECT Alias * DISTINCT FROM Table WHERE [DISTINCT] {*, column [alias].} table condition(s) {column, expr} [ASC/DESC]; select at least one column. may be used for columns on select list only. Denotes all Columns. can be used to eliminate duplicates. denotes the table where the columns originate. restricts query to rows that meet a condition. It may contain column value expressions and literals. AND/OR may be used in a WHERE clause to construct more complex conditions. AND takes priority over OR.

() ORDER BY

can be used to force priority. always appears last. Specified sort order. One or more columns may be specified.

ASC

ascending order is the default sorting order and need not be specified.

Clauses may be entered on separate lines in the buffer, and tabulation used for clarity and ease of editing.

PL / SQL
Procedural Language / Structured Query Language The SQL is a non-procedural language. For SQL, we cannot execute more than one instruction at a time and also this will not provide programming concepts to perform the database transactions programmatically. PL/SQL - It is a procedural language which allows to perform database transactions programmatically. Means it provides all facilities like other programming language such as conditional statements (If), Goto statement, Looping structure (For, while etc) & programming blocks. PROGRAMMING STRUCTURE [DECLARE Declarations .] BEGIN

Statements [Expections ..] END; The programming block in PL/SQL includes the following three sections 1. Declare section that allows to declare variables, constants cursors, exceptions, subranges data types & so on. This is an optional section. 2. Programming part : It is a set of SQL statements to perform a required task. The programming part must be enclosed with key words BEGIN & END. END must be terminated by semi-colon. 3. Exceptions : The statements specified in this section will automatically executes when ever a database transaction is failed specified before the exceptions. DECLARE: Declaration of variables Variable name Data type

To define a name you must follow the rules to define a name in Oracle. It supports all data types available in SQL and besides that provides the following additional data types. They are INT (or) INTEGER (or) SMALL INT POSITIVE REAL DOUBLE PRECISION CHAR VARCHAR Floating Values Integers with Positive

VARCHAR2 LONG CHARACTER STRING BOOLEAN Logical Data Type

Points to be considered while declaring a variable 1. You must use one line for one declaration Ex : A C Integer; Character;

2. Declaration of list of variables are also not allowed. Ex : A , B Integer; 3. A variable can be initialised Ex : A Integer := 100; Date := SYSDATE; CITY Varchar(30) := GUNTUR; CDATE Not allowed

4. We can declare the variable with default values. Ex : A Integer Default 100;

5. We can use NOT NULL Constraint to declare variables Ex : A Integer NOT NULL := 100;

Note : Whenever a variable declared with NOT NULL constraint and that must be initialised with a particular value. Declaring Constants Variable name CONSTANT Datatype := expression;

Ex : Height CONSTANT program execution.

Integer := 100;

Height is a constant name and that cannot be changed during

Operators:The PL/SQL supports the operators available in SQL & besides that it supports the following additional operators. (Arithmatic) *.* Exponential operator Ex : x:=3; Ex : x ** y => xy

(Assignment) := Sample Program DECLARE Qty Real; Rate Real; Amt Real; BEGIN

Qty := & QUANTITY; Rate := & RATE; Amt := Qty * Rate; DBMS_OUTPUT.PUTLINE (Amount is|| Amt); END; & Substitution variable that allows to enter data through keyboard. DBMS_OUTPUT It is pre-defined package provided by the Oracle system. This package provides the std. Procedures to implement various types of output operations in that PUT-LINE is one of the procedure. Syntax : PUT-LINE (STRING); [Only one string]

Note: Whenever you want to use the DBMS OUTPUT procedure in PL/SQL programming, you must set the SERVEROUTPUT variable to on at SQL prompt. i.e. SQL > SQL>Set Server output ON

Host notepad file name .SQL

It opens the notepad editor. If the said file name is already existing. It load the file contents, if not creates a new file. After doing modifications save and exit from the editor. SQL > a) File name to run the program b) First.SQL; Using % Type And % Row Type Attributes % Type: It defines a new variable of the type of another variable. Eg: 1) Declare Credit Debt Real (8.2); Credit % type;

It declares a variable debit using the type of the variable credit. 2) CUST-CODE customer custid % type;

It declares a variable CUST-CODE by using the type of column custid in the table customer. % Row type: This attribute declares a record type variable of a

specified table. Eg: CUSTREC customer % Row type; It declares a record type variable CUSTREC of the type of the table CUSTOMER. Note: CUSTREC will be having all the columns of CUSTOMER table as its member. SQL > Host notepad PRG.SQL Type the program, save and exit. SQL> a) PRG.SQL Executes the program. 1) DELCARE A B C BEGIN A B C DBMS End; / 2) DECLARE M1 M2 M3 TM AM integer; integer; integer; integer; integer; := := := & A; & B; A+B; OUT PUT.PUTLINE (sum is || c); integer; integer; integer;

BEGIN M1 M2 M3 TM AM := := := := := & Marks1; & Marks2; & marks 3; M1+M2+M3; TM/3;

DBMS OUTPUT. PUT-LINE (TOTAL MARKS || TM); DBMS OUTPUT. PUT-LINE (AVERAGE MARKS || AM); End; / CONDITIONAL STATEMENT: IF Syntax: If Condition then Statement 1; [else statement-2] End if; Eg: DECLARE A B Begin A B := := &A; &B; integer; integer;

If A>B then DBMS OUTPUT. PUT-LINE (A IS BIGGEST); Else DBMS OUTPUT. PUT-LINE (B IS BIGGEST) End IF; End; /

2)

Write a program to read total marks of a student confirm whether the student is passed (or) not. When the student secured more than (or) equals to 120 marks in 3 subjects. DECLARE M1 M2 M3 Avg BEGIN M1 M2 M3 := := := & M1; & M2; & M3; M1 + M2 + M3 ; integer; integer; integer; Real (6,2);

Avg :=

If Ang > 119 then DBMS-OUTPUT. PUT-LINE (STUDENT HAS PASSED) Else DBMS-OUTPUT. PUT-LINE (STUDENT HAS FAILED); End If; End; / 3) Write a program to read quantity purchased & P-code calculated. The amount as per the given table. P-CODE 1 2 3 4 Others DECLARE RATE 17.50 2.75 4.80 6.00 12.00

Quantity P-code Amt BEGIN Qty p-code

Real (8,2); Integer; Real (8,2); := := & Quantity; & Product Code; Qty * 17.50;

If p-code =1 then Amt := Else If p-code =2 then Amt Else If p-code Amt Else If p-code Amt Else If Qty Eno If; End If; End If; End If; End If; DBMS-OUTPUT . PUT-LINE (TOTAL AMOUNT IS || Amt); End; / Other form of if statement If condition then Statement 1; ElsIf condition then Statement-2; := Amt * 12.00 := := 4 then qty * 6.00; := := 3 then qty * 4.80; := Qty * 2.75;

; [Else statement-n;] End If; IF P-code Amt Elsif p-code Amt Elsif p-code Amt Elsif p-code Amt Else Amt End if; LOOPING STRUCTURES GOTO Label name := Qty * 12.00; := := := := := := := := 1 then Qty * 17.50; 2 then Qty * 2.75; 3 then Qty * 4.80 4 then Qty * 6.00;

This statement unconditionally transfers control to the specified label. Label name : The name of the label & it must satisfy the rules to define a name in Oracle. This name must be enclosed by angular brackets as given below when you want to use in source code. <<Label name>> Ex: DECLARE I BEGIN << Start Print>> Integer := 1;

DBMS-OUTPUT.PUT-LINE (-----|| I); I := I+1; If I<10 Then start-print; GOTO END IF; END; / FOR LOOP Syntax: FOR Var In [REVERSE] Statements; END LOOP; By default the value of Var starts with the value given in Start & ends with the value given in End incrementing by 1 for every iteration. If REVERSE clause is used it starts from End decremented by 1 for every iteration until it reaches start value. Ex : DECLARE I BEGIN For I IN 1 ..10LOOP DBMS-OUTPUT.PUT-LINE(----|| I); END LOOP; END; / WHILE LOOP Syntax : WhileCondition Loop Integer; Start . End Loop

Statement; End Loop; It repetedly executes the statements till the conditions set to true. Ex : DECLARE I BEGIN While I < 10 I := I + 1; End Loop; END; / DATA BASE OPERATIONS PL/SQL programming supports all database transactional statements like Insert, Update & Delete, retrieval statement select. Besides that the DDL commands will also supported by PL/SQL except the select statements the other statements can be used in PL/SQL without doing any modifications. Where as the select statement must be used with INTO clause in PL/SQL programs. Syntax : SELECT FROM Var-list {Expr. List || *} From Into Var-list table-name [WHERE condition] ; Loop DBMS-OUTPUT.PUT-LINE (---- || I); Integer := 1;

The list of variables declared in PL/SQL program in which you want to store the retrieved data.

Ex : DECLARE CCODE Integer;

CNAME CADDR BEGIN

Varchar2(30); Varchar2(30);

CCODE := & Customer-code; CNAME := & Customer-name; CADDR := & Customer-Addr; INSERT END; / USE EXCEPTION CLAUSE in PL/SQL in program to avoid errors in program. Syntax : EXCEPTION Statements; WHEN EXCEPTION-NAME THEN WHEN EXCEPTION-NAME THEN INTO CUSTOMER Values (CCODE, CNAME, CADDR);

Statements; Statements; , WHEN OTHERS THEN Statements; EXCEPTION NAME The name of the exception handles (or) error EXCEPTION NO-DATA FOUND Raised If No rows are retrieves from query

TOO-MANY ROWS

Query retrieves more than one row

ZERO-DIVIDE

When the divisor is zero, in an SQL expression

INVALID NUMBER

A number to be converted into numeric form is Invalid.

PROGRAM ERROR

When an internal program error has occurred.

OTHERS

Other than the above mentioned exception Handlers

(These are all predefined exceptions) Eg: Declare Ccode Cname Caddr Begin Ccode := &customer-code; Select Custname, Custaddr INTO Cname, Caddr From CUSTOMER Where CUST Code = Ccode; DBMS-OUTPUT. PUT-LINE (CUSTOMER DETAILS); DBMS-OUTPUT. PUT-LINE (NAME --- || CNAME); DBMS-OUTPUT. PUT-LINE (ADDRESS --- || CADDR); EXCEPTION WHEN NO-DATA FOUND THEN DBMS-OUTPUT. PUT-LINE (NO DETAILS ARE FOUND); WHEN TOO-MANY-ROWS THEN DBMS-OUTPUT. PUT-LINE (MANY ROWS ARE retrieved); Integer; Varchar2(30); Varchar2(30);

End; / CURSORS A cursor is a logical area where the oracle system will fix fetch the rows that are retrieved from a query. Cursors can be classified into 2 categories. 1) Implicit Cursors 2) Explicit Cursors

1) Implicit Cursors: The implicit Cursors are opened by the SQL statements. These cursors are totally managed by the oracle system i.e., opening cursors, fetching rows & closing cursors. Generally the implicit cursor will be referenced by the name SQL. 2) Explicit Cursors: These are created by the user. In PL/SQL we cannot process more than one record at a time. To avoid that problem use explicit cursors. Syntax: DECLARE CURSOR CURSOR-NAME IS QUERY; Query: The select statement. The query can be of joining of table, subqueries and all other types. Eg: Declare CURSOR CUST-CURSOR IS SELECT * FROM CUSTOMER; CURSOR STATEMENTS: 1) OPEN: OPEN CURSOR NAME; This statement executes the query * fetch the rows into cursor and open the cursor by placing the cursor pointer at first record. Eg: OPEN CUST-CURSOR;

2) FETCH: Fetch cursor-name Into var-list; This statement fetches the current cursor row into the list of variables. Eg: FETCH CUST-CURSOR INTO CUSTREC; 3) CLOSE: CLOSE CURSOR-NAME; It closes the opened cursor. Eg: CLOSE CUST-CURSOR; CURSOR ATTRIBUTES % % FOUND It returns true if a row is available in cursor other wise false. NOT FOUND Returns true if no record is available.

Syntax:

CURSOR-NAME % ATTRIBUTE;

Eg: CUST-CURSOR % NOT FOUND; Declare CURSOR CUST-CURSOR IS SELECT * FROM CUSTOMER; CURST REC CUSTOMER % ROW TYPE; (CREATES A RECORD VIZ; CURST REC TAKING ALL COLUMNS IF CUSTOMER TABLE) Begin OPEN CUST-CURSOR; LOOP FETCH CUST-CURSOR INTO CUST REC; EXIT WHEN CUST-CURSOR % NOT FOUND; DBMS-OUTPUT. PUT-LINE (CUST REC. SNO ||,| | CUSTREC. NAME ||, || CUST REC. ADDR | ); END LOOP;

CLOST CUST-CURSOR; End; / 1) Write a PL/SQL program to list the customers who belongs to a required address. Declare CURSOR CUST-CURSOR IS SELECT * FROM CUSTOMERS; CUST REC CUSTOMER % ROW TYPE; Begin OPEN CUST-CURSOR; LOOP FETCH CUST-CURSOR INTO CUSR REC; EXIT WHEN CUST-CURSOR % NOT FOUND; IF CUST REC.CUST ADDR = &CITY THEN DBMS-OUTPUT. PUT-LINE (CUSTOMER NAME || CUSTREC. CUST-NAME); END IF; END LOOP; CLOSE CUST-CURSOR; End; / CURSORS WITH PARAMETERS Declaration: CURSOR CURSOR-NAME (VAR.NAME) IS QUERY; Eg: Declare CURSOR CUST-CURSOR (CITY IN VARCHAR 2) IS SELECT * FROM CUSTOMER WHERE CUSTADDR = CITY; OPEN CURSOR- NAME (ARG-LIST);

Eg: OPEN CUST-CURSOR (GUNTUR); 1. Write a PL/SQL program to print the customer details and bills related to the current customer. DECLARE CURSOR CUST-CURSOR IS SELECT * FROM CUSTOMER; CURSOR BILL-CURSOR (CODE IS INTEGER) IS SELECT 8 FROM BILLS WHERE CUST=CCODE; CUSTREC CUSTOMER % ROWTYPE; BILL REC BILLS%ROWTYPE; BEGIN OPEN CUST-CURSOR; LOOP FETCH CUST-CURSOR INTO CUST REC; EXIT WHEN CUST-CURSOR % NOT FOUND DBMS-INPUT, PUT-LINE (CODE = || CUST-REC CUSTCODE); DBMS-INPUT, PUT-LINE (NAME = || CUST-REC.CUSTNAME); OPEN LOOP FETCH BILL-CURSOR INTO BILL REC EXIT WHEN BILL-CURSOR % NOT FOUND; DBMS-INPUT, PUT-LINE(BILL AMOUNT || BILL REC.BILLAMT); : END LOOP; CLOSE BILL-CURSOR; END LOOP; END; CLOSE CUST-CURSOR; BILL-CURSOR (CUSTREC.CUSTCODE);

CURSORS WITH FOR UPDATE CLAUSE The FOR UPDATE CLAUSE locks the rows Syntax : CURSOR Cursor-name[(arg-list)] IS QUERY FOR UPDATE; SELECT * FROM BILLS FOR UPDATE; WHERE CURRENT OF CLAUSE This clause causes the corresponding row is the master table relates to the current row in the cursor while performing the transactions like delete (or) update. When ever you want to use this clause you must declare cursor with FOR UPDATE clause. Eg. : (1) UPDATE statement WHERE CURRENT OF CURSOR-NAME; (2) DELETE statement WHERE CURRENT OF CURSOR-NAME;

Eg. : CURSOR BILL-CURSOR IS

DECLARE CURSOR BILL-CURSOR IS SELECT * FROM BILLS FOR UPDATE; BILL REC BILLS % ROWTYPE; INTEREST REAL; BEGIN OPEN LOOP FETCH BILL-CURSOR INTO BILLREC; EXIT WHEN BILL-CURSOR % NOT FOUND; IF BILLREC, BILLAMT > 1000 THEN BILL-CURSOR;

INTEREST = BILLREC.BILLAMT * 0.04; ELSE IF BILLREC.BILL AMT > 500 THEN INTEREST = BILLREC. BILLAMT * 0.03; ELSEINTEREST = BILLREC. BILLAMT * 0.02; ENDIF; UPDATE BILLS SET BILL AMT = BILLAMT + INTEREST WHERE CURRENT OF BILL-CURSOR; END LOOP; CLOSE BILL-CURSOR; END LOOP; CLOSE BILL-CURSOR; END; / CURSOR FOR-LOOPS It will provide a facility to reduce the usage of Loop statement, Open, Fetch & close statements while you are working with a cursor i.e, a single CURSOR FOR LOOP statement will replace all the above four statements Syntax : FOR Variable Statements; , END LOOP; This form of Cursor For Loop will open the cursor automatically and fetches a row from cursor to Variable and performs the statements repeatedly until the end of rows in cursor. DECLARE CURSOR CUST-CURSOR IS; IN CURSOR-NAME LOOP

SELECT 8 FROM CUSTOMER; CUST-REC BEGIN FOR CUST-REC IN CUST-CURSOR LOOP DBMS-OUTPUT.PUT-LINE (CUSTREC.CUST-CODE || , || CUSTREC.CUST-NAME || , || CUSTREC. CUST-ADDR); END LOOP; END; / EXCEPTIONS CLAUSE This clause executes the rested statements to an error occurs from an SQL statement execution. The exception errors can be classified into 3 categories. 1. Standard Errors 2. User Defined Errors 3. Undefined Errors The standard errors are the errors that care defined by the Oracle system. These errors names can be directly used in exception clause. Eg. : TOO-MANY-ROWS ZERO DIVIDE Etc., User Defined Errors: Some of the errors are not defines in Oracle system. To Trap such type of errors the user must define his own error definitions. Such type of errors are called user defined errors. Creating User Defined Errors CUSTOMER % ROWTYPE;

(a)Declare an user defined error name of type exception (b)In programming block raise that exception depending on your required situation. Using the RAISE command (c) Defined exception error block in exception area Eg. DECLARE NOT-MULTIPLE-FIFTY EXCEPTION; Qty Number; Rate Number; Amt Number; BEGIN Qty: = &Quantity Rate := & Rate; If MOD (qty,50) <> 0 Then RAISE NOT-MULTIPLE-FIFTY; End if; AMT := Qty * Rate; DBMS-OUTPUT. PUTLINE(Amount is = || Amt); Exception When NOT-MULTIPLE-FIFTY THEN DBMS-OUTPUT.PUT-LINE (Please Enter Qty in multiples of 50s); Exceptin When NOT-MULTIPLE-FIFTY THEN DBMS-OUTPUT.PUT-LINE (Please Enter Qty in multiples of 50s); END; / UNDEFINED ERRORS : These errors are not defined in oracle system like std. Errors. These errors are having an Unique number. These numbers are called error numbers. To define such type of error codes the Oracle provides the following procedure PRAGHA EXCEPTION-INIT (excepition-name,error-code);

Exception-name : The name of the exception you defined is declare section Error-Code : The Oracle error code you want to associate to the exception name. Eg. : DECLARE NULL-VALUE-CHECK EXCEPTION; PRAGMA EXCEPTION INIT (NULL-VALUE.CHECK,-01400); BEGIN INSERT INTO CUSTOMER VALUES (&CCODE,&CNAME,&CADDR); EXCEPTION WHEN NULL-VALUE CHECK THEN DBMS-OUTPUT. PUT-LINE (NULL VALUES NOT ACCEPTED IN END; / ERROR FUNCTIONS 1. SQL CODE Syntax : 2. SQL ERRM Syntax : It returns the error code related to the last database transaction. SQL CODE; Returns an error message related to the given error codes. SQLERRM (err-num); CUSTOMER CODE);

Eg. : SQLERRM (1400); Mandatory Entry. STRING REVERSE

For I IN 1.L LOOP L : = Substr(SI,I,1) S2 = C|| S2; End Loop; DATABASE TRIGGERS A trigger is a PL/SQL programming block which can automatically executes depending on a particular situation. A data base trigger has 3 main parts 1. Trigger event 2. Trigger Constraint 3. Trigger action

Trigger Event : A situation on which you want to perform the trigger action. In a database trigger there are 3 major events: (a) INSERT (b) DELETE (c) UPDATE.

Trigger Constraint : It is a restriction on trigger Trigger action : The PL/SQL program block We can specify maximum of 12 triggers on a table. Classification of Triggers: Main trigger events Sub trigger events : : INSERT, DELETE, UPDATE Before & After These classes controls the execution of triggers before the event is occurred after the event is completed respectively. Row level : A row level trigger executes for each

row in a transaction. Statement level : This trigger will execute for every transaction. Creation of Triggers: CREATE [OR REPLACE] TRIGGER trigger name {BEFORE | AFTER} {INSERT | DELETE | UPDATE [OF COLUMN] on table name [For each row] [When condition] Trigger Name On table name For each row : : : The name of the trigger you want to create. The table name on which you want to create a trigger. This clause designates whether the trigger is row level (or) statement level. If this clause is defined the trigger will be row level. If omitted, the trigger will be statement level. When condition : Eg: 1) When the values entered into custname & custaddr are to be converts in upper case before insertion of values. Create or Replace Trigger Upper convert Before Insert on customer for each you. Begin : : New, Custname := Upper (:New.Custname); New. Custoaddr := Upper (:New. Custaddr); It is a restriction to the trigger.

End; / New and Old are the referencing variables to a row to be processed. A new referencing variable consists the latest information. Old - consists only the existing data. Altering Trigger Definitions: When we want to alter a trigger definition use Or Replace clause in create trigger command. Alter Trigger: The command allows to make the functioning of the trigger enabled (or) disabled. Syntax: Alter Trigger trigger.name {Enable | Disable}; Enable Disable Enables the functioning of the triggers Disables the functioning of the triggers. When you disable the trigger is subsequent transactions on the table the trigger will not work. Eg: Alter Trigger Delete Child - Rows. Disable; Dropping Triggers: The drop Trigger command allows to remove a trigger from database permanently. Drop Trigger trigger-name; Eg: Drop Trigger Delete Child - Rows; Viewing Triggers: oracle system provides a view with the name usertriggers to manage the triggers you creates in the current user. Main Columns of view : Trigger.name Table.name Trigger-type

Triggering-event Trigger-body SQL> Select Trigger-Name from USER-TRIGGERS; SUB PROGRAMS Sub programs are named PL/SQL blocks that can take parameters are be invoked. PL/SQL has 2 types of sub programs called Procedures & Functions. Generally a procedure is used a perform an action & a function to compare a value. FUNCTIONS: A function is a set of PL/SQL statements, you can call by name. These functions evade an expression & return values to the caller (Who calls the function). Creating a Function: To create a function use the command CREATE FUNCTION. Syntax: CREATE [OR REPLACE] FUNCTION [SECHEME.] function [(ARGUMENT [IN] data type. [. Argument [in] data type].)] Return data type. {IS| AS} PL/SQL sub program body. Function The name of the function you want to create. The name of an argument to the function. An argument may be a string (or) numeric constant. An expression, variable (or) a function it you omit the argument the

Argument -

function does not accept arguments while calling. IN Specifies that you must supply a value for the argument when calling the function. Data type Is the type of data of an argument. It cannot specify length, precision (or) scale. Return Data type Eg: Specifies the data type of functions return value.

CREATE OR REPLACE FUNCTION CALC-AMOUNT (Q IN REAL, R IN REAL) RETURN REAL AS

Begin RETURN Q * R; End ; / Note: Is when you want to declare local variable you must use IS. As in all other cases. Calling Functions: You must use select statement while calling a function from SQL prompt as given below. SQL> Select calcamount (123, 45.76) from DUAL; O/P% Calcamount 5628.48 From PL/SQL program DECLARE Qty real; Rate real;

Amt BEGIN Qty

real; := & quantity;

Rate := & Rate; Amt := calcmount (Qty, rate); DBMS OUT PUT. PUT-LINE (AMOUNT IS | | AMT); End; / Execution: SQL > Set Server output on SQL > @ file name

Altering Function Definition: To alter the definition of a function use OR REPLACE clause in CREATE FUNCTION Statements. Droping Functions: Drop Function command is uses to remove a function from the database permanently. DROP FUNCTION function-name; Eg: Drop function calcamount;

PROCEDURES: It is a group of PL/SQL statement used to perform a particular action. Creating a Procedure: CREATE [OR REPLACE] PROCEDURE

[SCHEMA] PROCEDURE [(ARGUMENT [IN | AT | IN OUT] DATA TYPE [, ARGUMENT [IN | AT | IN OUT ] DATA TYPE] )] {IS |As} PL/SQL sub program body. IN Specifies that you must specify the value for the argument

when calling the procedure. OUR Specifies that the procedure passes a value for this argument back to its calling environment after execution. IN OUT Specifies that you must specify a value for the argument when calling the procedure and the procedure passes a value beak to its calling environment after execution. Eg: CREATE PROCEDURE CALCAREA ( RADIUS IN REAL AREA OUT REAL) AS Begin AREA := 3.1416 * RADIUS * RADIUS; End; / Executing Procedures: To execute a procedure at SQL prompt use the commands EXECUTE. Syntax: Execute procedure name. In PL/SQL program to execute a procedure specify the name of the procedure as a statement. Eg: Create procedure showing As begin DBMS-OUTPUT. PUT-LINE (WELCOME TO PROCEDURES); End ; / At SQL prompt From PL/SQL program End; / : SQL> Execute showing : Begin Showing ;

Altering Procedures: To alter a procedure definition use OR REPLACE clause. Droping Procedures: The command Drop Procedure is used to remove a stored procedure object from the database permanently. Drop Procedure Procedure Name; Eg: Drop Procedure showing; Example For Database Related Procedure SQL> HOST NOTEPAD Pros.SQL & create procedure update-due (ccode in integer) is dueamt real; Begin SELECT SUM (BILL AMOUNT) INTO DUEAMT FROM BILLS WHERE CUSTCODE = CCODE; UPDATE CUSTOMER SET DUE AMOUNT= NVL (DUE AMOUNT,O) + DUE AMT WHERE CUSTCODE = CCODE; End; / SQL> Execute update-due PACKAGES A package is a database object that groups logically related PL/SQL type objects and subprograms. Packages usually have 2 parts a specification & a body. Although sometimes the body is unnecessary. The package specification consists of public declarations which are visible to your application. The body holds implementation details, private declarations which are hidden from your application.

Creating a Package Specification: The command CREATE PACKAGE is used to create the specifications for a stored package. The specification is the collection of related procedures, functions and other program objects stored together in the database. Syntax: Create [or replace] package [scheme.] package {is | As} PL/SQL package SQL. Eg: CREATE OR REPLACE PACKAGE SAMPLE-PACK AS FUNCTION BILLS TOTAL (CODE IN INTEGER) RETURN REAL; PROCEDURE SHOWMSG; END SAMPLE-PACK; / Creating a Package Body: Used to create the body of stored package. CREATE [OR REPLACE] PACKAGE-BODY [SCHEMA..]PACKAGE {IS|AS} PL/SQL-PACKAGE-BODY. Package: The name of the package you want to create. That must be similar to the package name used in package specification. Eg: CREATE OR REPLACE PACKAGE-BODY SAMPLE-PACK AS FUNCTION BILLS TOTAL (CCODE IN INTEGER) RETURN REAL IS BAMT REAL; BEGIN SELECT SUM (BILL AMOUNT) INTO BAMT FROM BILLS WEEK CUSTCODE = CCODE;

RETURN (BAMT); END BILLS TOTAL; Procedure Showmsg as Begin DBMS-OURPUT.PUT-LINE PROGRAMMING); End showmsg; End sample-pack; / Calling a Member in a Package: Use dot notation method to call a remember in package. Eg: Execute sample-pack showmsg; O/P : Welcome to package programming. Altering Package Definition: To alter the definitions of a package or a package body use OR REPLACE command is create package and create package body command. Drop Package: Syntax: Drop Package Package.Name To remove the package specification from the database permanently. Syntax: Drop Package-Body Package-name. Compiling stored Procedure ALTER function function.name COMPILE; ALTER procedure procedure-name COMPILE; ALTER package package.name COMPILE [body]; Use these commands to recompile the stored procedures. (WELCOME TO PACKAGE

Eg: Alter function BILLS TOTAL COMPILE; Viewing Stored Objects (or) Procedures: The oracle provides a view with the name USER-SOURCE to maintain all stored object details like function, procedures, packages and package body. SQL> DESC USER-SOURCE Name Eg: Null ? Type Select distinct name from user-source it lists all the names in the stores objects in user-source. Eg: Select TEXT from user-source where NAME = IS PRIME it lists the programming part. SQL> COLUMN TEXT FURMAT A50; Eg: SELECT LINE, TEXT FROM USER-SOURCE where NAME = IS PRIME; it lists the text with line numbers. Eg: SQL> SELECT DISTINCT NAME FROM USER-SOURCE WHERE TYPE = FUNCTION; it lists the function names. Working with users: (An user can be creates only when we are is system/manager) User User is a person who can communicates the ORACLE database server. (OR) User is an account through which you can login is database and establish the means by which the oracle permits access by the user. Creating a user (Environment must not be scott(tiger) to create an user, use the command CREATE USER.

Syntax:

CREATE USER uses IDENTIFIED {BY PASSWORD; EXTERNALLY}

User:

The name of the user we want to create. The user must specify this password to logon.

Identified by password -

Eg: SQL> CREATE USER CLASS 79 IDENTIFIED BY MYCLASS; user created We cannot work with the user class 79 because that user does not have any privileges to do database transactions and to manage database objects. But, if we want to do all these things you must associate related privileges or roles to the user by using grant command. The GRANT command is used to grant system privileges and roles to users and roles. Syntax: Grant {System priv | role} [,{System-priv | role}]. To {user | role| PUBLIC } [,user | role | PUBLIC}]. [WITH ADMIN OPTION] System Priv: It is a system privilege to be granted Role : A role is the group of privileges the Oracle system provides there standard roles. Connect role CONNECT RESOURCE and DBA : Allows the user to logon to the database and allows to manage the objects like tables, snap shots, views

clusters,.. Resource role: It has the privileges from connect and besides that it has additional privileges like CREATE FUNCTION, PROCEDURES, TRIGGER. Dba Public : : Allows the user to create another user. Grant system privileges and rows to all users.

With admin option: Allows the grantee to grant system privileges or roles to other users & roles. Eg: GRANT CONNECT, RESOURCE, DBA TO CLASS 79 O/P : Grant succeeded. SQL> CONNECT CLASS79/MYCLASS Connecting to the user: A command CONNECT allows the user to connect to a required user. Syntax : conn[ect] [logon] Logon : Requires the following syntax User name [,password] [@database-specification] Disconnect Command: Detaches the current user from the data base. Changing Password to a user: Eg: GRANT CONNECTS TO CLASS 79 IDENTIFIED BY NEWPASS; SQL> CONNECT CLASS 79/NEWPASS

Revoke Command: It revoke system privileges and roles from user and roles. Syntax: REVOKE { SYSTEM-PRIV | ROLE } [,{SYSTEM-PRIV|ROLE}] FROM {USER|ROLE| PUBLIC} [,{USER|ROLE|PUBLIC}].. Eg: REVOKE RESOURCE FROM CLASS 79; REVOKE SUCCEED IT REVOKES THE ROLE RESOURCE FROM THE USES CLASS 79. Working with schemes: A schema is a communication area where we can store the database objects like tables, views, shop shots etc. The Oracle system will create a difficult scheme wit the name if the uses to be created. But, we can create more than 1 schema under one user. Creating a Schema: CREATE SCHEMA AUTHORIZATION SCHEMA { CREATE TABLE command | CREATE VIEW command | GRANT Command} Where Schema The name of the schema. It must be the same as your Oracle user name. Grant It is grant statement (objects privileges) to be issued & part of this create schema statement. Eg: Create schema myschemal; To create a new table under their schema. SQL> CREATE SCHEMA myschemal. Person (-.-.--.-.-.);

It creates a table person under schema my schemal. Note: Whenever you want to refer the table person you must use the schema name in which the table was created. (or) SQL> Create schema my schemal SQL> Create table person (-.-.--.-.-.);

It creates a schema with the name my scheml annd adds a new table object called person. Note: Default schema is the schema which was creates with name of the user. SYNONYM: A synonym is an alternative name for a table, view, procedure, stored function, package, shop shot or another synonym. Syntax: CREATE [PUBLIC] SYNONYM [SCHEMA] SYNONYM For [schema] object [@ db link] Public Creates a public synonym public synonyms are assessable to all user. If you omit this option the synonym is private a is assessable only within its schema. Schema Is the schema to contain the synonym. Is the name of the synonym to be created. identifies the objects for which synonym is created. to specify the server name, if there exists more than one

Synonym For @db link -

server. Eg: Create synonym X.person For Y.person; It creates a synonym X.person for the object Y.person. Create synonym X.Sales (Creates synonym for the some users table) For sales; Droping synonyms : Drop synonym command is used to remove a synonym from the database. Syntax: DROP [PUBLIC] SYNONYM [SCHEMA] SYNONYM Eg: Drop synonym X.sales; Rename To rename a table, view, sequence or private synonym.

Syntax: Rename old to new Eg: Rename person to Friend; CODD RULES 1. Table It is a right angular matrix where rows are called as Tuples & columns are called as attributes. 2. Security arrangements 3. Null value use 4. Integrity rule 5. Data dictionary concept 6. Distributed processing 7. Normalization Arranging users, passwords

RDBMS must satisfy 6 database rules of minimum.

Das könnte Ihnen auch gefallen