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 Oracle’s procedural language, PL/SQL, graphics facilities and of communication between products.

May be used with each of the Oracle tools. Also available in the Oracle Server itself (if the procedural option is installed). SQL *Plus and PL/SQL are the Oracle facilities that we will be discussing in this course. and accessing facilities provided by other CDE products. SQL . purposes and place in the Oracle family. SQL.Is available in each of the CDE products. PL/SQL . where access to the database is required. including Oracle. . . SQL *PLUS AND PL/SQL SQL.May include a subset of SQL commands. It is important to understand in each case their differences. . where access to the database is required.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.Is Oracle’s Procedural language for writing application logic and for manipulation data outside the database.Is the language used to access a relational database. Oracle Reports V2 : A powerful report writing tool (formally SQL *Report writer) for building and executing sophisticated reports with multiple text font images.

who in June 1970 published a paper called A Relational Model of Data for Large Shared Data Banks.SQL *Plus . SQL*Plus is just one of the products supporting them. Codd. Codd proposed the “Relational” model for database systems.Also has its own command language for controlling the behaviour of the product. of which Oracle is an example. 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: . E. SQL and PL/SQL are languages that are used in a number of Oracle products. In this paper Dr. We will now discuss the basic principles of relational database. .F. and for formatting the output from SQL queries. THE RELATIONAL APPROACH The principles of the relational model were first laid down by Dr. The relational database is perceived by its users as a collection of two – dimensional tables which are easy to understand.Is an Oracle Product with which SQL and PL/SQL languages may be used. In summary.

Often produces a very large new set. 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. and is therefore often called a “vertical subset”. . This is sometimes called a “horizontal subset”. 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. UNION Displays all rows that appear in either or both of two Relations.• 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. INTERSECTION Displays all rows that appear in both of two relations. or just rows that meet a condition or many conditions. PROJECTION Is an operation that displays certain columns from the relation. It is possible to display all rows.

(The data is the same regardless of the access path used. join. • There is a set of operators for partitioning and combining relations (Selection. • The user does not specify the access route and does not need to know how the data is arranged physically. union. • There are no explicit pointers. product. • The column/row format of a table is a familiar means of visualising data. intersection. SQL. (SQL uses operator minus). difference). • The language used to query the database is non-procedural and English-like. Properties of a Relational Database: • A Relational database appears as a collection of relations (tables) to the user. connectors are made purely on the basis of the data. Projection. • The commands for data retrieval and those for making changes to the database are all included within a single language .DIFFERENCE Displays rows that appear in one relation only. 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). • There is full data independence. .

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

5. It may contain letters. A-Z or a-z. 1. The name must begin with a letter . 6. The characters $ and # are also legal. 3. for example. 4.have an immediate effect on the database. Use the same name to describe the same entity across different . 2. 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. The name is the same whether upper or lowercase letters are used. emp and eMp are all the same table. It may be up to 30 characters in length. EMP. numerals. but their use is discouraged. 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. The name must not duplicate the same of another object in your account. and the special character_(underscore).

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 column’s 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 column’s width. The column’s 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 column’s 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),

but not the name of another column. SAL NUMBER (7.2).2) DEFAULT 0 . since they serve as keys for operations on this table. This prevents nulls from occurring (or errors. Columns without he NOTNULL constraint allow null values NOTNULL is one of several integrity constraints that may be defined for table.MGR SAL COMM NUMBER (4) NUMBER (77. NUMBER (7. For example: HIREDATE DATE DEFAULT SYSDATE. DEPTNO NUMBER (2) NOT NULL). NOT NULL is specified) if a row is inserted without a value for the column. 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. This ensures that NULL values are not permitted for these columns. Functions such as SYSDATE and USER are valid. you will notice that the definitions for the EMPNO and DEPTNO columns are followed by NOT NULL.2) HIREDATE DATE. The DEFAULT Option: A column may be given a default value through the default option. The default may be littorals. an expression.

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

to ensure that there are never two indentical department names at a single location: CREATE TABLE DEPT (DEPTNO NUMBER. DNAME VARCHAR2 (9). The keyword CONSTRAINTS allows you to name a new constraint yourself.LOC) . No two rows in the table can have the same value for this key. CONSTRAINT UNQ_DEPT_LOC UNIQUE (DNAME.Where n is a unique number. column. Table constraint syntax: ‘[CONSTRAINT constraints_name] UNIQUE (column. 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. NULLS are allowed if the Unique Key is based on a single column. LOC VARCHAR 2(10).…) Column constraint syntax: [CONSTRAINT constraint_name] UNIQUE For example.

The following example defines DEPTNO as primary key using a column constraint. however. only be one primary key per table.…) 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. A unique constraint causes Oracle to create a unique index to handle the rule. Primary Key Constraints As with unique keys.In the above example. the constraint UNQ_DEPT_LOC is a table constraint.…) . and this is known as the definitive key through which rows in the table are individually indentified. a primary key enforces uniqueness of the column or column combinations involved and a unique index is created to manage this. There may. Note the comma preceding its details. Null a are allowed in primary key columns. CREATE TABLE DEPT (DEPTNO NUMBER (2) CONSTRAINT DEPT_PRIM PRIMARY KEY. Table constraints syntax: [CONSTRAINT constraint_name] PRIMARY KEY (column. column. Indexes are discussed later.

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))

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

2) To create a table holding employee name. enter: . enter: DESC DEPT 30: Name ------------EMPNO ENAME JOB SAL Null? ------NOT NULL Type -----. SAL. To display the contents of the EMP SALS table.2) NUMBER ENAME. SAL BETWEEN LOSAL AND HISAL. GRADE EMP. Name ------------NAME SALARY GRADE Null? ------Type ------CHAR (10) NUMBER (7. salary and grade details. SALGRADE EMP. GRADE) AS SELECT FROM WHERE Table Created. enter: CREATE TABLE EMP_SALS (NAME. SALSRY.To see the description of DEPT 30.--NUMBER (4) CHAR (10) CHAR(9) NUMBER(7. DESC EMP_SALS.

we shall see how information about the database can be extracted from the Data Dictionary.SELECT FROM NAME --------KNR CSR BAR SNK ISR * EMP_SALS. ALTERING A TABLE Use the ALTER TABLE command to change the definition of a table. 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. Syntax: ALTER TABLE table name ADD clause MODIFY DROP options TO ADD clause DISABLE clause (column_spec[column_constraint]) ENABLE . Also.

2) NUMBER (2) CHAR (10) To add a table constraint to an existing table. To add a column to the EMP tables that will hold the name of an employee’s spouse.Use the add keyword to add a column and/or constraints to an existing 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. . To see a description of the revised table. enter: ALTER TABLE EMP ADD (SPOUSES_NAME CHAR (10). which specifies that the monthly salary must not exceed $5000 enter: ALTER TABLE EMP ADD (CHECK (SAL <=5000)). Table altered.

You may not change a column containing nulls from NULL to NOT NULL.THE MODIFY CLAUSE: Use the MODIFY keyword to modify the definition of an existing column. 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. MODIFY (column type [NULL]. .) To change the width of ENAME to 25 characters. enter: ALTER TABLE EMP MODIFY (ENAME CHAR (25)).2) NUMBER (7. ALTER TABLE name.2) NUMBER (2) CHAR (10) -----------.------- There are four changes that you cannot make: 1.

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

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

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

NULL.DEPTNO) VALUES (7658. a NULL could be specified : INSERT VALUES INTO DEPT (DEPTNO.’SAN JOSE’).TO_DATE(‘24/06/2084 9:30’. As previously mentioned. CHARACTER and DATE values must be enclosed in single quotes: Using Substitution Variables to INSERT Rows.ENAME.LOC) (50.INSERT INTO DEPT(DEPTNO.DNAME.JOB.’&D_NAME’.’MASON’. the format DD-MON-YY is usually used. .MGR.LOC) VALUES (50.’&LOCATION’). With this format the century defaults to the 20th century (19nn). If a DATE needs to be entered in another century and a specified time is also required. Using substitution variables it is possible to speed up input: INSERT VALUES INTO DEPT (DEPTNO.’ANALYST’. use the TO_DATE function: INSERT INTO EMP (EMPNO. INSERTING DATE AND TIME INFORMATION When inserting a DATE value.LOC) (&D_NUMBER. values are prompted for every time. Alternatively if the department name is not known.DNAME.HIREDATE.SAL. The date also contains time information. which is not specified defaults to midnight(00:00:00).7566.COMM.’SAN JOSE’). INSERT is a one-row-at-a-time command. When the command is run. ’DD/MM/YYYY HH:MI’).

SAL.JOB.)] SELECT select-list FROM table(s). UPDATING ROWS The UPDATE statement allows you to change values in rows in a table: UPDATE SET [WHERE table[alias] column [. . enter.ENAME.column…]={expression.…. Note the keyword ‘VALUES’ is not used here. 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.HIREDATE FROM EMP WHERE DEPTNO=10.SAL. To copy all information on department 10 into the D10 HISTORY table. INSERT INTO D10HISTORY (EMPNO.JOB. COPYING ROWS FROM ANOTHER TABLE INSERT INTO table [(column.HIREDATE) SELECT EMPNO.subquery} condition].3000.ENAME. NULL 20).column.

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 . all rows in the table will be updated. It is possible to use nested sub queries and correlated sub queries in the UPDATE statement. HIREDATE=SYSDATE. 1 Record updated.For example : To UPDATE Scott’s row. Suppose you had a table of new commission figures for certain employees. SAL=SAL*1.1 WHERE ENAME = ‘SCOTT’. If the WHERE clause is omitted. enter: UPDATE EMP SET JOB=”SALESMAN”. For example.

• Union • Intersection • Minus . Generally. The total rows retrieved from joining of tables is total rows from first table * total rows from second table. Second row in first table with all rows in second table and so on.EMPNO = 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. 3 Records updated. the tables are joined by using the following common method: Joins the first row in first table with all rows in 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.EMPNO) WHERE EMPNO IN (SELECT EMPNO FROM COMMISSION). JOINING OF TABLES It is a nothing but a method to access data from more than one table.

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

• Columns specified in join conditions should be indexed. Eg: SQL> SELECT ENAME. 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. When n tables are joined. A Cartesian product matches every row of one table to every row of the other table. • 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. • Columns from either table may be names in the SELECT clause. • The WHERE clause specifies how to join or merge the tables together. 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. . LOC FROM DEPT. • As many tables as desired may be joined together. a Cartesian join is performed. EMP WHERE JOB= ‘CLERK’.Join guidelines • The tables to be joined are specified in the FROM clause. • More than one pair of columns may be used to specify the join condition between any two tables. Outer Joins The outer join operator is a plus sign enclosed in parentheses (+). as well “search criteria” as seen with single tables queries. • 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.

DEPTNO.  If multiple columns are required to match for the join. SQL> SELECT LOC. use an outer join  row for rows not meeting the join condition. column (+) = tbale2. DEPT NO (+) = DEPT. the dummy Use the notation (+) after the table/column combination in the rows exist only for the purposes of the outer join. table2 table1. For example. Include departments without employees. WHERE EMP.  WHERE clause that needs the dummy rows (for example. that row ordinarily will not appear in the query’s result. DEPTNO).Syntax: Select From Where Eg: List the locations of all departments and the employees working at those locations. Outer Join Guidelines  columns table1. column If a row in one of the tables of a join does not satisfy the join condition.DEPTNO (+) = DEPT. department 40 in the table DEPT has no matching employees in the table EMP without an outer join.  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. all or none of the columns in a table’s join predicates should have the (+) . the result will not include department 40.  No data is actually added or altered in the table. ENAME FROM EMP. DEPT WHERE EMP.

name. Syntax: SELECT FROM WHERE Eg: List the number. MGR. WORKER. job of each employee.EMPNO MGRNO. and the number. Self Joins A self-join is used to match and retrieve rows that have a matching value in different columns of the same table.column. ENAME.JOB MGRJOB FROM EMP WORKER.MGR=MANAGER.EMPNO. Column = alias 2. . table alias1. table alias2 alias1.ENAME MGRNAME. Column alias2. EMP MANAGER WHERE WORKER. name and job of the employee’s manager. WORKER.  same table. MANAGER. 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.EMPNO.…. the join is on columns that contains the tables. MANAGER. SQL> SELECT WORKER.JOB. 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. Self Join Guidelines  alias 1.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.  same type of information. WORKER. MANAGER.

To delete all information about department 10 from the EMP table. Non-equi joins can be performed using the operators. 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. DELETE [WHERE FROM table condition]. we call them Equi-joins. enter: DELETE WHERE FROM EMP DEPTNO = 10. There are two classes of transactions. therefore. 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. If the WHERE clause is omitted. all rows will be deleted. DML transactions which can consist of any number of DML statements and which ORACLE treats as a . !=< < = > >= BETWEEN DELETING ROWS FROM A TABLE The DELETE command allows you to remove one or more rows from a table.

or none of the changes are carried out (they are all discarded). ROLLBACK allows us to discard or abandon changes. The COMMIT command makes database changes permanent. For every transaction either all the changes made the database are made permanent. 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. where some changes specified within the transaction are made to the database and others are not made. they must be committed to the database. There can be no ‘half-way’ situation during the execution of the transaction. or changes. made to the database between two commit commands therefore make up a transaction. . The change.single entity or logical unit of work. Until a transaction is committed. none of its changes are visible to other users. and DDL transactions which can only consist of one DDL statement. After one transaction ends. Making Changes Permanent In order for changes to become permanent. the next executable SQL statement will automatically start the next transaction.

and assures data consistency in the event of user process failure or system failure. System Failures When a transaction is interrupted by a serious error. for example a system failure. For example. This prevents the error from causing unwanted changes to your data. a transfer of funds (say $ 1000) between two accounts should include the debit to one . A new transaction is started following a commit or rollback that is when the first executable DML or DDL statements is encountered. Errors n entering commands. This is because the errors are detected at parse time (when the SQL statement is scanned and checked). An automatic rollback is most often caused by a system failure. such as misspelling a column name or trying to perform an unauthorised operation on another user’s table.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. do not interrupt a transaction or cause an automatic rollback. Transactions give you more flexibility and control when working with data. In this way SQL *Plus protects the integrity of your tables. not during execution time. and returns your tables to their status at the time of the last commit. the entire transaction is automatically rolled back. THE SIGNIFICANCE OF TRANSACTION ORACLE ensures data consistency based on transactions. such as an uninentional system reset or power blackout. Transactions should consist of only those DML commands that comprises one consistent change to the data.

The three SQL statements used to control transactions are summarised below: COMMIT [WORK] Syntax: COMMIT [WORK]. • You should explicitly end transactions in application programs using the COMMIT (or FOOLBACK) statement. 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.account of $ 1000 and the credit to another account of & 1000. • The keyword WORK is optional. Both actions should either fall or succeed together. the last uncommited transaction will be rolled back. The credit should not be committed without the debit. If you do not explicitly commit the transaction and the program terminates abnormally. • Makes changes in the current transaction permanent • Erases all save points in the transaction (covered below) • Ends the transaction • Releases the transaction’s locks (covered in the next unit). .

. you need not resubmit every statement. • If you create a second savepoint with the same name as an earlier save point. the DDL statement causes a commit to occur prior to its own execution. with the option of later committing that work or undoing all or a portion of it. • The maximum number of savepoints per user process defaults to 5. Then. Thus. This limit can be changed. 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. if the DDL statement executes successfully. for a long transaction. If you enter a DDL statements after entering several DML statements. it too is committed. ending the current transaction. finally committing or rolling back. you can save parts of it as you proceed.• 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. the earlier savepoint is deleted. If you make an error.

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

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

INTRODUCTION TO SQL This chapter provides an introduction to the query language used to access an ORACLE database. to reinstate the database.UPDATE or DELETE command issued. 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) . In particular. ROLLBACK can be issued explicitely by the user. The AUTOCOMMIT option controls when database changes are made permanent. or if you exit from SQL*Plus. ALTER or CREATE command is issued. Also COMMIT is issued if <control> Z (VAX specific) is pressed. when a DROP.COMMIT/ROLLBACK may be issued manually or automatically by using the AUTOCOMMIT option of the SET command. The SQL command set is outlined as well as the basic query block. SET AUTO [COMMIT] OFF COMMIT command can be issued explicitely by the user. There are two settings: Command SET AUTO [COMMIT] ON Description COMMIT issued automatically when each INSERT.

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

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

it is important to remember a few simple rules and guidelines in order to construct valid statements that are easy to read and edit. Refer to the SQL Language References Manual.) at the end of last clause. • Only one statement can be current at any time within the buffer. Any one of the following statements is valid: SELECT * FROM EMP. There are more SQL commands. • An SQL command is entered at the SQL prompt and a subsequent lines are numbered. 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. and it can be run in a number of ways: Place a semi-colon(. This is called the SQL buffer. • SQL commands may be on one or many lines.B. . • 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).REVOKE commands) N. WRITING SQL COMMANDS When writing SQL commands. in the buffer. SELECT *FROM EMP.

MGR EMP. ENAME. THE BASIC QUERY BLOCK The SELECT statement retrieves information from the database. SQL commands are split into clauses in the interests of clarity.e. which specifies the table involved.SELECT* FROM EMP. it must include: 1. In this manual. A SELECT clause. 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 SMITH ALLEN WARD CONES MARTIN BLAKE KNR SCOTT KING TURNER 7698 MGR 7902 7698 7698 7839 7698 7839 7839 7566 . In its simplest form. 2. A FROM clause. implementing all the operators of Relational Algebra. it is essentially a PROJECTION. which lists the columns to be displayed i. To list all department numbers.

performing calculations. Arithmetic expressions may contain column names. ARITHMETIC EXPRESSIONS An expression is a combination of one or more values. constant numeric values and the arithmetic operators: OPERATORS + * / SELECT DESCRIPTION ADD SUBSTRACT MULTIPLY DIVIDE ENAME.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. COMM . • 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. joining columns together. SAL * 12. or displaying literal text strings. operators and functions which evaluate to a value.

use a column alias: ENAME. alias headings will be forced to uppercase and cannot contain blank spaces. SAL+250+12 EMP.FROM EMP. A column alias gives a column an alternative heading on output. . If your arithmetic expression contains more than one operator. In the following example.second (left to right if there are several operators with the same priority). the multiplication (250*12) is evaluated first. In many cases it may be cryptic or meaningless. addition is required before multiplication. then +. the priority is *. Parentheses may be used to specify the order in which operators are executed. unless the alias is enclosed in double quotes (“ “).. for example./ first. So far Smith’s row : 800 + 3000 = 3800. then the salary value is added to the result of the multiplication (3000). By default. To display the column heading ANNSAL for annual Salary instead of SAL * 12. You can change a column’s heading by using an Alias. Specify the alias after the column in the select list. SELECT FROM ENAME. (SAL+250)*12 EMP. if. SELECT FROM COLUMN ALIASES When displaying the result of a query . SQL * Plus normally uses the selected column’s name as the heading.

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

‘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. Null values take up one byte of internal ‘storage’ overhead. ‘WORKS IN DEPARTMENT’ . unassigned. number literals do not need single quotes.A literal in the SELECT list is output for each row returned. Data and character literals must be enclosed within single quotes (‘). A null value is a value which is either unavailable. Literal strings of free format text can be included in the query result. Null values are handled correctly by SQL . and are treated like a column in the select list. FROM EMP. unknown or inapplicable. Zero is a number. The following statement contains literals selected with concatenation and a column alias : SELECT EMPNO // ’-‘ // ENAME DEPTNO. 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. A null value is not the same as zero. that value is said to be null.

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

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

DISTINCT DEPTNO EMP. Note that the DISTINCT qualifier can only be referred to once and must immediately follow the SELECT command word.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. JOB 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. enter : SELECT FROM DISTINCT DEPTNO. THE ORDER BY CLAUSE . To display distinct values of DEPTNO and JOB.

SAL*12. ORDER BY must always be the last clause in the SELECT statement. the command word DESC is specified after the column name in the ORDER BY clause.HIREDATE EMP HIREDATE DESC. so that the latest dates are displayed first. 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.DEPTNO EMP ENAME. If used. JOB.Normally the order of rows returned in a query result is undefined. To sort by ENAME. enter : SELECT FROM ORDER BY ENAME CLARK ALLEN KNR CSR JOB CLERK SALESMAN MANAGER MANAGER ENAME. The ORDER by clause may be used to sort the rows.JOB. To reverse the order of the HIREDATE column. enter: SELECT FROM ORDER BY ENAME JOB ENAME. HIREDATE .

To order two columns. and display in reverse order of salary. SAL DESC. enter: SELECT FROM ORDER BY DEPTNO 10 10 10 20 20 20 20 20 30 30 DEPTNO. 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. Specify the columns to order by. separated by commas. In the ORDER BY clause.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. JOB ENAME EMP DEPTNO. . If any or all are to be reversed. specify DESC after any or each column. it is not necessary to have SELECTed it.

and you should not rely on the ORACLE – determined order being consistent from query to query. A comparison operator 3. 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. and are reported first when rows are sorted in descending order. A column name 2. Without the ORDER BY clause. THE WHERE CLAUSE The WHERE clause corresponds to the Restriction operator of Relational Algebra. WARNING The ORDER BY clause is used in a query when you want to display the rows in a specific order. literal values. the rows are returned in an order convenient to ORACLE. arithmetic expressions or functions. if used.ORDER BY AND NULL VALUES In version 6 of the ORACLE RDBMS. It contains a condition that rows must meet in order to be displayed The WHERE clause. A column name. The WHERE clause expects 3 elements: 1. constant or list of values . Null values are displayed last for ascending sequence. must follow the FORM clause: SELECT FROM WHERE Columns table certain conditions are met The WHERE clause may compare values in columns.

EMP JOB=’CLERK’ EMPNO 7369 7876 7900 JOB CLERK CLERK CLERK DEPTNO 20 20 30 . Number or Date Character strings and dates in the WHERE clause must be enclosed in single quotation marks. To list the names. Refer to “Character Functions” in Unit 4.EMPNO.Comparison Operators are used on the WHERE clause and can be dividend into two categories. numbers.JOB. enter: SELECT FROM WHERE ENAME SMITH ADAMS JAMES ENAME. 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. Character strings must match case with the column value unless modified by a function. job and departments of all clerks.DEPTNO.

suppose you want to find those employees whose commission is greater than their salary. DEPTNO 30 40 COMPARING ONE COLUMN WITH ANOTHER IN THE SAME ROW You can compare a column with another column in the same row.COMM EMP COMM>SAL.SAL. enter : SELECT FROM WHERE DNAME SALES OPERATIONS DNAME.DEPTNO DEPT DEPTNO>20. For example.00 SQL OPERATORS There are four SQL operators which operate with all data types: Operator Meaning . SAL 1250. as well as with a constant value.MILLER 7934 CLERK 10 To find all department names with department numbers greater than 20.00 COMM 1400. enter : SELECT FROM WHERE ENAME MARTIN ENAME.

00 1100. THE IN OPERATOR Tests for values in a specified list.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.00 1250. enter : . SAL 1600.00 1300. and the lower limit must be specified first.SAL EMP SAL BETWEEN 1000 TO 2000. To find all employees who have one of three MGR numbers.00 Note that values specified are inclusive.00 1250.00 Match any of a list of values Match a character pattern Is a null value TURNER 1500.

Symbol % Represents Any sequence of zero or more characters Any single character To list all employees whose name starts with an S.00 MGR 7902 7566 7788 7576 If characters or dates are used in the list they must be enclosed in single quotes (‘ ‘). Using the LIKE operator.SELECT FROM WHERE EMPNO 7369 7788 7876 7902 EMPNO. THE LIKE OPERATOR Sometimes you may not know the exact value to search for. . ENAME. The character pattern matching operation may be referred to as a ‘wild-card’ search. it is possible to select rows that match a character pattern.7566.00 3000. enter: SELECT FROM WHERE ENAME SMITH ENAME EMP ENAME LIKE ‘S%’.00 1100.00 3000.7788) ENAME SMITH SCOTT ADAMS FORD SAL 800.SAL.MGR EMP MGR IN (7902. Two symbols can be used to construct the search string.

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. MGR ENAME EMP ENAME LIKE ‘----‘ . you are testing for a NULL value.SCOTT The ‘-‘ can be used to search for a specific number of characters. So to find all employees who have no manager.MGR EMP MGR IS NULL. SELECT FROM WHERE ENAME KING Negating Expressions ENAME. IS NULL Operator The IS NULL operator specifically tests for values that are NULL.

enter : SELECT FROM WHERE ENAME SMITH JONES BLAKE CLARK SCOTT KING JAMES ENAME.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.00 950.00 3000.00 .00 2975.SAL EMP SAL NOT BETWEEN 1000 AND 2000 SAL 800.UNIX.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.00 2450.00 2950.00 5000.

enter: SELECT FROM WHERE ENAME SMITH ALLEN KNR JONES CLARK SCOTT TURNER ENAME.00 ENAME. MGR 7902 7698 7698 7839 7566 7839 7782 . 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).FORD SELECT FROM WHERE 3000. JOB EMP JOB NOT LIKE ‘M%’. MGR EMP MGR IS NOT NULL.

If these operators are not used and NULL values are compared. whereas the OR predicate will expect wither condition to be ‘true’. See how the result is dramatically changed.00 1. even another NULL. the result is simply always false. The result is false because a NULL value may not be either equal or unequal to any other value. Note than an error is not raised.SAL EMP SAL BETWEEN 1000 AND 2000 JOB = ‘CLERK’. enter : . the result is always FALSE. For example.Note: If a NULL value is used in a comparison. To find all clerks who earn between 1000 and 2000. enter : SELECT FROM WHERE AND EMPNO 7876 7934 EMPNO. COMM!= NULL is always FALSE. the conditions are the same. the predicate is different.100. In the following two examples. ENAME ADAMS MILLER JOB CLERK CLERK SAL 1.ENAME.JOB.00 To find all employees who are either and/or all employees who earn between 1000 and 2000. then the comparison operator should be either IS or IS NOT NULL.300. 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’.

600.SAL EMP SAL BETWEEN 1000 AND 2000 JOB = ‘CLERK’.SELECT FROM WHERE OR EMPNO 7369 7499 7521 7844 EMPNO.975. ENAME SMITH ALLEN WARD KNR JOB CLERK SALESMAN SALESMAN CLERK SAL 800.600.SAL.00 You may combine AND and OR in the same logical expression.450.JOB.100.00 1.DEPTNO EMP SAL>1500 JOB = ‘MANAGER’ JOB = ‘SALESMAN’.JOB. We say that AND has a higher precedence than OR. Since AND has a higher precedence than OR.00 1.00 1. SELECT FROM WHERE AND OR EMPNO 7499 7521 7566 7654 7782 EMPNO. ENAME ALLEN CSR JONES MARTIN KNR JOB SALESMAN SALESMAN MANAGER SALESMAN MANAGER SAL 1. When AND and OR appear in the same WHERE clause.250. and all salesmen.00 2. all the ANDs are performed first then all the Ors are performed.250.00 1.250.00 1. the following SQL statement returns all managers with salaries over $1500.ENAME.00 2.ENAME.00 DEPTNO 30 30 20 30 10 .

We shall discuss the variants in detail later.SAL. the OR operator is evaluated before the AND operator. Oracle does not pad the comparison string and would therefore only retrieve an exact math.DEPTNO EMP SAL > 1500 =’SALESMAN’).00 2.00 2. EMPNO 7499 7566 7698 7782 ENAME ALLEN JONES BLAKE CLARK JOB SALESMAN MANAGER MANAGER MANAGER SAL 1.450.600. the results of a condition involving character data may vary depending on the type of column.If you wanted to select all managers and salesmen with salaries over $1500 you would enter: SELECT FROM WHERE EMPNO.850. number or date values. only one row is returned for the condition: WHERE ENAME=’SCOTT’ .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.ENAME. CHARACTER DATATYPES AND CONDITIONS The basic types of data stored in an Oracle table are character. In the first example opposite. Oracle provides column type CHAR for fixed length values and type VARCHAR2 for variable length values in a column.975.00 2. For VARCHAR2 columns. However.JOB.

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

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

ASC ascending order is the default sorting order and need not be specified. and tabulation used for clarity and ease of editing. PROGRAMMING STRUCTURE [DECLARE Declarations …. Looping structure (For. always appears last. Means it provides all facilities like other programming language such as conditional statements (If). One or more columns may be specified. PL/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.It is a procedural language which allows to perform database transactions programmatically. PL / SQL Procedural Language / Structured Query Language The SQL is a non-procedural language. while etc) & programming blocks.] BEGIN . Goto statement.() ORDER BY can be used to force priority. For SQL. Specified sort order. Clauses may be entered on separate lines in the buffer.

. exceptions. The programming block in PL/SQL includes the following three sections 1. This is an optional section. Programming part : It is a set of SQL statements to perform a required task.] END. 3. They are INT (or) INTEGER (or) SMALL INT POSITIVE REAL DOUBLE – PRECISION CHAR VARCHAR Floating Values Integers with Positive . Declare section that allows to declare variables.Statements [Expections …. constants cursors. Exceptions : The statements specified in this section will automatically executes when ever a database transaction is failed specified before the exceptions. The programming part must be enclosed with key words BEGIN & END. DECLARE: Declaration of variables Variable name Data type To define a name you must follow the rules to define a name in Oracle. subranges data types & so on. 2. It supports all data types available in SQL and besides that provides the following additional data types. END must be terminated by semi-colon.

A variable can be initialised Ex : A Integer := 100. . Declaration of list of variables are also not allowed. 5. Date := SYSDATE. Character. B Integer. Declaring Constants Variable name CONSTANT Datatype := expression. Ex : A . We can declare the variable with default values. Note : Whenever a variable declared with NOT NULL constraint and that must be initialised with a particular value. 2. We can use NOT NULL Constraint to declare variables Ex : A Integer NOT NULL := 100.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. CITY Varchar(30) := ‘GUNTUR’. Ex : A Integer Default 100. CDATE Not allowed 4. 3.

Amt Real. Rate Real. Ex : x ** y => xy (Assignment) := Sample Program DECLARE Qty Real. DBMS_OUTPUT It is pre-defined package provided by the Oracle system.Ex : Height CONSTANT program execution. [Only one string] .* Exponential operator Ex : x:=3. Syntax : PUT-LINE (STRING). (Arithmatic) *. Amt := Qty * Rate. & Substitution variable that allows to enter data through keyboard. END. 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. BEGIN Qty := & QUANTITY. Integer := 100.PUTLINE (‘Amount is’|| Amt). Procedures to implement various types of output operations in that PUT-LINE is one of the procedure. This package provides the std. DBMS_OUTPUT. Rate := & RATE.

It load the file contents. if not creates a new file. Credit % type. It declares a variable debit using the type of the variable credit. Eg: 1) Declare Credit Debt Real (8.e. It declares a variable CUST-CODE by using the type of column custid in the table customer. After doing modifications save and exit from the editor. i. SQL > SQL>Set Server output ON Host notepad file name . 2) CUST-CODE customer custid % type. you must set the SERVEROUTPUT variable to on at SQL prompt.SQL.2). SQL > a) File name – to run the program b) First.Note: Whenever you want to use the DBMS OUTPUT procedure in PL/SQL programming. % Row type: This attribute declares a record type variable of a .SQL It opens the notepad editor. If the said file name is already existing. Using % Type And % Row Type Attributes % Type: It defines a new variable of the type of another variable.

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

TM/3. DBMS− OUTPUT.BEGIN M1 M2 M3 TM AM := := := := := & Marks1. Else DBMS− OUTPUT. PUT-LINE (‘AVERAGE MARKS’ || AM). integer. DBMS− OUTPUT. PUT-LINE (‘B IS BIGGEST’) End IF. PUT-LINE (‘TOTAL MARKS‘ || TM). / CONDITIONAL STATEMENT: IF Syntax: If Condition then Statement –1. & Marks2. Eg: DECLARE A B Begin A B := := &A. PUT-LINE (‘A IS BIGGEST’). M1+M2+M3. &B. & marks 3. [else statement-2] End if. End. If A>B then DBMS− OUTPUT. integer. / . End.

Avg := If Ang > 119 then DBMS-OUTPUT. integer. & M2.50 2. Real (6. integer.00 12. P-CODE 1 2 3 4 Others DECLARE RATE 17.2). The amount as per the given table.00 . PUT-LINE (‘STUDENT HAS FAILED’). End. When the student secured more than (or) equals to 120 marks in 3 subjects.75 4. integer. End If.2) Write a program to read total marks of a student confirm whether the student is passed (or) not. M1 + M2 + M3 . & M3.80 6. / 3) Write a program to read quantity purchased & P-code calculated. DECLARE M1 M2 M3 Avg BEGIN M1 M2 M3 := := := & M1. PUT-LINE (‘STUDENT HAS PASSED’) Else DBMS-OUTPUT.

DBMS-OUTPUT . := Qty * 2. / Other form of if statement If condition then Statement –1. PUT-LINE (‘TOTAL AMOUNT IS’ || Amt). Real (8.75.Quantity P-code Amt BEGIN Qty p-code Real (8. ElsIf condition then Statement-2. 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. Integer. End If. . End If. End If. Qty * 17. End If.80. & Product Code.00.2).2).50. End. := := 3 then qty * 4. := := & Quantity. := Amt * 12.00 := := 4 then qty * 6.

00. This statement unconditionally transfers control to the specified label. This name must be enclosed by angular brackets as given below when you want to use in source code.00. LOOPING STRUCTURES GOTO Label name := Qty * 12. Label name : The name of the label & it must satisfy the rules to define a name in Oracle.80 4 then Qty * 6.. 3 then Qty * 4. 2 then Qty * 2. [Else statement-n.50. .] End If. := := := := := := := := 1 then Qty * 17. IF P-code Amt Elsif p-code Amt Elsif p-code Amt Elsif p-code Amt Else Amt End if.75. <<Label name>> Ex: DECLARE I BEGIN << Start Print>> Integer := 1.

END. END LOOP. 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. End Loop . / FOR LOOP Syntax: FOR Var In [REVERSE] Statements.PUT-LINE(‘----‘|| I). GOTO END IF.DBMS-OUTPUT. Ex : DECLARE I BEGIN For I IN 1 . Start …….. END.10LOOP DBMS-OUTPUT.PUT-LINE (‘-----‘|| I). If I<10 Then start-print. / WHILE LOOP Syntax : WhileCondition Loop Integer. I := I+1. If REVERSE clause is used it starts from End decremented by 1 for every iteration until it reaches start value.

. Update & Delete. 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.PUT-LINE (‘----‘ || I). END. Ex : DECLARE I BEGIN While I < 10 I := I + 1. Where as the select statement must be used with ‘INTO’ clause in PL/SQL programs. It repetedly executes the statements till the conditions set to true. Loop DBMS-OUTPUT. List || *} From Into Var-list table-name [WHERE condition] …. retrieval statement – select. Syntax : SELECT FROM Var-list {Expr. End Loop.Statement. The list of variables declared in PL/SQL program in which you want to store the retrieved data. / DATA BASE OPERATIONS PL/SQL programming supports all database transactional statements like Insert. Integer := 1. Ex : DECLARE CCODE Integer. End Loop.

/ USE EXCEPTION CLAUSE in PL/SQL in program to avoid errors in program. CNAME := & Customer-name. WHEN OTHERS THEN Statements. Syntax : EXCEPTION Statements. ……. EXCEPTION – NAME The name of the exception handles (or) error EXCEPTION NO-DATA FOUND Raised If No rows are retrieves from query .CNAME CADDR BEGIN Varchar2(30). Varchar2(30). WHEN EXCEPTION-NAME THEN WHEN EXCEPTION-NAME THEN INTO CUSTOMER Values (CCODE. Statements. CCODE := & Customer-code. CADDR := & Customer-Addr. CADDR). CNAME. Statements. INSERT END.

PUT-LINE (‘NAME ---‘ || CNAME). Integer. PUT-LINE (‘CUSTOMER DETAILS…’). WHEN TOO-MANY-ROWS THEN DBMS-OUTPUT. . PUT-LINE (‘ADDRESS ---‘ || CADDR). DBMS-OUTPUT. Varchar2(30). EXCEPTION WHEN NO-DATA –FOUND THEN DBMS-OUTPUT. Caddr From CUSTOMER Where CUST Code = Ccode.TOO-MANY ROWS Query retrieves more than one row ZERO-DIVIDE When the divisor is zero. Select Custname. OTHERS Other than the above mentioned exception Handlers (These are all predefined exceptions) Eg: Declare Ccode Cname Caddr Begin Ccode := &customer-code. PUT-LINE (‘NO DETAILS ARE FOUND’). PROGRAM – ERROR When an internal program error has occurred. PUT-LINE (‘MANY ROWS ARE retrieved’). Custaddr INTO Cname. DBMS-OUTPUT. Varchar2(30). in an SQL expression INVALID – NUMBER A number to be converted into numeric form is Invalid. DBMS-OUTPUT.

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

CURST REC TAKING ALL COLUMNS IF CUSTOMER TABLE) Begin OPEN CUST-CURSOR. Eg: FETCH CUST-CURSOR INTO CUSTREC. (CREATES A RECORD VIZ. Declare CURSOR CUST-CURSOR IS SELECT * FROM CUSTOMER. .’ || CUST REC. 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. LOOP FETCH CUST-CURSOR INTO CUST REC. This statement fetches the current cursor row into the list of variables. CURST REC CUSTOMER % ROW TYPE.2) FETCH: Fetch cursor-name Into var-list. DBMS-OUTPUT. PUT-LINE (CUST REC. Eg: CLOSE CUST-CURSOR. Eg: CUST-CURSOR % NOT FOUND. 3) CLOSE: CLOSE CURSOR-NAME. It closes the opened cursor.’| | CUSTREC. ADDR | ). END LOOP. NAME ||’. Syntax: CURSOR-NAME % ATTRIBUTE. EXIT WHEN CUST-CURSOR % NOT FOUND. SNO ||’.

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

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

Eg. BILLAMT > 1000 THEN BILL-CURSOR. SELECT * FROM BILLS FOR UPDATE. BEGIN OPEN LOOP FETCH BILL-CURSOR INTO BILLREC. BILL REC BILLS % ROWTYPE.CURSORS WITH FOR UPDATE CLAUSE The FOR UPDATE CLAUSE locks the rows Syntax : CURSOR Cursor-name[(arg-list)] IS QUERY FOR UPDATE. Eg. : CURSOR BILL-CURSOR IS DECLARE CURSOR BILL-CURSOR IS SELECT * FROM BILLS FOR UPDATE. INTEREST REAL. (2) DELETE statement WHERE CURRENT OF CURSOR-NAME. . 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. EXIT WHEN BILL-CURSOR % NOT FOUND. : (1) UPDATE statement WHERE CURRENT OF CURSOR-NAME. IF BILLREC.

END. END LOOP.BILL AMT > 500 THEN INTEREST = BILLREC. DECLARE CURSOR CUST-CURSOR IS. 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. ENDIF. CLOSE BILL-CURSOR. BILLAMT * 0.INTEREST = BILLREC. ELSE IF BILLREC. Open. END LOOP. Fetch & close statements while you are working with a cursor i.BILLAMT * 0. UPDATE BILLS SET BILL AMT = BILLAMT + INTEREST WHERE CURRENT OF BILL-CURSOR.04.e.03. CLOSE BILL-CURSOR. END LOOP.02. a single CURSOR FOR LOOP statement will replace all the above four statements Syntax : FOR Variable Statements. / CURSOR FOR-LOOPS It will provide a facility to reduce the usage of Loop statement. …. BILLAMT * 0. IN CURSOR-NAME LOOP . ELSEINTEREST = BILLREC.

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

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

’&CNAME’. PUT-LINE (‘NULL VALUES NOT ACCEPTED IN END. CUSTOMER CODE’). STRING REVERSE .’&CADDR’). EXCEPTION WHEN NULL-VALUE CHECK THEN DBMS-OUTPUT. Eg.CHECK. / ERROR FUNCTIONS 1. PRAGMA EXCEPTION INIT (NULL-VALUE. BEGIN INSERT INTO CUSTOMER VALUES (&CCODE. SQL CODE. Eg. SQLERRM (err-num).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. Mandatory Entry. : SQLERRM (1400). SQL ERRM Syntax : It returns the error code related to the last database transaction. : DECLARE NULL-VALUE-CHECK EXCEPTION.-01400). SQL CODE Syntax : 2. Returns an error message related to the given error codes.

L LOOP L : = Substr(SI. 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. DELETE. A data base trigger has 3 main parts 1.1) S2 = C|| S2. Classification of Triggers: Main trigger events Sub trigger events : : INSERT.I. Row level : A row level trigger executes for each .For I IN 1…. Trigger event 2. 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. UPDATE Before & After – These classes controls the execution of triggers before the event is occurred after the event is completed respectively. End Loop. Trigger Constraint 3. DATABASE TRIGGERS A trigger is a PL/SQL programming block which can automatically executes depending on a particular situation.

The table name on which you want to create a trigger. It is a restriction to the trigger. Custname := Upper (:New.row in a transaction. New. 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. Statement level : This trigger will execute for every transaction. Create or Replace Trigger Upper convert Before Insert on customer for each you. Custoaddr := Upper (:New. . This clause designates whether the trigger is row level (or) statement level. Begin : : New. If this clause is defined the trigger will be row level. If omitted. When condition : Eg: 1) When the values entered into custname & custaddr are to be converts in upper case before insertion of values.Custname). Custaddr). the trigger will be statement level.

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

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

SQL> Select calcamount (123. R IN REAL) RETURN REAL AS Begin RETURN Q * R. IN Specifies that you must supply a value for the argument when calling the function. .48 From PL/SQL program DECLARE Qty real. precision (or) scale.function does not accept arguments while calling. CREATE OR REPLACE FUNCTION CALC-AMOUNT (Q IN REAL. Return Data type Eg: Specifies the data type of function’s return value. Rate real. It cannot specify length. / Note: Is –when you want to declare local variable you must use ‘IS’. O/P% Calcamount 5628. End . 45. As – in all other cases. Data type Is the type of data of an argument. Calling Functions: You must use select statement while calling a function from SQL prompt as given below.76) from DUAL.

rate). := & quantity. Droping Functions: Drop Function command is uses to remove a function from the database permanently. 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 [. Amt := calcmount (Qty. IN Specifies that you must specify the value for the argument . DBMS – OUT PUT. PUT-LINE (‘AMOUNT IS‘ | | AMT). DROP FUNCTION function-name. End. Eg: Drop function calcamount. ARGUMENT [IN | AT | IN OUT ] DATA TYPE] …)] {IS |As} PL/SQL –sub program –body.Amt BEGIN Qty real. Rate := & Rate. / 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.

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

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

]PACKAGE {IS|AS} PL/SQL-PACKAGE-BODY. / Creating a Package Body: Used to create the body of – stored package. Eg: CREATE OR REPLACE PACKAGE SAMPLE-PACK AS FUNCTION BILLS TOTAL (CODE IN INTEGER) RETURN REAL.. functions and other program objects stored together in the database.] package {is | As} PL/SQL – package – SQL.Creating a Package Specification: The command CREATE PACKAGE is used to create the specifications for a stored package. Syntax: Create [or replace] package [scheme. END SAMPLE-PACK. Package: The name of the package you want to create. . The specification is the collection of related procedures. 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. CREATE [OR REPLACE] PACKAGE-BODY [SCHEMA. That must be similar to the package name used in package specification. PROCEDURE SHOWMSG.

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. END BILLS TOTAL.name COMPILE.Name To remove the package specification from the database permanently. Use these commands to recompile the stored procedures. End sample-pack. O/P : Welcome to package programming. ALTER procedure procedure-name COMPILE. End showmsg. Compiling stored Procedure ALTER function function.RETURN (BAMT). (‘WELCOME TO PACKAGE .name COMPILE [body]. ALTER package package.PUT-LINE PROGRAMMING’). / Calling a Member in a Package: Use dot notation method to call a remember in package. Syntax: Drop Package-Body Package-name. Eg: Execute sample-pack showmsg. Drop Package: Syntax: Drop Package Package. Procedure Showmsg as Begin DBMS-OURPUT.

Eg: Select TEXT from user-source where NAME = ‘IS PRIME’ it lists the programming part.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. Creating a user – (Environment must not be scott(tiger) to create an user. Eg: SQL> SELECT DISTINCT NAME FROM USER-SOURCE WHERE TYPE = ‘FUNCTION’. Eg: SELECT LINE. it lists the text with line numbers. 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. 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. TEXT FROM USER-SOURCE where NAME = ‘IS PRIME’. packages and package body. it lists the function names. SQL> COLUMN TEXT FURMAT ‘A50’. . procedures. (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. use the command CREATE USER.

if we want to do all these things you must associate related privileges or roles to the user by using grant command. Connect role CONNECT RESOURCE and DBA : Allows the user to logon to the database and allows to manage the objects like tables. But.{System-priv | role}]…. The GRANT command is used to grant system privileges and roles to users and roles. The user must specify this password to logon. Identified by password - Eg: SQL> CREATE USER CLASS 79 IDENTIFIED BY MYCLASS.Syntax: CREATE USER uses IDENTIFIED {BY PASSWORD. EXTERNALLY} User: The name of the user we want to create. views . 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. To {user | role| PUBLIC } [. Syntax: Grant {System – priv | role} [.user | role | PUBLIC}]…. snap shots. [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.

DBA TO CLASS 79 O/P : Grant succeeded. Eg: GRANT CONNECT. TRIGGER. Resource role: It has the privileges from connect and besides that it has additional privileges like CREATE FUNCTION. With admin option: Allows the grantee to grant system privileges or roles to other users & roles. PROCEDURES. Dba Public : : Allows the user to create another user. SQL> CONNECT CLASS 79/NEWPASS . Grant system privileges and rows to all users. Changing Password to a user: Eg: GRANT CONNECTS TO CLASS 79 IDENTIFIED BY NEWPASS.password] [@database-specification] Disconnect Command: Detaches the current user from the data base.clusters. Syntax : conn[ect] [logon] Logon : Requires the following syntax User name [.……. RESOURCE.. SQL> CONNECT CLASS79/MYCLASS Connecting to the user: A command CONNECT allows the user to connect to a required user.

To create a new table under their schema.{USER|ROLE|PUBLIC}]….{SYSTEM-PRIV|ROLE}]…… FROM {USER|ROLE| PUBLIC} [. shop shots etc. Eg: REVOKE RESOURCE FROM CLASS 79. Eg: Create schema myschemal..). Creating a Schema: CREATE SCHEMA AUTHORIZATION SCHEMA { CREATE TABLE command | CREATE VIEW command | GRANT Command}… Where Schema The name of the schema. Person (-.--. we can create more than 1 schema under one user. views. It must be the same as your Oracle user name.-.-. Syntax: REVOKE { SYSTEM-PRIV | ROLE } [. Grant It is – grant statement (objects privileges) to be issued & part of this create schema statement. The Oracle system will create a difficult scheme wit the name if the uses to be created.Revoke Command: It revoke system privileges and roles from user and roles. SQL> CREATE SCHEMA myschemal. 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. But.-.

Is the name of the synonym to be created.). package. stored function. Syntax: CREATE [PUBLIC] SYNONYM [SCHEMA] SYNONYM For [schema] object [@ db link] Public Creates a public synonym public synonyms are assessable to all user. procedure. shop shot or another synonym.--. if there exists more than one Synonym For @db link - . identifies the objects for which synonym is created.-. 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.-.It creates a table person under schema my schemal. view. Schema Is the schema to contain the synonym. If you omit this option the synonym is private a is assessable only within its schema. 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 (-. to specify the server name.

Table It is a right angular matrix where rows are called as Tuples & columns are called as attributes.sales. Distributed processing 7. passwords .person For Y. Integrity rule 5. Syntax: DROP [PUBLIC] SYNONYM [SCHEMA] SYNONYM Eg: Drop synonym X. view. Null value use 4. Data dictionary concept 6.server.person for the object Y. Droping synonyms : Drop synonym command is used to remove a synonym from the database. 2. Syntax: Rename old to new Eg: Rename person to Friend. Eg: Create synonym X. Create synonym X.person. Security arrangements 3. Rename To rename a table. CODD RULES 1.person. Normalization Arranging users.Sales (Creates synonym for the some user’s table) For sales. sequence or private synonym. It creates a synonym X.

.RDBMS must satisfy 6 database rules of minimum.

Sign up to vote on this title
UsefulNot useful