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.

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

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

Often produces a very large new set. . It is possible to display all rows. PROJECTION Is an operation that displays certain columns from the relation. All rows in the first set are concatenated with rows in the second set. and is therefore often called a “vertical subset”. Data retrieval is achieved by means of relational operations on tables RELATIONAL OPERATORS The relational operators are defined below Relational RESTRICTION Description Is an operation that gets and displays data from the relation. UNION Displays all rows that appear in either or both of two Relations. or just rows that meet a condition or many conditions.• 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. INTERSECTION Displays all rows that appear in both of two relations. This is sometimes called a “horizontal subset”.

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

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

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

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

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

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

LOC) . DNAME VARCHAR2 (9). NULLS are allowed if the Unique Key is based on a single column.…) Column constraint syntax: [CONSTRAINT constraint_name] UNIQUE For example.Where n is a unique number. The keyword CONSTRAINTS allows you to name a new constraint yourself. column. LOC VARCHAR 2(10). Table constraint syntax: ‘[CONSTRAINT constraints_name] UNIQUE (column. CONSTRAINT UNQ_DEPT_LOC UNIQUE (DNAME. to ensure that there are never two indentical department names at a single location: CREATE TABLE DEPT (DEPTNO NUMBER. Constraints types You may define the following constraint types: − NULL/NOT NULL − UNIQUE − PRIMARY KEY − FOREIGN KEY(REFERENTIAL INTEGRITY) − CHECK UNIQUE Constraint: This designates a column or combination of columns as a unique key. No two rows in the table can have the same value for this key.

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

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


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

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

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. we shall see how information about the database can be extracted from the Data Dictionary. Also. Syntax: ALTER TABLE table name ADD clause MODIFY DROP options TO ADD clause DISABLE clause (column_spec[column_constraint]) ENABLE . 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.

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. 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. 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. 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)). .2) NUMBER (7. Table altered.

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

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

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

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

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

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

It is possible to use nested sub queries and correlated sub queries in the UPDATE statement. all rows in the table will be updated.1 WHERE ENAME = ‘SCOTT’. If the WHERE clause is omitted. HIREDATE=SYSDATE. For example. the COMMISSION table below is to be used to update certain rows at the EMP table: COMMISSION EMPNO 7499 7654 7844 7844 7844 COMM 1100 500 500 2000 1500 EMP EMPNO 7499 7654 7844 COMM 300 1400 0 The changes in the COMMISSION table can be applied to the EMP . 1 Record updated.For example : To UPDATE Scott’s row. enter: UPDATE EMP SET JOB=”SALESMAN”. SAL=SAL*1. Suppose you had a table of new commission figures for certain employees.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

DISTINCT DEPTNO EMP. enter : SELECT FROM DEPTNO 10 20 30 Multiple columns may be specified after the DISTINCT qualifier and the DISTINCT affects all selected columns.To eliminate the duplicate values displayed in the previous example. DEPTNO JOB 10 10 10 20 20 20 CLERCK MANAGER PRESIDENT ANALYST CLERK MANAGER This displays a list of all the different combinations of jobs and department numbers. Note that the DISTINCT qualifier can only be referred to once and must immediately follow the SELECT command word. To display distinct values of DEPTNO and JOB. THE ORDER BY CLAUSE . enter : SELECT FROM DISTINCT DEPTNO. JOB EMP.

the command word DESC is specified after the column name in the ORDER BY clause.DEPTNO EMP ENAME. If used. The ORDER by clause may be used to sort the rows.HIREDATE EMP HIREDATE DESC.JOB.SAL*12. HIREDATE . To sort by ENAME. ORDER BY must always be the last clause in the SELECT statement. JOB. enter : SELECT FROM ORDER BY ENAME CLARK ALLEN KNR CSR JOB CLERK SALESMAN MANAGER MANAGER ENAME. so that the latest dates are displayed first. enter: SELECT FROM ORDER BY ENAME JOB ENAME. SAL*12 13200 19200 34200 29400 DEPTNO 20 30 30 10 DEFAULT ORDERING OF DATA The default sort order is ASCENDING: • Numeric values lowest first • Date values earliest first • Character values alphabetically REVERSING THE DEFAULT ORDER To reverse this order. To reverse the order of the HIREDATE column.Normally the order of rows returned in a query result is undefined.

and display in reverse order of salary. If any or all are to be reversed.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 ENAME EMP DEPTNO. specify DESC after any or each column. SAL DESC. The limit is the number of columns on the table. Specify the columns to order by. separated by commas. enter: SELECT FROM ORDER BY DEPTNO 10 10 10 20 20 20 20 20 30 30 DEPTNO. . JOB PRESIDENT MANAGER CLERK ANALYST ANALYST MANAGER CLERK CLERK MANAGER CLERK ENAME KING CLARK MILLER SCOTT FORD JONES ADAMS SMITH BLAKE JAMES To order by a column. it is not necessary to have SELECTed it. To order two columns. In the ORDER BY clause.

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

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

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

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

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

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

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


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

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

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

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

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

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

The programming part must be enclosed with key words BEGIN & END.. It supports all data types available in SQL and besides that provides the following additional data types. Exceptions : The statements specified in this section will automatically executes when ever a database transaction is failed specified before the exceptions.] END. constants cursors. DECLARE: Declaration of variables Variable name Data type To define a name you must follow the rules to define a name in Oracle. END must be terminated by semi-colon.Statements [Expections …. exceptions. 2. 3. Programming part : It is a set of SQL statements to perform a required task. 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 . Declare section that allows to declare variables. This is an optional section. subranges data types & so on.

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

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

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

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

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

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

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

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

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

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

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

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

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

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



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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

RDBMS must satisfy 6 database rules of minimum. .

Sign up to vote on this title
UsefulNot useful