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.

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

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

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

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

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

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

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.


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



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



Floating point number with precision of 38 significant digits.



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 values from January 1,4712 BC to December 1,4712 AD. Time information is also stored.



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


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

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

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

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

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

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


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

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

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

To see a description of the revised 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.2) NUMBER (2) CHAR (10) To add a table constraint to an existing table.2) NUMBER (7. . 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)). 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. Table altered.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

• The keyword WORK is optional.account of $ 1000 and the credit to another account of & 1000. Both actions should either fall or succeed together. • 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). The three SQL statements used to control transactions are summarised below: COMMIT [WORK] Syntax: COMMIT [WORK]. . CONTROLLING TRANSACTIONS WITH SQL STATEMENTS The following SQL statements are used to control when commit or rollback occur: • COMMIT [WORK] • SAVEPOINT savepoint_name • ROLLBACK[WORK] to [SAVEPOINT] savepoint_name Note that COMMIT and ROLLBACK are SQL statements. The credit should not be committed without the debit. the last uncommited transaction will be rolled back. • You should explicitly end transactions in application programs using the COMMIT (or FOOLBACK) statement. If you do not explicitly commit the transaction and the program terminates abnormally.

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

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

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

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

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

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

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

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

Arithmetic expressions may contain column names. ARITHMETIC EXPRESSIONS An expression is a combination of one or more values. joining columns together. SAL * 12. COMM . or displaying literal text strings.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. operators and functions which evaluate to a value. for example. performing calculations. constant numeric values and the arithmetic operators: OPERATORS + * / SELECT DESCRIPTION ADD SUBSTRACT MULTIPLY DIVIDE ENAME. • Arithmetic expressions • Column aliases • Concatenated columns • Literals All of these options allow the user to query data and manipulates it for query purposes.

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

Once defined. expression. 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. number included on the SELECT list which is not a column name or a column name or a column alias. a column alias can only be used in the SELECT clause. To combine EMPNO and ENAME and give the alias EMPLOYEE to the expression. SAL*12 ANNSAL. arithmetic expressions or constant values to create a character expression. COMM EMP. Note: Within a SQL statement. an alias can be used with SQL * Plus commands which are dealt with in Units 10 and 11. KNR ALLEN MARTIN SCOTT EMPNO//ENAME EMP.SELECT FROM ENAME. EMPLOYEE . THE CONCATENATION OPERATOR The concatenation operator (//) allows columns to be linked to other columns.

Null values are handled correctly by SQL . Zero is a number. unassigned.A literal in the SELECT list is output for each row returned. Literal strings of free format text can be included in the query result. EMPLOYEE 7369 SMITH 7499 ALLEN 7521 KNR 7566 JONES 7654 CSR 7698 BLAKE HANDLING NULL VALUES If a row lacks a data value for a particular column. that value is said to be null. ‘WORKS IN DEPARTMENT’ WORKS IN DEPARTMENT WORKS IN DEPARTMENT WORKS IN DEPARTMENT WORKS IN DEPARTMENT WORKS IN DEPARTMENT WORKS IN DEPARTMENT DEPTNO 20 30 30 20 30 30 EMPLOYEE. ‘WORKS IN DEPARTMENT’ . unknown or inapplicable. FROM EMP. A null value is a value which is either unavailable. The following statement contains literals selected with concatenation and a column alias : SELECT EMPNO // ’-‘ // ENAME DEPTNO. Data and character literals must be enclosed within single quotes (‘). A null value is not the same as zero. Null values take up one byte of internal ‘storage’ overhead. number literals do not need single quotes. and are treated like a column in the select list.

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

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

DISTINCT DEPTNO EMP.To eliminate the duplicate values displayed in the previous example. THE ORDER BY CLAUSE . 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. Note that the DISTINCT qualifier can only be referred to once and must immediately follow the SELECT command word. To display distinct values of DEPTNO and JOB. JOB EMP. enter : SELECT FROM DEPTNO 10 20 30 Multiple columns may be specified after the DISTINCT qualifier and the DISTINCT affects all selected columns.

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

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

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

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

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

SAL 1600.00 Match any of a list of values Match a character pattern Is a null value TURNER 1500.SAL EMP SAL BETWEEN 1000 TO 2000.00 1100.00 1250.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.00 Note that values specified are inclusive. Suppose we want to see those employees whose salary is between 1000 and 2000: SELECT FROM WHERE ENAME ALLEN WARD MARTIN ADAMS MILLER ENAME. THE IN OPERATOR Tests for values in a specified list.00 1250. enter : . To find all employees who have one of three MGR numbers. and the lower limit must be specified first.00 1300.

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

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

00 2975.00 950.00 .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 2450.00 2950.00 5000.00 3000. enter : SELECT FROM WHERE ENAME SMITH JONES BLAKE CLARK SCOTT KING JAMES ENAME.SAL EMP SAL NOT BETWEEN 1000 AND 2000 SAL 800.The following operators are negative tests: OPERATOR != ^= <> NOT COLNAME= NOT COLNAME> SQL OPERATORS OPERATOR NOT BETWEEN NOT IN NOT LIKE IS NOT NULL DESCRIPTION Not between two given values Not in given list of values Not like string Is not a null value DESCRIPTION Not equal to (VAX.UNIX.


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

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

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

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

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

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

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

Ex : A . 2. Date := SYSDATE. Ex : A Integer Default 100. Declaring Constants Variable name CONSTANT Datatype := expression. B Integer. 3. Declaration of list of variables are also not allowed. Note : Whenever a variable declared with NOT NULL constraint and that must be initialised with a particular value. We can declare the variable with default values. Character. CITY Varchar(30) := ‘GUNTUR’. We can use NOT NULL Constraint to declare variables Ex : A Integer NOT NULL := 100. You must use one line for one declaration Ex : A C Integer. . A variable can be initialised Ex : A Integer := 100.VARCHAR2 LONG CHARACTER STRING BOOLEAN Logical Data Type Points to be considered while declaring a variable 1. 5. CDATE Not allowed 4.

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

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

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

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

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

Quantity P-code Amt BEGIN Qty p-code Real (8.50. If p-code =1 then Amt := Else If p-code =2 then Amt Else If p-code Amt Else If p-code Amt Else If Qty Eno If.2). DBMS-OUTPUT . := := & Quantity. Real (8. := Qty * 2. & Product Code.75. / Other form of if statement If condition then Statement –1. End If. Integer.00 := := 4 then qty * 6. ElsIf condition then Statement-2.00. End If. . := Amt * 12. := := 3 then qty * 4. PUT-LINE (‘TOTAL AMOUNT IS’ || Amt). Qty * 17.2).80. End If. End If. End.

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

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

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

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

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

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

Declare CURSOR CUST-CURSOR IS SELECT * FROM CUSTOMER. . (CREATES A RECORD VIZ. DBMS-OUTPUT. Eg: CUST-CURSOR % NOT FOUND. 3) CLOSE: CLOSE CURSOR-NAME. NOT FOUND Returns true if no record is available. This statement fetches the current cursor row into the list of variables. PUT-LINE (CUST REC. CURST REC CUSTOMER % ROW TYPE. ADDR | ). EXIT WHEN CUST-CURSOR % NOT FOUND. CURST REC TAKING ALL COLUMNS IF CUSTOMER TABLE) Begin OPEN CUST-CURSOR. NAME ||’. CURSOR ATTRIBUTES % % FOUND It returns true if a row is available in cursor other wise false. END LOOP.’ || CUST REC.2) FETCH: Fetch cursor-name Into var-list. LOOP FETCH CUST-CURSOR INTO CUST REC.’| | CUSTREC. Eg: CLOSE CUST-CURSOR. Syntax: CURSOR-NAME % ATTRIBUTE. SNO ||’. It closes the opened cursor. Eg: FETCH CUST-CURSOR INTO CUSTREC.



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

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

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

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

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

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

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

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

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

SQL> Select calcamount (123. Calling Functions: You must use select statement while calling a function from SQL prompt as given below. Rate real.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. precision (or) scale. Data type Is the type of data of an argument.76) from DUAL. As – in all other cases. End . / Note: Is –when you want to declare local variable you must use ‘IS’. IN Specifies that you must supply a value for the argument when calling the function. It cannot specify length. 45.48 From PL/SQL program DECLARE Qty real. R IN REAL) RETURN REAL AS Begin RETURN Q * R. . O/P% Calcamount 5628.

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

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

SQL & create procedure update-due (ccode in integer) is dueamt real.O) + DUE AMT WHERE CUSTCODE = CCODE. Although sometimes the body is unnecessary. Drop Procedure Procedure Name. UPDATE CUSTOMER SET DUE AMOUNT= NVL (DUE AMOUNT. Droping Procedures: The command Drop Procedure is used to remove a stored procedure object from the database permanently. End.Altering Procedures: To alter a procedure definition use OR REPLACE clause. . Example For Database Related Procedure SQL> HOST NOTEPAD Pros. / SQL> Execute update-due PACKAGES A package is a database object that groups logically related PL/SQL type objects and subprograms. Packages usually have 2 parts a specification & a body. Eg: Drop Procedure showing. The body holds implementation details. 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.

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

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

TEXT FROM USER-SOURCE where NAME = ‘IS PRIME’. SQL> COLUMN TEXT FURMAT ‘A50’. . Viewing Stored Objects (or) Procedures: The oracle provides a view with the name USER-SOURCE to maintain all stored object details like function. packages and package body.Eg: Alter function BILLS TOTAL COMPILE. Eg: SQL> SELECT DISTINCT NAME FROM USER-SOURCE WHERE TYPE = ‘FUNCTION’. 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. use the command CREATE USER. (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. procedures. Eg: Select TEXT from user-source where NAME = ‘IS PRIME’ it lists the programming part. it lists the function names. Creating a user – (Environment must not be scott(tiger) to create an user. Eg: SELECT LINE. 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.

Identified by password - Eg: SQL> CREATE USER CLASS 79 IDENTIFIED BY MYCLASS.Syntax: CREATE USER uses IDENTIFIED {BY PASSWORD. But.{System-priv | role}]…. The user must specify this password to logon. 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. EXTERNALLY} User: The name of the user we want to create. snap shots. 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. [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. Syntax: Grant {System – priv | role} [. The GRANT command is used to grant system privileges and roles to users and roles.user | role | PUBLIC}]…. views . To {user | role| PUBLIC } [.

DBA TO CLASS 79 O/P : Grant succeeded. Changing Password to a user: Eg: GRANT CONNECTS TO CLASS 79 IDENTIFIED BY NEWPASS. RESOURCE. SQL> CONNECT CLASS79/MYCLASS Connecting to the user: A command CONNECT allows the user to connect to a required user.password] [@database-specification] Disconnect Command: Detaches the current user from the data base. TRIGGER.. Grant system privileges and rows to all users.…….clusters. 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. Dba Public : : Allows the user to create another user. Eg: GRANT CONNECT. Syntax : conn[ect] [logon] Logon : Requires the following syntax User name [. PROCEDURES. SQL> CONNECT CLASS 79/NEWPASS .

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

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

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

RDBMS must satisfy 6 database rules of minimum. .

Sign up to vote on this title
UsefulNot useful