Oracle SQL.pdf

March 3, 2018 | Author: adnanahmar | Category: Relational Database, Databases, Oracle Corporation, Sql, Oracle Database
Share Embed Donate


Short Description

Download Oracle SQL.pdf...

Description

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

What is a Database? A database is a collection of information that is organized so that it can easily be accessed, managed, and updated. OR A collection of information organized in such a way that a computer program can quickly select desired pieces of data. You can think of a database as an electronic filing system. Traditional databases are organized by fields, records, and files/table. A field is a single piece of information; a record is one complete set of fields; and a file is a collection of records/table. For example, a telephone book is analogous to a file. It contains a list of records, each of which consists of three fields: name, address, and telephone number.

OR The definition of a database is a structured collection of records or data that is stored in a computer system. In order for a database to be truly functional, it must not only store large amounts of records well, but be accessed easily. In addition, new information and changes should also be fairly easy to input. In order to have a highly efficient database system, you need to incorporate a program that manages the queries and information stored on the system. This is usually referred to as DBMS or a Database Management System. Besides these features, all databases that are created should be built with high data integrity. Database Management System (DBMS) A collection of programs that enables you to store, modify, and extract information from a database. There are many different types of DBMSs, ranging from small systems that run on personal computers to huge systems that run on mainframes. The following are examples of database applications: • computerized library systems • automated teller machines • flight reservation systems • computerized parts inventory systems Requests for information from a database are made in the form of a query 1

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Types of Databases There are several common types of databases; each type of database has its own data model (how the data is structured). They include; Flat Model, Hierarchical Model, Relational Model and Network Model. The Flat Model Database In a flat model database, there is a two dimensional (flat structure) array of data. For instance, there is one column of information and within this column it is assumed that each data item will be related to the other. For instance, a flat model database includes only zip codes. Within the database, there will only be one column and each new row within that one column will be a new zip code. The Hierarchical Model Database The hierarchical model database resembles a tree like structure, such as how Microsoft Windows organizes folders and files. In a hierarchical model database, each upward link is nested in order to keep data organized in a particular order on a same level list. For instance, a hierarchal database of sales, may list each days sales as a separate file. Within this nested file are all of the sales (same types of data) for the day. The Network Model In a network model, the defining feature is that a record is stored with a link to other records in effect networked. These networks (or sometimes referred to as pointers) can be a variety of different types of information such as node numbers or even a disk address. The Relational Model The relational model is the most popular type of database and an extremely powerful tool, not only to store information, but to access it as well. Relational databases are organized as tables. The beauty of a table is that the information can be accessed or added without reorganizing the tables. A table can have many records and each record can have many fields. Tables are sometimes called a relation. For instance, a company can have a database called customer orders, within this database will be several different tables or relations all relating to customer orders. Tables can include customer information (name, address, contact, info, customer number, etc) and other tables (relations) such as orders that the customer previously bought (this can include item number, item description, payment amount, payment method, etc). It should be noted that every record (group of fields) in a relational database has its own primary key. A primary key is a unique field that makes it easy to identify a record. Relational databases use a program interface called SQL or Standard Query Language. SQL is currently used on practically all relational databases. Relational databases are extremely easy to customize to fit almost any kind of data storage. You can easily create relations for items that you sell, employees that work for your company, etc. Accessing Information Using a Database While storing data is a great feature of databases, for many database users the most important feature is quick and simple retrieval of information. In a relational database, it is extremely easy to pull up information regarding an employee, but relational databases also add the power of running queries. Queries are requests to pull specific types of information and either show them in their natural state or create a report using the data. For instance, if you had a database of employees and it included tables such as salary and job description, you can easily run a query of which jobs pay over a certain amount. No matter what kind of information you store on your database, queries can be created using SQL to help answer important questions.

2

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Storing a Database Databases can be very small (less than 1 MB) or extremely large and complicated (terabytes as in many government databases), however all databases are usually stored and located on hard disk or other types of storage devices and are accessed via computer. Large databases may require separate servers and locations, however many small databases can fit easily as files located on your computer's hard drive. Securing a Database Obviously, many databases store confidential and important information that should not be easily accessed by just anyone. Many databases require passwords and other security features in order to access the information. While some databases can be accessed via the internet through a network, other databases are closed systems and can only be accessed on site. Field / Column A space allocated for a particular item of information. Admission form, for example, contains a number of fields: one for your name, one for your Father Name, one for your date of birth, and so on. In database systems, fields are the smallest units of information you can access. In spreadsheets, fields are called cells. Record A collection of fields is called a record. Table Collection of related records is called a table. Or Table is a storage object of a database. Oracle Tables Oracle stores records relating to each other in a table. For example, all the records for employees of a company would be stored by Oracle in one table, the employee table. EMP TABLE EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 MANAGER 7839 02-APR-81 2975 20 SALESMAN 7698 28-SEP-81 1250 1400 30 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 SALESMAN 7698 08-SEP-81 1500 0 30 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 ANALYST 7566 03-DEC-81 3000 20 CLERK 7782 23-JAN-82 1300 10

EMPNO is a primary key in EMP Table. DEPTNO is a foreign key in EMP Table. A table consists of a number of records. The field names of each record in the table are the same, although the field values may differ. Every employee record has a salary field, called SAL. The values in the SAL field can be different for each employee. 3

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Each field occupies one column and each record occupies one row. In each column of the table, you put a specific category of information for the employees, such as their employee number, name, and job. Each row in the table contains the information relating to a specific employee, together as one record. Each record is a unique entry and is independent of any other record in the table. The EMP table, for example, contains records for SMITH and ALLEN. Although both records are part of the EMP table, the data contained within them is independent of each other. There is no relationship between SMITH's andALLEN's salaries. After the analysis of the business requirements, the database design team defines the necessary tables. Different tables are created for the various groups of information. An EMP table is created for employee information, a DEPT table is created for department information. Related tables are grouped together to form a database. For example, a personnel or human resources application database includes both the EMP and DEPT tables and all other tables involved in the application. DEPT TABLE DEPTNO --------10 20 30 40

DNAME -------------ACCOUNTING RESEARCH SALES OPERATIONS

LOC ------------NEW YORK DALLAS CHICAGO BOSTON

DEPTNO is a primary key in DEPT Table. Primary Keys Every table in Oracle has a field or a combination of fields that uniquely identifies each record in the table. This unique identifier is called the primary key, or simply the key. * * * * * *

Primary Key is used to identify a record in a table. No Duplication NULL is not allowed (must provide a value) Only one Primary Key in a table May be composite Primary Key Table in which Primary Key exists normally called parent table

Foreign Key Remember that every table in ORACLE has a primary key a field or fields making each record unique. In the employee table, the primary key is the employee ID number, and it is stored in the EMPNO field. In the DEPT table, the department number is the primary key and is stored in the DEPTNO field. The department number is also stored in a field in the EMP table - the DEPTNO field. The department number field links the EMP table to the DEPT table. This relationship is based on the department number field. Employee SMITH works in department number 20, ALLEN works in department 30. When a field in one table matches the primary key of another table, the field is referred to as a foreign key. A foreign key is a field or a group of fields in one table whose values match those of the primary key of another table. You can think of a foreign key as the primary key of a foreign table. In the personnel database example, the DEPTNO field in the EMP table is a foreign key. The DEPTNO field is still the primary key of the DEPT table. * * * * *

Comes from an other table Duplication allowed Null is allowed There may be multiple foreign Key in a table Table in which Foreign Key exists normally called child table 4

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Relational Databases Oracle makes it very easy to link the data in multiple tables: matching an employee to the department in which they work is one example. This is a key feature of a relational database management system, or RDBMS. They store data in two or more tables and enable you to define relationships between the tables. The link between the tables is based on one or more field values common to both tables. For example, the following diagram represents part of the EMP table and the entire DEPT table: DEPT DEPTNO --------10 20 30 40

DNAME -------------ACCOUNTING RESEARCH SALES OPERATIONS

LOC ------------NEW YORK DALLAS CHICAGO BOSTON

EMP EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME DEPTNO ---------- --------SMITH 20 ALLEN 30 WARD 30 JONES 20 MARTIN 30 BLAKE 30 CLARK 10 SCOTT 20 KING 10 TURNER 30 ADAMS 20 JAMES 30 FORD 20 MILLER 10

There is a department number field in both the EMP and DEPT tables. In the EMP table, the department number represents the department in which the employee works. In the DEPT table, the department number represents a valid department within the business. In both tables, they are department numbers; in essence, the contents of the DEPTNO field in the EMP table represents the same thing as the contents of the DEPTNO field in the DEPARTMENT table. It's not necessary that the linking fields have the same field names. What's important is their value and what they represent. The business is divided into departments. The departments are identified and stored in the DEPT table. Each department is assigned a department number. The relationship between the EMP and DEPT tables is based on the department number. Each employee works in one specific department. The employee's department number is stored in the DEPTNO field of the EMP table. An employee cannot be assigned to a department that is not defined in the DEPT table. A department can be defined in the DEPT table, yet have no employees assigned to it.

5

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Data Storage on Different Media

Electronic Spreadsheet

Filling cabinet

Database

Storing Information Every organization has some information needs. A library keeps a list of members, books, due dates, and fines. A company needs to save information about employees, departments, and salaries. These pieces of information are called data. Organizations can store data on various media and in different formats, such as a hard-copy document in a filing cabinet or data stored in electronic spreadsheets or in databases. A database is an organized collection of information. To manage databases, you need database management systems (DBMS). A DBMS is a program that stores, retrieves, and modifies data in the database on request. There are four main types of databases: hierarchical, network, relational, and more recently object relational.

6

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Chapter 1

Writing Basic SQL SELECT Statements SQL is an ANSI (American National Standards Institute) standard computer language for accessing and manipulating databases. SQL statements are used to retrieve and update data in a database. SQL works with database programs like MS Access, DB2, Informix, MS SQL Server, Oracle, Sybase, etc. What is SQL? SQL stands for Structured Query Language SQL allows you to access a database SQL is an ANSI standard computer language SQL can execute queries against a database SQL can retrieve data from a database SQL can insert new records in a database SQL can delete records from a database SQL can update records in a database SQL is easy to learn SQL Queries With SQL, we can query a database and have a result set returned. A query like this: SELECT EMPNO, ENAME, JOB, SAL FROM EMP; SQL Query is also called SQL statement. Result of the above query: EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

JOB SAL --------- --------CLERK 800 SALESMAN 1600 SALESMAN 1250 MANAGER 2975 SALESMAN 1250 MANAGER 2850 MANAGER 2450 ANALYST 3000 PRESIDENT 5000 SALESMAN 1500 CLERK 1100 CLERK 950 ANALYST 3000 CLERK 1300

Almost all modern Relational Database Management Systems like MS SQL Server, Microsoft Access, MSDE, Oracle, DB2, Sybase, MySQL, Postgres and Informix use SQL as standard database language. There are three types of SQL Statements: 1. Data Manipulation Language (DML) 2. Data Manipulation Language (DDL) 3. Data Control Language (DCL)

7

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

What is SQL*Plus? SQL*Plus is an interactive and batch query tool that is installed with every Oracle Database Server or Client installation. It has a command-line user interface, a Windows Graphical User Interface (GUI) and the iSQL*Plus web-based user interface. SQL*Plus has its own commands and environment, and it provides access to the Oracle Database. It enables you to enter and execute SQL, PL/SQL, SQL*Plus and operating system commands.

What is iSQL*Plus? iSQL*Plus is a browser-based interface which uses the SQL*Plus processing engine in a threetier model comprising: • • •

Client (Web browser). Middle tier (Application Server). Database (Oracle Database).

8

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

The Oracle Product Family As an Oracle database administrator, you may be responsible for a database that is actually part of another Oracle product or that complements or is relied upon by that other product. Oracle has long since become more than just a database company— though the Oracle database is at the heart of what Oracle Corporation does best. In addition to the database, Oracle Corporation also offers these products, among others: • Oracle E-Business Suite Also referred to as Oracle Applications, the E-Business Suite is the premier enterprise resource planning (ERP) suite in the industry. Encompassing many modules, including financials, human resources, distribution, manufacturing, and many others, the E-Business Suite allows organizations to leverage Oracle technology to better run their businesses and increase profitability and customer satisfaction. Oracle E-Business Suite makes use of the Oracle database, Application Server, and Developer Suite to run and enhance the application. • Oracle Collaboration Suite One of Oracle’s newest products, Collaboration Suite encompasses e-mail, fax, calendaring, web conferencing, a files repository, voice mail, and other modules to provide a single integrated platform for an organization’s collaboration and communication infrastructure. Like Oracle E-Business Suite, Collaboration Suite also incorporates the Oracle database and Application Server as its foundation. • Oracle Application Server A Java 2 Enterprise Edition (J2EE)–certified server platform, Oracle Application Server integrates everything you need to deploy and develop web-based applications. Oracle Application Server includes a portal server and tools to develop portlets, Web Services capabilities, content management, support for forms-based applications using Oracle Forms, reporting using Oracle Reports, development using PL/SQL or Java, and many other features. It also includes the capability to configure and use a single sign-on server that interfaces with other thirdparty directory services such as Microsoft’s Active Directory, Novell’s NDS, and Sun’s iPlanet. • Oracle Developer Suite If you need to develop applications for the Oracle database or Application Server, Oracle Developer Suite provides tools for the development of Java, PL/SQL, business intelligence, data warehousing, and other applications. • Oracle Consulting When you need assistance in your Oracle deployment, Oracle Consulting can provide the expertise and individuals to help your projects succeed. • Oracle University The training of customers and partners on Oracle products and technologies is the responsibility of Oracle University and its partners. Instructor-led and online courses are available. More information on the products available from Oracle Corporation can be found on the Oracle web site at www.oracle.com.

9

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Connecting to database You can connect to the database by using different tools. I am using SQL*Plus to connect to the database. SQL*Plus is Oracle provided tool for accessing database. In order to connect to database, you must provide:

SQL prompt is appeared after successful login.

SQL statements are used to access database. There are three types of SQL statements. • Data Manipulation Language (DML) • Data Definition Language (DDL) • Data Control Language (DCL)

10

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT * FROM EMP;

1

1

2

EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

1. 2.

3. 4.

5. 6.

4

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 MANAGER 7839 02-APR-81 2975 20 SALESMAN 7698 28-SEP-81 1250 1400 30 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 5 10 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 5 17-NOV-81 5000 10 SALESMAN 7698 08-SEP-81 1500 0 30 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 ANALYST 7566 03-DEC-81 3000 20 CLERK 7782 23-JAN-82 1300 10

A single row or tuple representing all data required for a particular employee. Each row in a table should be identified by a primary key, which allows no duplicate rows. The order of rows is insignificant; specify the row order when the data is retrieved. A column or attribute containing the employee number. The employee number identifies a unique employee in the EMP table. In this example, the employee number column is designated as the primary key. A primary key must contain a value, and the value must be unique. A column that is not a key value. A column represents one kind of data in a table; in the example, the name of all the employees. Column order is insignificant when storing data; specify the column order when the data is retrieved. A column containing the department number, which is also a foreign key. A foreign key is a column that defines how tables relate to each other. A foreign key refers to a primary key or a unique key in the same table or in another table. In the example, DEPTNO uniquely identifies a department in the DEPT table. A field may have no value in it. This is called a null value. In the EMP table, only employees who have a role of salesman have a value in the COMM (commission) field. A field can be found at the intersection of a row and a column. There can be only one value in it.

SQL> SELECT * FROM DEPT; DEPTNO --------10 20 30 40

DNAME -------------ACCOUNTING RESEARCH SALES OPERATIONS

LOC ------------NEW YORK DALLAS CHICAGO BOSTON

11

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

What is Keyword? SELECT FROM WHERE ORDER BY GROUP BY etc.

What is Clause? SELECT ... FROM ... WHERE ... ORDER BY ... GROUP BY ... etc.

What is SQL Statement? SELECT * FROM EMP; SELECT EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO FROM EMP; SELECT * FROM EMP WHERE SAL>2000; etc.

SELECT & FROM Keywords Specify number of columns just after SELECT. Specify table name just after FROM keyword.

Solve the following: Display all columns and all rows of EMP table. SQL> SELECT * FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 MANAGER 7839 02-APR-81 2975 20 SALESMAN 7698 28-SEP-81 1250 1400 30 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 SALESMAN 7698 08-SEP-81 1500 0 30 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 ANALYST 7566 03-DEC-81 3000 20 CLERK 7782 23-JAN-82 1300 10

14 rows selected.

Display all columns and all rows of DEPT table. SQL> SELECT * FROM DEPT; DEPTNO --------10 20 30 40

DNAME -------------ACCOUNTING RESEARCH SALES OPERATIONS

LOC ------------NEW YORK DALLAS CHICAGO BOSTON

12

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Display employee number, name, and salary of all employees. SQL> SELECT EMPNO, ENAME, SAL FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME SAL ---------- --------SMITH 800 ALLEN 1600 WARD 1250 JONES 2975 MARTIN 1250 BLAKE 2850 CLARK 2450 SCOTT 3000 KING 5000 TURNER 1500 ADAMS 1100 JAMES 950 FORD 3000 MILLER 1300

14 rows selected.

Above query can be written as follows: SQL> 2 3 4 5 6

SELECT EMPNO, ENAME, SAL FROM EMP;

EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME SAL ---------- --------SMITH 800 ALLEN 1600 WARD 1250 JONES 2975 MARTIN 1250 BLAKE 2850 CLARK 2450 SCOTT 3000 KING 5000 TURNER 1500 ADAMS 1100 JAMES 950 FORD 3000 MILLER 1300

14 rows selected.

It is good habit to write each clause in separate line. i.e. SQL> SELECT EMPNO, ENAME, SAL 2 FROM EMP; Result of above three queries is same. 13

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Remember about SQL statements

SQL statements are not case sensitive. SQL statements can be on one or more lines. Keywords cannot be abbreviated or split across lines. Clauses are usually placed on separate lines. Indents are used to enhance readability -- IN ABOVE SQL STATEMENTS [SELECT , FROM ] ARE KEY WORDS -- IN ABOVE SQL STATEMENTS [SELECT .. , FROM .. ] ARE clauses. * Means All Columns

How to display structure of a table?

Mean how many columns are there in a table, data type, width and either null is allowed or not. User DESCRIBE / DESC command SQL> DESC EMP Name Null? ------------------------------- -------EMPNO NOT NULL ENAME JOB MGR HIREDATE SAL COMM DEPTNO

Type ---NUMBER(4) VARCHAR2(10) VARCHAR2(9) NUMBER(4) DATE NUMBER(7,2) NUMBER(7,2) NUMBER(2)

There are eight columns in EMP table. Data type and width of each column is also displayed. NOT NULL is written in front of EMPNO. SQL> DESC DEPT Name Null? ------------------------------- -------DEPTNO NOT NULL DNAME LOC

Type ---NUMBER(2) VARCHAR2(14) VARCHAR2(13)

What is Data Type?

Classification of a particular type of information. It is easy for humans to distinguish between different types of data. Some data types are as follows: NUMBER CHAR VARCHAR2 DATE

Accepts Accepts Accepts Accepts

Example of Numbers Example of VARCHAR2 Example of DATE

0 to 9, decimal point, positive or negative sign 0 to 9, alpha bets and special characters 0 to 9, alpha bets and special characters Date Salary, Commission, Fee, Charges, Amount etc Name, Father Name, Job, Address etc. Date of Birth, Admission Date, Resignation Date etc.

14

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Selecting specific columns and notice the heading of each column. SQL> SELECT EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 MANAGER 7839 02-APR-81 2975 20 SALESMAN 7698 28-SEP-81 1250 1400 30 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 SALESMAN 7698 08-SEP-81 1500 0 30 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 ANALYST 7566 03-DEC-81 3000 20 CLERK 7782 23-JAN-82 1300 10

14 rows selected. SQL> SELECT ENAME, JOB, SAL, DEPTNO FROM EMP; ENAME JOB SAL DEPTNO ---------- --------- --------- --------SMITH CLERK 800 20 ALLEN SALESMAN 1600 30 WARD SALESMAN 1250 30 JONES MANAGER 2975 20 MARTIN SALESMAN 1250 30 BLAKE MANAGER 2850 30 CLARK MANAGER 2450 10 SCOTT ANALYST 3000 20 KING PRESIDENT 5000 10 TURNER SALESMAN 1500 30 ADAMS CLERK 1100 20 JAMES CLERK 950 30 FORD ANALYST 3000 20 MILLER CLERK 1300 10 14 rows selected. SQL> SELECT JOB, SAL FROM EMP; JOB SAL --------- --------CLERK 800 SALESMAN 1600 SALESMAN 1250 MANAGER 2975 SALESMAN 1250 MANAGER 2850 MANAGER 2450 ANALYST 3000 PRESIDENT 5000 SALESMAN 1500 CLERK 1100 CLERK 950 ANALYST 3000 CLERK 1300 15

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT ENAME FROM EMP; ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER SQL> SELECT DEPTNO, DNAME, LOC FROM DEPT; DEPTNO DNAME LOC --------- -------------- ------------10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON SQL> SELECT DEPTNO, DNAME FROM DEPT; DEPTNO DNAME --------- -------------10 ACCOUNTING 20 RESEARCH 30 SALES 40 OPERATIONS SQL> SELECT DNAME FROM DEPT; DNAME -------------ACCOUNTING RESEARCH SALES OPERATIONS What is DUAL Table? The DUAL table is owned by the user SYS and can be accessed by all users. It contains one column, DUMMY, and one row with the value X. The DUAL table is useful when you want to return a value once only, for instance, the value of a constant, pseudocolumn, or expression that is not derived from a table with user data. The DUAL table is generally used for SELECT clause syntax completeness, because both SELECT and FROM clauses are mandatory, and several calculations do not need to select from actual tables. SQL> DESC DUAL Name Null? Type ------------------------------- -------- ---DUMMY VARCHAR2(1) SQL> SELECT * FROM DUAL; D X 16

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Display Current Date using DUAL Table SQL> SELECT SYSDATE FROM DUAL; SYSDATE --------14-JUL-08

Display Current User using DUAL Table SQL> SELECT USER FROM DUAL; USER -----------------------------SCOTT SQL>

Arithmetic operators and precedence + * /

Addition Subtraction Multiplication Division

PRECEDENCE 1. ( ) 2. * / 3. + -

Parenthesis has the highest precedence Multiplication and Division have the same precedence Addition and Subtraction have the same precedence

Performing calculation in using SQL SQL> SELECT 7+10 FROM DUAL; 7+10 ---------17 SQL> SELECT 7+10-2+5 FROM DUAL; 7+10-2+5 ---------20 SQL> SELECT 7+10*2+5 FROM DUAL; 7+10*2+5 ---------32 SQL> SELECT 7+10-2*5 FROM DUAL; 7+10-2*5 ---------7 17

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT 7*10-2+5 FROM DUAL; 7*10-2+5 ---------73 SQL> SELECT 7*10-2*5 FROM DUAL; 7*10-2*5 ---------60 SQL> SELECT 7+10/2+5 FROM DUAL; 7+10/2+5 ---------17

SQL> SELECT 7*10/2+5 FROM DUAL; 7*10/2+5 ---------40 SQL> SELECT 7*10/2*5 FROM DUAL; 7*10/2*5 ---------175 SQL> SELECT 7+10/2*5 FROM DUAL; 7+10/2*5 ---------32 SQL> SELECT 7*10/(2+5) FROM DUAL; 7*10/(2+5) ---------10 SQL> SELECT 7*10+2+5 FROM DUAL; 7*10+2+5 ---------77 SQL> SELECT 7*(10+2)+5 FROM DUAL; 7*(10+2)+5 ---------89

18

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Performing calculations with columns, Notice heading of each column WITH NUMBER COLUMNS

SQL> SELECT EMPNO, ENAME, SAL, SAL+100, SAL-100, SAL*12 FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME SAL SAL+100 SAL-100 SAL*12 ---------- --------- --------- --------- --------SMITH 800 900 700 9600 ALLEN 1600 1700 1500 19200 WARD 1250 1350 1150 15000 JONES 2975 3075 2875 35700 MARTIN 1250 1350 1150 15000 BLAKE 2850 2950 2750 34200 CLARK 2450 2550 2350 29400 SCOTT 3000 3100 2900 36000 KING 5000 5100 4900 60000 TURNER 1500 1600 1400 18000 ADAMS 1100 1200 1000 13200 JAMES 950 1050 850 11400 FORD 3000 3100 2900 36000 MILLER 1300 1400 1200 15600

SQL> SELECT EMPNO, ENAME, SAL, SAL*12, SAL+100*12, (SAL+100)*12 FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME SAL SAL*12 SAL+100*12 (SAL+100)*12 ---------- --------- --------- ---------- -----------SMITH 800 9600 2000 10800 ALLEN 1600 19200 2800 20400 WARD 1250 15000 2450 16200 JONES 2975 35700 4175 36900 MARTIN 1250 15000 2450 16200 BLAKE 2850 34200 4050 35400 CLARK 2450 29400 3650 30600 SCOTT 3000 36000 4200 37200 KING 5000 60000 6200 61200 TURNER 1500 18000 2700 19200 ADAMS 1100 13200 2300 14400 JAMES 950 11400 2150 12600 FORD 3000 36000 4200 37200 MILLER 1300 15600 2500 16800

SQL> SELECT EMPNO, ENAME, COMM, COMM+100, COMM-100, COMM*12 FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME COMM COMM+100 COMM-100 COMM*12 ---------- --------- --------- --------- --------SMITH ALLEN 300 400 200 3600 WARD 500 600 400 6000 JONES MARTIN 1400 1500 1300 16800 BLAKE CLARK SCOTT KING TURNER 0 100 -100 0 ADAMS JAMES FORD MILLER

?

?

19

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT EMPNO, ENAME, SAL, COMM, SAL+COMM FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME SAL COMM SAL+COMM ---------- --------- --------- --------SMITH 800 ALLEN 1600 300 1900 WARD 1250 500 1750 JONES 2975 MARTIN 1250 1400 2650 BLAKE 2850 CLARK 2450 SCOTT 3000 KING 5000 TURNER 1500 0 1500 ADAMS 1100 JAMES 950 FORD 3000 MILLER 1300

?

?

14 rows selected. SQL> SELECT EMPNO, ENAME, SAL, COMM, SAL+COMM*12, (SAL+COMM)*12 FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME SAL COMM SAL+COMM*12 (SAL+COMM)*12 ---------- --------- --------- ----------- ------------SMITH 800 ALLEN 1600 300 5200 22800 WARD 1250 500 7250 21000 JONES 2975 MARTIN 1250 1400 18050 31800 BLAKE 2850 CLARK 2450 SCOTT 3000 KING 5000 TURNER 1500 0 1500 18000 ADAMS 1100 JAMES 950 FORD 3000 MILLER 1300

In above result notice calculation with NULL values • •

A null is a value that is unavailable, unassigned, unknown or inapplicable. A null is not the same as zero or a blank space.

If you add, subtract, multiply or divided a value with null, the whole result becomes null.

20

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

NULL value can be controlled with NVL() function NVL (column_name, replaced_value) SELECT EMPNO, ENAME, JOB, SAL, COMM, NVL(COMM,0) FROM EMP; NULL will be replaced with 0 SELECT EMPNO, ENAME, JOB, SAL, COMM, NVL(COMM,100) FROM EMP; NULL will be replaced with 100

Notice the result of column number 3, 4 and 5 SQL> SELECT EMPNO, ENAME, COMM, NVL(COMM,0), NVL(COMM,50) FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME COMM NVL(COMM,0) NVL(COMM,50) ---------- --------- ----------- -----------SMITH 0 50 ALLEN 300 300 300 WARD 500 500 500 JONES 0 50 MARTIN 1400 1400 1400 BLAKE 0 50 CLARK 0 50 SCOTT 0 50 KING 0 50 TURNER 0 0 0 ADAMS 0 50 JAMES 0 50 FORD 0 50 MILLER 0 50

14 rows selected.

Notice the result of column number 6 and 7 SQL> SELECT EMPNO, ENAME, JOB, SAL, COMM, SAL+COMM, SAL+NVL(COMM,0) FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

JOB SAL COMM SAL+COMM SAL+NVL(COMM,0) --------- --------- --------- --------- --------------CLERK 800 800 SALESMAN 1600 300 1900 1900 SALESMAN 1250 500 1750 1750 MANAGER 2975 2975 SALESMAN 1250 1400 2650 2650 MANAGER 2850 2850 MANAGER 2450 2450 ANALYST 3000 3000 PRESIDENT 5000 5000 SALESMAN 1500 0 1500 1500 CLERK 1100 1100 CLERK 950 950 ANALYST 3000 3000 CLERK 1300 1300

14 rows selected. 21

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Performing calculations with columns, Notice heading of each column WITH DATE COLUMNS SQL> SELECT SYSDATE, SYSDATE+1, SYSDATE-1 FROM DUAL; SYSDATE SYSDATE+1 SYSDATE-1 --------- --------- --------14-JUL-08 15-JUL-08 13-JUL-08 SQL> SELECT SYSDATE, SYSDATE+7, SYSDATE+30, SYSDATE+365 FROM DUAL; SYSDATE SYSDATE+7 SYSDATE+3 SYSDATE+3 --------- --------- --------- --------14-JUL-08 21-JUL-08 13-AUG-08 14-JUL-09

SQL> SELECT EMPNO, ENAME, HIREDATE, HIREDATE+1, HIREDATE+7 FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

HIREDATE --------17-DEC-80 20-FEB-81 22-FEB-81 02-APR-81 28-SEP-81 01-MAY-81 09-JUN-81 19-APR-87 17-NOV-81 08-SEP-81 23-MAY-87 03-DEC-81 03-DEC-81 23-JAN-82

HIREDATE+ --------18-DEC-80 21-FEB-81 23-FEB-81 03-APR-81 29-SEP-81 02-MAY-81 10-JUN-81 20-APR-87 18-NOV-81 09-SEP-81 24-MAY-87 04-DEC-81 04-DEC-81 24-JAN-82

HIREDATE+ --------24-DEC-80 27-FEB-81 01-MAR-81 09-APR-81 05-OCT-81 08-MAY-81 16-JUN-81 26-APR-87 24-NOV-81 15-SEP-81 30-MAY-87 10-DEC-81 10-DEC-81 30-JAN-82

14 rows selected. SQL> SELECT EMPNO, ENAME, HIREDATE, HIREDATE-7 FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

HIREDATE --------17-DEC-80 20-FEB-81 22-FEB-81 02-APR-81 28-SEP-81 01-MAY-81 09-JUN-81 19-APR-87 17-NOV-81 08-SEP-81 23-MAY-87 03-DEC-81 03-DEC-81 23-JAN-82

HIREDATE--------10-DEC-80 13-FEB-81 15-FEB-81 26-MAR-81 21-SEP-81 24-APR-81 02-JUN-81 12-APR-87 10-NOV-81 01-SEP-81 16-MAY-87 26-NOV-81 26-NOV-81 16-JAN-82

14 rows selected. 22

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Column Alias / Column Heading When displaying the result of a query, SQL*Plus normally uses the name of the selected column as the column heading. This heading may not be descriptive and hence may be difficult to understand. You can change a column heading by using a column alias. Specify the alias after the column in the SELECT list using a space as a separator. By default, alias headings appear in uppercase. If the alias contains spaces or special characters (such as # or $), or is case sensitive, enclose the alias in double quotation marks (" "). AS is optional SQL> SELECT EMPNO, ENAME, JOB AS DESIGNATION, SAL AS SALARY, COMM COMMISSION FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

DESIGNATI SALARY COMMISSION --------- --------- ---------CLERK 800 SALESMAN 1600 300 SALESMAN 1250 500 MANAGER 2975 SALESMAN 1250 1400 MANAGER 2850 MANAGER 2450 ANALYST 3000 PRESIDENT 5000 SALESMAN 1500 0 CLERK 1100 CLERK 950 ANALYST 3000 CLERK 1300

14 rows selected.

SQL> SELECT EMPNO, ENAME, SAL, SAL*12 ANN_SAL FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME SAL ANN_SAL ---------- --------- --------SMITH 800 9600 ALLEN 1600 19200 WARD 1250 15000 JONES 2975 35700 MARTIN 1250 15000 BLAKE 2850 34200 CLARK 2450 29400 SCOTT 3000 36000 KING 5000 60000 TURNER 1500 18000 ADAMS 1100 13200 JAMES 950 11400 FORD 3000 36000 MILLER 1300 15600

14 rows selected. SQL>

23

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT EMPNO, ENAME, JOB, SAL MONTHLY_SALARY, SAL+NVL(COMM,0) GROSS_SALARY, 2 SAL*12 ANNUAL_SALARY FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

JOB MONTHLY_SALARY GROSS_SALARY ANNUAL_SALARY --------- -------------- ------------ ------------CLERK 800 800 9600 SALESMAN 1600 1900 19200 SALESMAN 1250 1750 15000 MANAGER 2975 2975 35700 SALESMAN 1250 2650 15000 MANAGER 2850 2850 34200 MANAGER 2450 2450 29400 ANALYST 3000 3000 36000 PRESIDENT 5000 5000 60000 SALESMAN 1500 1500 18000 CLERK 1100 1100 13200 CLERK 950 950 11400 ANALYST 3000 3000 36000 CLERK 1300 1300 15600

14 rows selected. By default, alias headings appear in uppercase. If the alias contains spaces or special characters (such as # or $), or is case sensitive, enclose the alias in double quotation marks (" "). SQL> SELECT EMPNO, ENAME, JOB "JOB TITLE", SAL "salary", COMM COMMISSION 2 FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

JOB TITLE salary COMMISSION --------- --------- ---------CLERK 800 SALESMAN 1600 300 SALESMAN 1250 500 MANAGER 2975 SALESMAN 1250 1400 MANAGER 2850 MANAGER 2450 ANALYST 3000 PRESIDENT 5000 SALESMAN 1500 0 CLERK 1100 CLERK 950 ANALYST 3000 CLERK 1300

14 rows selected. SQL>

24

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Concatenation Operator You can link columns to other columns, arithmetic expressions, or constant values to create a character expression by using the concatenation operator (||). Columns on either side of the operator are combined to make a single output column.

SQL> SELECT EMPNO||ENAME FROM EMP; EMPNO||ENAME -------------------------------------------------7369SMITH 7499ALLEN 7521WARD 7566JONES 7654MARTIN 7698BLAKE 7782CLARK 7788SCOTT 7839KING 7844TURNER 7876ADAMS 7900JAMES 7902FORD 7934MILLER 14 rows selected. SQL> SELECT EMPNO||ENAME||JOB EMPLOYEE_INFO FROM EMP; EMPLOYEE_INFO ----------------------------------------------------------7369SMITHCLERK 7499ALLENSALESMAN 7521WARDSALESMAN 7566JONESMANAGER 7654MARTINSALESMAN 7698BLAKEMANAGER 7782CLARKMANAGER 7788SCOTTANALYST 7839KINGPRESIDENT 7844TURNERSALESMAN 7876ADAMSCLERK 7900JAMESCLERK 7902FORDANALYST 7934MILLERCLERK 14 rows selected. SQL>

SQL> SELECT SAL||COMM SALARY FROM EMP;

25

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Literal Character Strings A literal is a character, a number, or a date that is included in the SELECT list and that is not a column name or a column alias. It is printed for each row returned. Literal strings of freeformat text can be included in the query result and are treated the same as a column in the SELECT list. Date and character literals must be enclosed within single quotation marks (' '); number literals need not. SQL> SELECT EMPNO, ENAME, JOB, 5000, 'KARACHI', '14-AUG-1947' FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

JOB 5000 'KARACH '14-AUG-194 --------- --------- ------- ----------CLERK 5000 KARACHI 14-AUG-1947 SALESMAN 5000 KARACHI 14-AUG-1947 SALESMAN 5000 KARACHI 14-AUG-1947 MANAGER 5000 KARACHI 14-AUG-1947 SALESMAN 5000 KARACHI 14-AUG-1947 MANAGER 5000 KARACHI 14-AUG-1947 MANAGER 5000 KARACHI 14-AUG-1947 ANALYST 5000 KARACHI 14-AUG-1947 PRESIDENT 5000 KARACHI 14-AUG-1947 SALESMAN 5000 KARACHI 14-AUG-1947 CLERK 5000 KARACHI 14-AUG-1947 CLERK 5000 KARACHI 14-AUG-1947 ANALYST 5000 KARACHI 14-AUG-1947 CLERK 5000 KARACHI 14-AUG-1947

14 rows selected. SQL> SELECT 'Mr. '||ENAME EMPLOYEE FROM EMP; EMPLOYEE -------------Mr. SMITH Mr. ALLEN Mr. WARD Mr. JONES Mr. MARTIN Mr. BLAKE Mr. CLARK Mr. SCOTT Mr. KING Mr. TURNER Mr. ADAMS Mr. JAMES Mr. FORD Mr. MILLER 14 rows selected.

SQL> SELECT 'Rs. '||SAL SALAR FROM EMP; SQL> SELECT ENAME||' WORKS IN DEPARTMENT NUMBER '||DEPTNO EMPLOYEE FROM EMP; SQL> SELECT ENAME||' IS EARNING '||SAL||' PER MONTH' SALARY FROM EMP;

26

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT ENAME||' works as '||JOB||' in Dept No. '||DEPTNO "Employee Information" FROM EMP; Employee Information -------------------------------------------------------------------------------SMITH works as CLERK in Dept No. 20 ALLEN works as SALESMAN in Dept No. 30 WARD works as SALESMAN in Dept No. 30 JONES works as MANAGER in Dept No. 20 MARTIN works as SALESMAN in Dept No. 30 BLAKE works as MANAGER in Dept No. 30 CLARK works as MANAGER in Dept No. 10 SCOTT works as ANALYST in Dept No. 20 KING works as PRESIDENT in Dept No. 10 TURNER works as SALESMAN in Dept No. 30 ADAMS works as CLERK in Dept No. 20 JAMES works as CLERK in Dept No. 30 FORD works as ANALYST in Dept No. 20 MILLER works as CLERK in Dept No. 10 14 rows selected. SQL>

SQL> SELECT ENAME||' Earn Monthly '||SAL||' And His Annual Salary Is '||SAL*12 "Employee Salary Info..." FROM EMP; Employee Salary Info... --------------------------------------------------------------------------------------------------SMITH Earn Monthly 800 And His Annual Salary Is 9600 ALLEN Earn Monthly 1600 And His Annual Salary Is 19200 WARD Earn Monthly 1250 And His Annual Salary Is 15000 JONES Earn Monthly 2975 And His Annual Salary Is 35700 MARTIN Earn Monthly 1250 And His Annual Salary Is 15000 BLAKE Earn Monthly 2850 And His Annual Salary Is 34200 CLARK Earn Monthly 2450 And His Annual Salary Is 29400 SCOTT Earn Monthly 3000 And His Annual Salary Is 36000 KING Earn Monthly 5000 And His Annual Salary Is 60000 TURNER Earn Monthly 1500 And His Annual Salary Is 18000 ADAMS Earn Monthly 1100 And His Annual Salary Is 13200 JAMES Earn Monthly 950 And His Annual Salary Is 11400 FORD Earn Monthly 3000 And His Annual Salary Is 36000 MILLER Earn Monthly 1300 And His Annual Salary Is 15600 14 rows selected. SQL>

27

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Duplicate Rows SQL> SELECT DEPTNO FROM EMP; DEPTNO --------20 30 30 20 30 30 10 20 10 30 20 30 20 10 14 rows selected.

Eliminating Duplicate Rows

To eliminate duplicate rows in the result, include the DISTINCT keyword in the SELECT clause immediately after the SELECT keyword. In the example on the slide, the EMPLOYEES table actually contains 20 rows but there are only seven unique department numbers in the table. You can specify multiple columns after the DISTINCT qualifier. The DISTINCT qualifier affects all the selected columns, and the result is every distinct combination of the columns. SQL> SELECT DISTINCT DEPTNO FROM EMP; DEPTNO --------30 20 10 SQL> SELECT DISTINCT JOB FROM EMP; JOB --------CLERK SALESMAN PRESIDENT MANAGER ANALYST SQL> SELECT DISTINCT DEPTNO, JOB FROM EMP; DEPTNO --------20 30 20 30 10 30 10 10 20

JOB --------CLERK SALESMAN MANAGER CLERK PRESIDENT MANAGER CLERK MANAGER ANALYST

9 rows selected. SQL> 28

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Chapter 2

Restricting Data There are two types of queries • •

Restricted queries (Limiting the rows) Unrestricted queries

Limiting the Rows Selected You can restrict the rows returned from the query by using the WHERE clause. A WHERE clause contains a condition that must be met, and it directly follows the FROM clause. If the condition is true, the row meeting the condition is returned.

In the following example, the SELECT statement retrieves records of all employees who belong to department number 10. SQL> SELECT * FROM EMP WHERE DEPTNO=10; EMPNO --------7782 7839 7934

ENAME ---------CLARK KING MILLER

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 09-JUN-81 2450 10 PRESIDENT 17-NOV-81 5000 10 CLERK 7782 23-JAN-82 1300 10

SQL>

Display all employees who are earning more then 2000. SQL> SELECT * FROM EMP WHERE SAL>3000; EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO --------- ---------- --------- --------- --------- --------- --------- --------7839 KING PRESIDENT 17-NOV-81 5000 10 SQL>

The following query retrieves records of all employees who are working as CLERK. SQL> SELECT * FROM EMP WHERE JOB='CLERK'; EMPNO --------7369 7876 7900 7934

ENAME ---------SMITH ADAMS JAMES MILLER

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 CLERK 7782 23-JAN-82 1300 10

Note that the job title CLERK has been specified in uppercase to ensure that it matches the job column in the EMP table. Character strings are case sensitive. If data is stored in uppercase and you specify condition in lowercase then the result retrieve no record. SQL> SELECT * FROM EMP WHERE JOB='clerk'; no rows selected SQL> 29

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Retrieve all employees who were hired on 03-DEC-1981 SQL> SELECT * FROM EMP WHERE HIREDATE='03-DEC-1981'; EMPNO --------7900 7902

ENAME ---------JAMES FORD

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7698 03-DEC-81 950 30 ANALYST 7566 03-DEC-81 3000 20

SQL> Character Strings and Dates Character strings and dates in the WHERE clause must be enclosed in single quotation marks (''). Number constants, however, should not be enclosed in single quotation marks. All character searches are case sensitive. In the following example, no rows are returned because the EMP table stores all names in upper case: SELECT * FROM EMP WHERE JOB='clerk'; Oracle databases store dates in an internal numeric format, representing the century, year, month, day, hours, minutes, and seconds. The default date display is DD-MON-RR.

Comparison Conditions Operator = > >= < =3000; ENAME, JOB, SAL, SAL*12 FROM EMP WHERE SAL*12>30000; EMP WHERE SAL'22-FEB-1981'; HIREDATE, HIREDATE+10 FROM EMP WHERE HIREDATE+15>'01-MAR-1981'; ENAME FROM EMP WHERE ENAME='SMITH'; ENAME FROM EMP WHERE ENAME>'SMITH'; ENAME FROM EMP WHERE ENAME>'S'; ENAME FROM EMP WHERE ENAME SELECT * FROM EMP WHERE SAL BETWEEN 2000 AND 3000; EMPNO --------7566 7698 7782 7788 7902

ENAME ---------JONES BLAKE CLARK SCOTT FORD

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 02-APR-81 2975 20 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 ANALYST 7566 19-APR-87 3000 20 ANALYST 7566 03-DEC-81 3000 20

Retrieve all employees who were hired in Feb 1981 SQL> SELECT * FROM EMP WHERE HIREDATE BETWEEN '01-FEB-1981' AND '28-FEB-1981'; EMPNO --------7499 7521

ENAME ---------ALLEN WARD

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30

SQL> SELECT EMPNO, ENAME, JOB FROM EMP WHERE ENAME BETWEEN 'K' AND 'P'; EMPNO --------7654 7839 7934

ENAME ---------MARTIN KING MILLER

JOB --------SALESMAN PRESIDENT CLERK

IN ( ) SQL> SELECT * FROM EMP WHERE EMPNO IN(7788,7839,7968,7654) ; EMPNO --------7654 7788 7839

ENAME ---------MARTIN SCOTT KING

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------SALESMAN 7698 28-SEP-81 1250 1400 30 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10

SQL> SELECT * FROM EMP WHERE ENAME IN ('SCOTT','MARTIN','ALLEN','ASLAM', 'ZIA'); EMPNO --------7499 7654 7788

ENAME ---------ALLEN MARTIN SCOTT

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 28-SEP-81 1250 1400 30 ANALYST 7566 19-APR-87 3000 20

31

[email protected]

Prepared by Muhammad Raheem

Oracle SQL The LIKE Condition

Phone: 021-4265550, Cell: 0321-4265550

You may not always know the exact value to search for. You can select rows that match a character pattern by using the LIKE condition. The character pattern-matching operation is referred to as a wildcard search. Two symbols can be used to construct the search string. % denotes zero or many characters. _ denotes one character.

Retrieve all employees whose name begins with A SQL> SELECT * FROM EMP WHERE ENAME LIKE 'A%'; EMPNO --------7499 7876

ENAME ---------ALLEN ADAMS

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------SALESMAN 7698 20-FEB-81 1600 300 30 CLERK 7788 23-MAY-87 1100 20

Retrieve all employees whose name ends with S SQL> SELECT * FROM EMP WHERE ENAME LIKE '%S'; EMPNO --------7566 7876 7900

ENAME ---------JONES ADAMS JAMES

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 02-APR-81 2975 20 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30

Retrieve all employees who contain M anywhere in their name SQL> SELECT * FROM EMP WHERE ENAME LIKE '%M%'; EMPNO --------7369 7654 7876 7900 7934

ENAME ---------SMITH MARTIN ADAMS JAMES MILLER

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 SALESMAN 7698 28-SEP-81 1250 1400 30 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 CLERK 7782 23-JAN-82 1300 10

Retrieve all employees who contain sequentially A and then M in their name SQL> SELECT * FROM EMP WHERE ENAME LIKE '%A%M%'; EMPNO --------7876 7900

ENAME ---------ADAMS JAMES

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30

Retrieve all employees who contain second character as A in their name SQL> SELECT * FROM EMP WHERE ENAME LIKE '_A%'; EMPNO --------7521 7654 7900

ENAME ---------WARD MARTIN JAMES

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------SALESMAN 7698 22-FEB-81 1250 500 30 SALESMAN 7698 28-SEP-81 1250 1400 30 CLERK 7698 03-DEC-81 950 30

32

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Retrieve all employees who contain second last character as E in their name SQL> SELECT * FROM EMP WHERE ENAME LIKE '%E_'; EMPNO --------7499 7566 7844 7900 7934

ENAME ---------ALLEN JONES TURNER JAMES MILLER

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------SALESMAN 7698 20-FEB-81 1600 300 30 MANAGER 7839 02-APR-81 2975 20 SALESMAN 7698 08-SEP-81 1500 0 30 CLERK 7698 03-DEC-81 950 30 CLERK 7782 23-JAN-82 1300 10

Retrieve all employees who contain first character A and third character L in their name SQL> SELECT * FROM EMP WHERE ENAME LIKE 'A_L%'; EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO --------- ---------- --------- --------- --------- --------- --------- --------7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30

Retrieve all employees who were hired in 87 SQL> SELECT * FROM EMP WHERE HIREDATE LIKE '%87'; EMPNO --------7788 7876

ENAME ---------SCOTT ADAMS

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------ANALYST 7566 19-APR-87 3000 20 CLERK 7788 23-MAY-87 1100 20

Retrieve all employees who contains only 4 characters in their name SQL> SELECT * FROM EMP WHERE ENAME LIKE '____'; EMPNO --------7521 7839 7902

ENAME ---------WARD KING FORD

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------SALESMAN 7698 22-FEB-81 1250 500 30 PRESIDENT 17-NOV-81 5000 10 ANALYST 7566 03-DEC-81 3000 20

Checking null values SQL> SELECT * FROM EMP WHERE MGR IS NULL; EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO --------- ---------- --------- --------- --------- --------- --------- --------7839 KING PRESIDENT 17-NOV-81 5000 10

SELECT SELECT SELECT SELECT SELECT SELECT

* * * * * *

FROM FROM FROM FROM FROM FROM

EMP EMP EMP EMP EMP EMP

WHERE WHERE WHERE WHERE WHERE WHERE

HIREDATE BETWEEN '01-JAN-1981' AND '31-DEC-1981'; ENAME LIKE 'KHAN%'; ENAME LIKE '%KHAN'; ENAME LIKE '%KHAN%'; ENAME LIKE '__R%'; COMM IS NULL; 33

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Logical Conditions A logical condition combines the result of two component conditions to produce a single result based on them or inverts the result of a single condition. A row is returned only if the overall result of the condition is true. Three logical operators are available in SQL: • AND • OR • NOT All the examples so far have specified only one condition in the WHERE clause. You can use several conditions in one WHERE clause using the AND and OR operators.

Operator AND OR NOT

Meaning Returns TRUE if both component conditions are true Returns TRUE if either component condition is true Returns TRUE if the following condition is false

Using the AND Operator AND requires both conditions to be true If either condition is FALSE result will be FALSE in case of AND CONDITION 1

CONDITION 2

RESULT

TRUE TRUE FALSE FALSE

TRUE FALSE TRUE FALSE

TRUE FALSE FALSE FALSE

Retrieve all clerks of department number 20 SQL> SELECT EMPNO, ENAME, JOB, DEPTNO FROM EMP WHERE JOB='CLERK' AND DEPTNO=20; EMPNO --------7369 7876

ENAME ---------SMITH ADAMS

JOB DEPTNO --------- --------CLERK 20 CLERK 20

Retrieve all salesman who are earning more than 1500 SQL> SELECT * FROM EMP WHERE JOB='SALESMAN' AND SAL>1500; EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO --------- ---------- --------- --------- --------- --------- --------- --------7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30

Retrieve all salesman who were hired before mar 1981 SQL> SELECT * FROM EMP WHERE JOB='SALESMAN' AND HIREDATE SELECT EMPNO, ENAME, JOB, DEPTNO FROM EMP WHERE JOB='CLERK' OR DEPTNO=20; EMPNO --------7369 7566 7788 7876 7900 7902 7934

ENAME ---------SMITH JONES SCOTT ADAMS JAMES FORD MILLER

JOB DEPTNO --------- --------CLERK 20 MANAGER 20 ANALYST 20 CLERK 20 CLERK 30 ANALYST 20 CLERK 10

7 rows selected.

Using the NOT Operator NOT operator inverse / invert the result. NOT operator can be used with SQL Operators ( Between … and …, IN, LIKE, IS NULL) SQL> SELECT * FROM EMP WHERE SAL NOT BETWEEN 2000 AND 3000; EMPNO --------7369 7499 7521 7654 7839 7844 7876 7900 7934

ENAME ---------SMITH ALLEN WARD MARTIN KING TURNER ADAMS JAMES MILLER

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 SALESMAN 7698 28-SEP-81 1250 1400 30 PRESIDENT 17-NOV-81 5000 10 SALESMAN 7698 08-SEP-81 1500 0 30 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 CLERK 7782 23-JAN-82 1300 10

9 rows selected. SQL> SQL> SQL> SQL> SQL>

SELECT SELECT SELECT SELECT SELECT

* * * * *

FROM FROM FROM FROM FROM

EMP EMP EMP EMP EMP

WHERE WHERE WHERE WHERE WHERE

ENAME EMPNO ENAME ENAME ENAME

NOT NOT NOT NOT NOT

35

BETWEEN 'K' AND 'P'; IN(7788,7839,7968,7654) ; IN ('SCOTT','MARTIN','ALLEN','ASLAM'); LIKE 'A%'; LIKE '%S';

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Rules of Precedence Order Evaluated Operator 1 Arithmetic operators 2 Concatenation operator 3 Comparison conditions 4 IS [NOT] NULL, LIKE, [NOT] IN 5 [NOT] BETWEEN 6 NOT logical condition 7 AND logical condition 8 OR logical condition The rules of precedence determine the order in which expressions are evaluated and calculated. The table lists the default order of precedence. You can override the default order by using parentheses around the expressions you want to calculate first. AND Operator Evaluates first in the following example:

CLERK of department number 10 or MANAGER of any department SQL> SELECT ENAME,JOB,SAL,DEPTNO FROM EMP 2 WHERE JOB='MANAGER' OR JOB='CLERK' AND DEPTNO=10; ENAME ---------JONES BLAKE CLARK MILLER

JOB SAL DEPTNO --------- --------- --------MANAGER 2975 20 MANAGER 2850 30 MANAGER 2450 10 CLERK 1300 10

Example of the Precedence of the AND Operator In the above example, there are two conditions: • The first condition is that the JOB is CLERK and the DEPTNO is 10. • The second condition is that the JOB is MANAGER. Therefore, the SELECT statement reads as follows: “Select the row if an employee is a CLERK and belong to department number 10, or if the employee is a MANAGER.”

CLERK and MANAGER of department number 10 SQL> SELECT ENAME,JOB,SAL,DEPTNO FROM EMP 2 WHERE (JOB='MANAGER' OR JOB='CLERK') AND DEPTNO=10; ENAME ---------CLARK MILLER

JOB SAL DEPTNO --------- --------- --------MANAGER 2450 10 CLERK 1300 10

Using Parentheses In the example, there are two conditions: • The first condition is that the JOB is CLERK or MANAGER. • The second condition is DEPTNO is 10. Therefore, the SELECT statement reads as follows: “Select the row if an employee is a CLERK or a MANAGER, and if the employee belongs to department number 10.” 36

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Sorting Data The ORDER BY Clause

The order of rows returned in a query result is undefined. The ORDER BY clause can be used to sort the rows. If you use the ORDER BY clause, it must be the last clause of the SQL statement. You can specify an expression, or an alias, or column position as the sort condition. Sorting By Column Name SQL> SELECT * FROM EMP ORDER BY ENAME; EMPNO --------7876 7499 7698 7782 7902 7900 7566 7839 7654 7934 7788 7369 7844 7521

ENAME ---------ADAMS ALLEN BLAKE CLARK FORD JAMES JONES KING MARTIN MILLER SCOTT SMITH TURNER WARD

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7788 23-MAY-87 1100 20 SALESMAN 7698 20-FEB-81 1600 300 30 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 ANALYST 7566 03-DEC-81 3000 20 CLERK 7698 03-DEC-81 950 30 MANAGER 7839 02-APR-81 2975 20 PRESIDENT 17-NOV-81 5000 10 SALESMAN 7698 28-SEP-81 1250 1400 30 CLERK 7782 23-JAN-82 1300 10 ANALYST 7566 19-APR-87 3000 20 CLERK 7902 17-DEC-80 800 20 SALESMAN 7698 08-SEP-81 1500 0 30 SALESMAN 7698 22-FEB-81 1250 500 30

14 rows selected. Sorting on Multiple Columns SQL> SELECT * FROM EMP ORDER BY DEPTNO, ENAME; EMPNO --------7782 7839 7934 7876 7902 7566 7788 7369 7499 7698 7900 7654 7844 7521

ENAME ---------CLARK KING MILLER ADAMS FORD JONES SCOTT SMITH ALLEN BLAKE JAMES MARTIN TURNER WARD

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 09-JUN-81 2450 10 PRESIDENT 17-NOV-81 5000 10 CLERK 7782 23-JAN-82 1300 10 CLERK 7788 23-MAY-87 1100 20 ANALYST 7566 03-DEC-81 3000 20 MANAGER 7839 02-APR-81 2975 20 ANALYST 7566 19-APR-87 3000 20 CLERK 7902 17-DEC-80 800 20 SALESMAN 7698 20-FEB-81 1600 300 30 MANAGER 7839 01-MAY-81 2850 30 CLERK 7698 03-DEC-81 950 30 SALESMAN 7698 28-SEP-81 1250 1400 30 SALESMAN 7698 08-SEP-81 1500 0 30 SALESMAN 7698 22-FEB-81 1250 500 30

14 rows selected. SQL> SQL> SQL> SQL>

SELECT SELECT SELECT SELECT

* FROM * FROM EMPNO, EMPNO,

EMP ORDER BY ENAME DESC; EMP ORDER BY DEPTNO, ENAME DESC; ENAME, JOB, SAL, COMM FROM EMP ORDER BY JOB; ENAME, JOB, SAL, COMM FROM EMP ORDER BY JOB DESC;

37

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Sorting By Column Position SQL> SQL> SQL> SQL>

SELECT SELECT SELECT SELECT

* FROM * FROM EMPNO, EMPNO,

EMP ORDER BY 2; EMP ORDER BY 2 DESC; ENAME, JOB, DEPTNO FROM EMP ORDER BY 2; ENAME, JOB, DEPTNO FROM EMP ORDER BY 4,1;

Sorting By Column Alias SQL> SELECT ENAME,SAL,COMM, SAL*12 ANN_SAL FROM EMP ORDER BY ANN_SAL; ENAME SAL COMM ANN_SAL ---------- --------- --------- --------SMITH 800 9600 JAMES 950 11400 ADAMS 1100 13200 WARD 1250 500 15000 MARTIN 1250 1400 15000 MILLER 1300 15600 TURNER 1500 0 18000 ALLEN 1600 300 19200 CLARK 2450 29400 BLAKE 2850 34200 JONES 2975 35700 SCOTT 3000 36000 FORD 3000 36000 KING 5000 60000

SQL> SELECT EMPNO, ENAME, SAL SALARY FROM EMP ORDER BY SALARY; How Null Values Appear When Ordering (Sorting) SQL> SELECT * FROM EMP ORDER BY COMM; EMPNO --------7844 7499 7521 7654 7788 7839 7876 7900 7902 7934 7698 7566 7369 7782

ENAME ---------TURNER ALLEN WARD MARTIN SCOTT KING ADAMS JAMES FORD MILLER BLAKE JONES SMITH CLARK

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------SALESMAN 7698 08-SEP-81 1500 0 30 SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 SALESMAN 7698 28-SEP-81 1250 1400 30 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 ANALYST 7566 03-DEC-81 3000 20 CLERK 7782 23-JAN-82 1300 10 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 02-APR-81 2975 20 CLERK 7902 17-DEC-80 800 20 MANAGER 7839 09-JUN-81 2450 10

SQL> SELECT * FROM EMP ORDER BY COMM DESC; What is Differences in result? SQL> SELECT EMPNO, ENAME, JOB DESIGNATION FROM EMP ORDER BY 3; SQL> SELECT EMPNO, ENAME, JOB DESIGNATION FROM EMP ORDER BY JOB; SQL> SELECT EMPNO, ENAME, JOB DESIGNATION FROM EMP ORDER BY DESIGNATION; 38

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Chapter 3

Single-Row Functions Single row functions:

Manipulate data items Accept arguments and return one value Act on each row returned Return one result per row May modify the data type Can be nested Accept arguments which can be a column or an expression

Types of Single Row Functions Character Functions Number Functions Date Functions Conversion Functions General Functions

UPPER, LOWER, INITCAP, LENGTH, SUBSTR, INSTR ROUND, TRUNC, MOD DATE TO_CHAR, TO_DATE, TO_NUMBER NVL, COALESCE

Case Manipulation Functions

LOWER, UPPER, and INITCAP are the three case-conversion functions. • LOWER: Converts mixed case or uppercase character strings to lowercase • UPPER: Converts mixed case or lowercase character strings to uppercase • INITCAP: Converts the first letter of each word to uppercase and remaining letters to lowercase SQL> SELECT UPPER('ORACLE'), LOWER('ORACLE'),INITCAP('ORACLE') FROM DUAL; UPPER( LOWER( INITCA ------ ------ -----ORACLE oracle Oracle SQL> SELECT ENAME, UPPER(ENAME), LOWER(ENAME),INITCAP(ENAME) FROM EMP; ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

UPPER(ENAM ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

LOWER(ENAM ---------smith allen ward jones martin blake clark scott king turner adams james ford miller

INITCAP(EN ---------Smith Allen Ward Jones Martin Blake Clark Scott King Turner Adams James Ford Miller

14 rows selected. SELECT SELECT SELECT SELECT SELECT

* * * * *

FROM FROM FROM FROM FROM

EMP EMP EMP EMP EMP

WHERE WHERE WHERE WHERE WHERE

ENAME = 'smith'; ENAME = UPPER('smith'); LOWER(ENAME) = 'smith'; UPPER(ENAME) = 'SMITH'; UPPER(ENAME) = UPPER('smith'); 39

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Character Manipulation Functions

CONCAT, SUBSTR, LENGTH, INSTR, LPAD, RPAD, and TRIM are the character manipulation functions covered in this lesson. • SUBSTR: Extracts a string of determined length • LENGTH: Shows the length of a string as a numeric value • INSTR: Finds numeric position of a named character • LPAD: Pads the character value right-justified • RPAD: Pads the character value left-justified SQL> SELECT LENGTH('ORACLE SQL') FROM DUAL; LENGTH('ORACLESQL') ------------------10 SQL> SELECT * FROM EMP WHERE LENGTH(ENAME)=4; EMPNO --------7521 7839 7902

ENAME ---------WARD KING FORD

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------SALESMAN 7698 22-FEB-81 1250 500 30 PRESIDENT 17-NOV-81 5000 10 ANALYST 7566 03-DEC-81 3000 20

SQL> SELECT * FROM EMP WHERE ENAME LIKE '____'; EMPNO --------7521 7839 7902

ENAME ---------WARD KING FORD

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------SALESMAN 7698 22-FEB-81 1250 500 30 PRESIDENT 17-NOV-81 5000 10 ANALYST 7566 03-DEC-81 3000 20

SQL> SELECT SUBSTR('PETROMAN',4) FROM DUAL; SUBST ----ROMAN SQL> SELECT SUBSTR('PETROMAN',4,3) FROM DUAL; SUB --ROM SQL> SELECT SUBSTR('PETROMAN',-1,1) FROM DUAL; S N SQL> SELECT SUBSTR('PETROMAN',-2,1) FROM DUAL; S A SQL> SELECT SUBSTR('PETROMAN',-3,3) FROM DUAL; SUB --MAN 40

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Retrieve all employees whose name begins with

S

SQL> SELECT * FROM EMP WHERE SUBSTR(ENAME,1,1)='S'; EMPNO --------7369 7788

ENAME ---------SMITH SCOTT

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 ANALYST 7566 19-APR-87 3000 20

SQL> SELECT * FROM EMP WHERE ENAME LIKE 'S%'; EMPNO --------7369 7788

ENAME ---------SMITH SCOTT

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 ANALYST 7566 19-APR-87 3000 20

Retrieve all employees whose name contains

A

in second position

SQL> SELECT * FROM EMP WHERE SUBSTR(ENAME,2,1)='A'; EMPNO --------7521 7654 7900

ENAME ---------WARD MARTIN JAMES

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------SALESMAN 7698 22-FEB-81 1250 500 30 SALESMAN 7698 28-SEP-81 1250 1400 30 CLERK 7698 03-DEC-81 950 30

SQL> SELECT * FROM EMP WHERE ENAME LIKE '_A%'; EMPNO --------7521 7654 7900

ENAME ---------WARD MARTIN JAMES

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------SALESMAN 7698 22-FEB-81 1250 500 30 SALESMAN 7698 28-SEP-81 1250 1400 30 CLERK 7698 03-DEC-81 950 30

Retrieve all employees whose name ends with S SQL> SELECT * FROM EMP WHERE SUBSTR(ENAME,-1,1)='S'; EMPNO --------7566 7876 7900

ENAME ---------JONES ADAMS JAMES

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 02-APR-81 2975 20 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30

SQL> SELECT * FROM EMP WHERE ENAME LIKE '%S'; EMPNO --------7566 7876 7900

ENAME ---------JONES ADAMS JAMES

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 02-APR-81 2975 20 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30

SQL>

41

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

INSTR() SQL> SELECT INSTR('PAKISTAN','I') FROM DUAL; INSTR('PAKISTAN','I') --------------------4 SQL> SELECT INSTR('PAKISTAN','i') FROM DUAL; INSTR('PAKISTAN','I') --------------------0 SQL> SELECT INSTR('PAKISTAN','TA') FROM DUAL; INSTR('PAKISTAN','TA') ---------------------6 SQL> SELECT INSTR('PAKISTAN','A') FROM DUAL; INSTR('PAKISTAN','A') --------------------2 SQL> SELECT ENAME,INSTR(ENAME,'A') FROM EMP; ENAME INSTR(ENAME,'A') ---------- ---------------SMITH 0 ALLEN 1 WARD 2 JONES 0 MARTIN 2 BLAKE 3 CLARK 3 SCOTT 0 KING 0 TURNER 0 ADAMS 1 JAMES 2 FORD 0 MILLER 0

Find occurrence of 'a' start from 3rd position SQL> SELECT INSTR('PAKISTAN','A',3) FROM DUAL; INSTR('PAKISTAN','A',3) ----------------------7

Assignment

CRV-0807-2011 CPV-0807-0111 BRV-0807-0002 BPV-0807-0201 JV-0807-0128

Extract Extract Extract Extract

CRV, which denotes Voucher Type 0807, which denotes year 08 and month 07 08 from this BRV, 08 denotes year 2008 07 from this BPV, 07 denotes July of 2008

Extract 0128 from this JV, which denotes Voucher No. 42

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Before padding or before filling means left padding or left filling Using LPAD( ) functions SQL> SELECT LPAD('PAK',7,'*') FROM DUAL; LPAD('P ------****PAK SQL> SELECT LPAD('PAK',7,' ') FROM DUAL; LPAD('P ------PAK SQL> SELECT LPAD('PAK',7,'->') FROM DUAL; LPAD('P ------->->PAK SQL> SELECT LPAD('PAK',7,'123-') FROM DUAL; LPAD('P ------123-PAK SQL> SELECT LPAD('4265550',12,'0321-') CELL_NO FROM DUAL; CELL_NO -----------0321-4265550 SQL> SELECT LPAD('4265550',11,'021-') PTCL_NO FROM DUAL; PTCL_NO ----------021-4265550 SQL> SELECT EMPNO, ENAME, LPAD(EMPNO,8,'ORA-') NEW_EMPNO, 2 LPAD(ENAME,15,'.') ENAME, LPAD(ENAME,15,' ') ENAME FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

NEW_EMPN -------ORA-7369 ORA-7499 ORA-7521 ORA-7566 ORA-7654 ORA-7698 ORA-7782 ORA-7788 ORA-7839 ORA-7844 ORA-7876 ORA-7900 ORA-7902 ORA-7934

ENAME ENAME --------------- --------------..........SMITH SMITH ..........ALLEN ALLEN ...........WARD WARD ..........JONES JONES .........MARTIN MARTIN ..........BLAKE BLAKE ..........CLARK CLARK ..........SCOTT SCOTT ...........KING KING .........TURNER TURNER ..........ADAMS ADAMS ..........JAMES JAMES ...........FORD FORD .........MILLER MILLER

14 rows selected. 43

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

After padding or after filling means right padding or right filling Using RPAD( ) functions SQL> SELECT EMPNO, RPAD(ENAME,40,'.') ENAME, LPAD(JOB,10,' ') JOB, SAL FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME JOB SAL ---------------------------------------- ---------- --------SMITH................................... CLERK 800 ALLEN................................... SALESMAN 1600 WARD.................................... SALESMAN 1250 JONES................................... MANAGER 2975 MARTIN.................................. SALESMAN 1250 BLAKE................................... MANAGER 2850 CLARK................................... MANAGER 2450 SCOTT................................... ANALYST 3000 KING.................................... PRESIDENT 5000 TURNER.................................. SALESMAN 1500 ADAMS................................... CLERK 1100 JAMES................................... CLERK 950 FORD.................................... ANALYST 3000 MILLER.................................. CLERK 1300

14 rows selected. SQL>

Number Functions Number functions accept numeric input and return numeric values. This section describes some of the number functions. ROUND Function The ROUND function rounds the column, expression, or value to n decimal places. If the second argument is 0 or is missing, the value is rounded to zero decimal places. If the second argument is 2, the value is rounded to two decimal places. Conversely, if the second argument is -2, the value is rounded to two decimal places to the left. The ROUND function can also be used with date functions. You will see examples later in this lesson. TRUNC Function The TRUNC function truncates the column, expression, or value to n decimal places. The TRUNC function works with arguments similar to those of the ROUND function. If the second argument is 0 or is missing, the value is truncated to zero decimal places. If the second argument is 2, the value is truncated to two decimal places. Conversely, if the second argument is -2, the value is truncated to two decimal places to the left. Like the ROUND function, the TRUNC function can be used with date functions. MOD Function The MOD function finds the remainder of value1 divided by value2. Note: The MOD function is often used to determine if a value is odd or even. 44

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

ROUND ( ) function with numbers SQL> 2 3 4 5 6 7

SELECT ROUND(5.9283), ROUND(5.9283,0), ROUND(5.9283,1), ROUND(5.9283,2), ROUND(5.9283,3) FROM DUAL;

ROUND(5.9283) ROUND(5.9283,0) ROUND(5.9283,1) ROUND(5.9283,2) ROUND(5.9283,3) ------------- --------------- --------------- --------------- --------------6 6 5.9 5.93 5.928 SQL> 2 3 4 5 6 7

SELECT ROUND(3.5397), ROUND(3.5397,0), ROUND(3.5397,1), ROUND(3.5397,2), ROUND(3.5397,3) FROM DUAL;

ROUND(3.5397) ROUND(3.5397,0) ROUND(3.5397,1) ROUND(3.5397,2) ROUND(3.5397,3) ------------- --------------- --------------- --------------- --------------4 4 3.5 3.54 3.54

TRUNC ( ) function with numbers SQL> 2 3 4 5 6 7

SELECT TRUNC(5.9283), TRUNC(5.9283,0), TRUNC(5.9283,1), TRUNC(5.9283,2), TRUNC(5.9283,3) FROM DUAL;

TRUNC(5.9283) TRUNC(5.9283,0) TRUNC(5.9283,1) TRUNC(5.9283,2) TRUNC(5.9283,3) ------------- --------------- --------------- --------------- --------------5 5 5.9 5.92 5.928 SQL> 2 3 4 5 6 7

SELECT TRUNC(3.5397), TRUNC(3.5397,0), TRUNC(3.5397,1), TRUNC(3.5397,2), TRUNC(3.5397,3) FROM DUAL;

TRUNC(3.5397) TRUNC(3.5397,0) TRUNC(3.5397,1) TRUNC(3.5397,2) TRUNC(3.5397,3) ------------- --------------- --------------- --------------- --------------3 3 3.5 3.53 3.539 SQL>

45

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

ROUND ( ) with -Ve Decimal Request -1 -2 -3 -4 SQL> 2 3 4 5 6

nearest nearest nearest nearest

10 100 1000 10000

10 100 1000 10000

20 200 2000 20000

30 300 3000 30000

40... 400... 4000... 40000...

SELECT ROUND(3175.9283,-1), ROUND(3175.9283,-2), ROUND(3175.9283,-3), ROUND(3175.9283,-4) FROM DUAL;

ROUND(3175.9283,-1) ROUND(3175.9283,-2) ROUND(3175.9283,-3) ROUND(3175.9283,-4) ------------------- ------------------- ------------------- ------------------3180 3200 3000 0 SQL> 2 3 4 5 6

SELECT ROUND(5175.9283,-1), ROUND(5175.9283,-2), ROUND(5175.9283,-3), ROUND(5175.9283,-4) FROM DUAL;

ROUND(5175.9283,-1) ROUND(5175.9283,-2) ROUND(5175.9283,-3) ROUND(5175.9283,-4) ------------------- ------------------- ------------------- ------------------5180 5200 5000 10000 SQL> 2 3 4 5 6

SELECT ROUND(5675.9283,-1), ROUND(5675.9283,-2), ROUND(5675.9283,-3), ROUND(5675.9283,-4) FROM DUAL;

ROUND(5675.9283,-1) ROUND(5675.9283,-2) ROUND(5675.9283,-3) ROUND(5675.9283,-4) ------------------- ------------------- ------------------- ------------------5680 5700 6000 10000

TRUNC ( ) with -Ve Decimal Request SQL> 2 3 4 5 6

SELECT TRUNC(5675.9283,-1), TRUNC(5675.9283,-2), TRUNC(5675.9283,-3), TRUNC(5675.9283,-4) FROM DUAL;

TRUNC(5675.9283,-1) TRUNC(5675.9283,-2) TRUNC(5675.9283,-3) TRUNC(5675.9283,-4) ------------------- ------------------- ------------------- ------------------5670 5600 5000 0 SQL>

46

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

MOD ( ) SQL> SELECT MOD(3,2), MOD(10,2), MOD(15,3), MOD(52,6), MOD(230,5) FROM DUAL; MOD(3,2) MOD(10,2) MOD(15,3) MOD(52,6) MOD(230,5) --------- --------- --------- --------- ---------1 0 0 4 0 The example calculates the remainder of the salary after dividing it by 500 for all employees. SQL> 2 3 4 5 6 7

SELECT ENAME, SAL, MOD(SAL,500), SAL-MOD(SAL,500), (SAL-MOD(SAL,500))/500 NOTES_500, -- (SAL-MOD(SAL,500))/1000 NOTES_1000, TRUNC((SAL-MOD(SAL,500))/1000) NOTES_1000 FROM EMP;

ENAME SAL MOD(SAL,500) SAL-MOD(SAL,500) NOTES_500 NOTES_1000 ---------- --------- ------------ ---------------- --------- ---------SMITH 800 300 500 1 0 ALLEN 1600 100 1500 3 1 WARD 1250 250 1000 2 1 JONES 2975 475 2500 5 2 MARTIN 1250 250 1000 2 1 BLAKE 2850 350 2500 5 2 CLARK 2450 450 2000 4 2 SCOTT 3000 0 3000 6 3 KING 5000 0 5000 10 5 TURNER 1500 0 1500 3 1 ADAMS 1100 100 1000 2 1 JAMES 950 450 500 1 0 FORD 3000 0 3000 6 3 MILLER 1300 300 1000 2 1 14 rows selected. SQL>

47

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Working with Dates Arithmetic with Dates SQL> SELECT SYSDATE, SYSDATE-1, SYSDATE+1 FROM DUAL; SYSDATE SYSDATE-1 SYSDATE+1 --------- --------- --------24-JUL-08 23-JUL-08 25-JUL-08 SQL> SELECT ENAME,HIREDATE,HIREDATE-5,HIREDATE+5 FROM EMP; ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

HIREDATE --------17-DEC-80 20-FEB-81 22-FEB-81 02-APR-81 28-SEP-81 01-MAY-81 09-JUN-81 19-APR-87 17-NOV-81 08-SEP-81 23-MAY-87 03-DEC-81 03-DEC-81 23-JAN-82

HIREDATE--------12-DEC-80 15-FEB-81 17-FEB-81 28-MAR-81 23-SEP-81 26-APR-81 04-JUN-81 14-APR-87 12-NOV-81 03-SEP-81 18-MAY-87 28-NOV-81 28-NOV-81 18-JAN-82

HIREDATE+ --------22-DEC-80 25-FEB-81 27-FEB-81 07-APR-81 03-OCT-81 06-MAY-81 14-JUN-81 24-APR-87 22-NOV-81 13-SEP-81 28-MAY-87 08-DEC-81 08-DEC-81 28-JAN-82

14 rows selected.

Finding job duration SQL> 2 3 4 5 6

SELECT ENAME,SYSDATE,HIREDATE, SYSDATE-HIREDATE IN_DAYS, (SYSDATE - HIREDATE) / 7 IN_WEEKS, (SYSDATE - HIREDATE) / 30 IN_MONTHS, (SYSDATE - HIREDATE) / 365 IN_YEARS FROM EMP;

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

SYSDATE --------24-JUL-08 24-JUL-08 24-JUL-08 24-JUL-08 24-JUL-08 24-JUL-08 24-JUL-08 24-JUL-08 24-JUL-08 24-JUL-08 24-JUL-08 24-JUL-08 24-JUL-08 24-JUL-08

HIREDATE --------17-DEC-80 20-FEB-81 22-FEB-81 02-APR-81 28-SEP-81 01-MAY-81 09-JUN-81 19-APR-87 17-NOV-81 08-SEP-81 23-MAY-87 03-DEC-81 03-DEC-81 23-JAN-82

IN_DAYS --------10081.777 10016.777 10014.777 9975.7768 9796.7768 9946.7768 9907.7768 7767.7768 9746.7768 9816.7768 7733.7768 9730.7768 9730.7768 9679.7768

IN_WEEKS --------1440.2538 1430.9681 1430.6824 1425.111 1399.5395 1420.9681 1415.3967 1109.6824 1392.3967 1402.3967 1104.8253 1390.111 1390.111 1382.8253

IN_MONTHS --------336.05923 333.89256 333.82589 332.52589 326.55923 331.55923 330.25923 258.92589 324.89256 327.22589 257.79256 324.35923 324.35923 322.65923

IN_YEARS --------27.621306 27.443224 27.437745 27.330895 26.840484 27.251443 27.144594 21.28158 26.703498 26.895279 21.188429 26.659662 26.659662 26.519936

14 rows selected. SQL> 48

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Oracle Date Format Oracle database stores dates in an internal numeric format, representing the century, year, month, day, hours, minutes, and seconds. The default display and input format for any date is DD-MON-RR. Valid Oracle dates are between January 1, 4712 B.C. and December 31, 9999 A.D. This data is stored internally as follows: CENTURY YEAR MONTH 19 94 06

DAY 07

HOUR 5

MINUTE 10

SECOND 43

Centuries and the Year 2000 The Oracle server is year 2000 compliant. When a record with a date column is inserted into a table, the century information is picked up from the SYSDATE function. However, when the date column is displayed on the screen, the century component is not displayed by default. The DATE data type always stores year information as a four-digit number internally: two digits for the century and two digits for the year. For example, the Oracle database stores the year as 1996 or 2001, and not just as 96 or 01.

The SYSDATE Function SYSDATE is a date function that returns the current database server date and time. You can use SYSDATE just as you would use any other column name. For example, you can display the current date by selecting SYSDATE from a table. It is customary to select SYSDATE from a dummy table called DUAL.

Date Functions Date functions operate on Oracle dates. All date functions return a value of DATE data type except MONTHS_BETWEEN, which returns a numeric value. •

MONTHS_BETWEEN(date1, date2): Finds the number of months between date1 and date2. The result can be positive or negative. If date1 is later than date2, the result is positive; if date1 is earlier than date2, the result is negative. The noninteger part of the result represents a portion of the month.



ADD_MONTHS(date, n): Adds n number of calendar months to date. The value of n must be an integer and can be negative.



NEXT_DAY(date, 'char'): Finds the date of the next specified day of the week ('char') following date. The value of char may be a number representing a day or a character string.



LAST_DAY(date): Finds the date of the last day of the month that contains date.



ROUND(date[,'fmt']): Returns date rounded to the unit specified by the format model fmt. If the format model fmt is omitted, date is rounded to the nearest day.



TRUNC(date[, 'fmt']): Returns date with the time portion of the day truncated to the unit specified by the format model fmt. If the format model fmt is omitted, date is truncated to the nearest day.

49

[email protected]

Prepared by Muhammad Raheem

Oracle SQL SQL> 2 3 4 5 6 7

Phone: 021-4265550, Cell: 0321-4265550

SELECT MONTHS_BETWEEN('14-AUG-2008','14-AUG-1947') TOT_MONTHS, MONTHS_BETWEEN('14-AUG-2008','14-AUG-1947')/12 TOT_YEARS, MONTHS_BETWEEN('14-AUG-2008','14-AUG-1947')*4 TOT_WEEKS, MONTHS_BETWEEN('14-AUG-2008','14-AUG-1947')*30 TOT_DAYS, MONTHS_BETWEEN('14-AUG-2008','14-AUG-1947')*30*24 TOT_HOURS FROM DUAL;

TOT_MONTHS TOT_YEARS TOT_WEEKS TOT_DAYS TOT_HOURS ---------- --------- --------- --------- --------732 61 2928 21960 527040 SQL> SQL> 2 3 4 5 6 7 8

SELECT ADD_MONTHS('14-AUG-2008',1) AFTER_1_MONTH, ADD_MONTHS('14-AUG-2008',6) AFTER_6_MONTHS, ADD_MONTHS('14-AUG-2008',12) AFTER_1_YEAR, ADD_MONTHS('14-AUG-2008',12*3) AFTER_3_YEARS, ADD_MONTHS('14-AUG-2008',-3) BEFORE_3_MONTHS, ADD_MONTHS('14-AUG-2008',-12*3) BEFORE_3_YEARS FROM DUAL;

AFTER_1_M AFTER_6_M AFTER_1_Y AFTER_3_Y BEFORE_3_ BEFORE_3_ --------- --------- --------- --------- --------- --------14-SEP-08 14-FEB-09 14-AUG-09 14-AUG-11 14-MAY-08 14-AUG-05 SQL>

What was the first Thursday, Friday, Saturday & Sunday after August 14, 1947 SQL> 2 3 4 5 6

SELECT NEXT_DAY('14-AUG-1947','THURSDAY') FIRST_THU, NEXT_DAY('14-AUG-1947','FRIDAY') FIRST_FRI, NEXT_DAY('14-AUG-1947','SATURDAY') FIRST_SAT, NEXT_DAY('14-AUG-1947','SUNDAY') FIRST_SUN FROM DUAL;

FIRST_THU FIRST_FRI FIRST_SAT FIRST_SUN --------- --------- --------- --------21-AUG-47 15-AUG-47 16-AUG-47 17-AUG-47 SQL>

How to find last day of the month SQL> 2 3 4 5

SELECT LAST_DAY('14-AUG-1947'), LAST_DAY('14-FEB-1947'), LAST_DAY('14-FEB-2008') FROM DUAL;

LAST_DAY( LAST_DAY( LAST_DAY( --------- --------- --------31-AUG-47 28-FEB-47 29-FEB-08 SQL> 50

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Find out duration of each employee SQL> 2 3 4 5

SELECT EMPNO, ENAME, SYSDATE, HIREDATE, MONTHS_BETWEEN(SYSDATE,HIREDATE) IN_MONTHS, MONTHS_BETWEEN(SYSDATE,HIREDATE)/12 IN_YEARS, MONTHS_BETWEEN(SYSDATE,HIREDATE)*30 IN_DAYS FROM EMP;

EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

SYSDATE --------24-JUL-08 24-JUL-08 24-JUL-08 24-JUL-08 24-JUL-08 24-JUL-08 24-JUL-08 24-JUL-08 24-JUL-08 24-JUL-08 24-JUL-08 24-JUL-08 24-JUL-08 24-JUL-08

HIREDATE --------17-DEC-80 20-FEB-81 22-FEB-81 02-APR-81 28-SEP-81 01-MAY-81 09-JUN-81 19-APR-87 17-NOV-81 08-SEP-81 23-MAY-87 03-DEC-81 03-DEC-81 23-JAN-82

IN_MONTHS --------331.25276 329.15598 329.09147 327.73663 321.89792 326.76889 325.51082 255.18824 320.25276 322.54308 254.05921 319.70437 319.70437 318.05921

IN_YEARS --------27.604397 27.429665 27.424289 27.311386 26.824827 27.230741 27.125902 21.265687 26.68773 26.87859 21.171601 26.642031 26.642031 26.504934

IN_DAYS --------9937.5828 9874.6795 9872.7441 9832.0989 9656.9376 9803.0666 9765.3247 7655.6473 9607.5828 9676.2924 7621.7763 9591.1311 9591.1311 9541.7763

14 rows selected.

What was the first Sunday after hiring What was the last day in which each employee was hired What was the date after two months of hiring SQL> 2 3 4 5 6

SELECT EMPNO, ENAME, HIREDATE, NEXT_DAY(HIREDATE,'SUNDAY') FIRST_SUN, LAST_DAY(HIREDATE) LAST_DAY, ADD_MONTHS(HIREDATE,2) AFTER_2_MONTHS FROM EMP;

EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

HIREDATE --------17-DEC-80 20-FEB-81 22-FEB-81 02-APR-81 28-SEP-81 01-MAY-81 09-JUN-81 19-APR-87 17-NOV-81 08-SEP-81 23-MAY-87 03-DEC-81 03-DEC-81 23-JAN-82

FIRST_SUN --------21-DEC-80 22-FEB-81 01-MAR-81 05-APR-81 04-OCT-81 03-MAY-81 14-JUN-81 26-APR-87 22-NOV-81 13-SEP-81 24-MAY-87 06-DEC-81 06-DEC-81 24-JAN-82

LAST_DAY --------31-DEC-80 28-FEB-81 28-FEB-81 30-APR-81 30-SEP-81 31-MAY-81 30-JUN-81 30-APR-87 30-NOV-81 30-SEP-81 31-MAY-87 31-DEC-81 31-DEC-81 31-JAN-82

AFTER_2_M --------17-FEB-81 20-APR-81 22-APR-81 02-JUN-81 28-NOV-81 01-JUL-81 09-AUG-81 19-JUN-87 17-JAN-82 08-NOV-81 23-JUL-87 03-FEB-82 03-FEB-82 23-MAR-82

14 rows selected. SQL> 51

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

ROUND ( ) & TRUNC ( ) functions with date The ROUND and TRUNC functions can be used for number and date values. When used with dates, these functions round or truncate to the specified format model. Therefore, you can round dates to the nearest year or month. ROUND (MONTH) 01-15 FIRST DAY OF SAME MONTH 16-31 FIRST DAY OF NEXT MONTH ROUND (YEAR) 01-JAN ... 30-JUN 01-JUL ... 31-DEC

FIRST DAY OF SAME YEAR FIRST DAY OF NEXT YEAR

TRUNC (MONTH) 01-31 FIRST DAY OF SAME MONTH TRUNC (YEAR) 01-JAN ... 31-DEC

FIRST DAY OF SAME YEAR.

ROUND (DD) DEFAULT IF NOT SPECIFIED LESS THAN 12:00PM SAM DAY MORE THAN 12:00PM NEXT DAY ROUND (DAY) BEFORE 12:00PM WEDNESDAY, PREVIOUS SUNDAY OF THE WEEK AFTER 12:00PM WEDNESDAY, NEXT SUNDAY OF THE WEEK TRUNC (DD) TRUNC (DAY)

Same Day, eliminating time portion from date Previous Sunday

Assume SYSDATE is 24-JUL-2008 SQL> SELECT SYSDATE, ROUND(SYSDATE,'MONTH'), TRUNC(SYSDATE,'MONTH') FROM DUAL; SYSDATE ROUND(SYS TRUNC(SYS --------- --------- --------24-JUL-08 01-AUG-08 01-JUL-08 SQL> 2 3 4 5

SELECT SYSDATE-10, ROUND(SYSDATE-10,'MONTH'), TRUNC(SYSDATE-10,'MONTH') FROM DUAL;

SYSDATE-1 ROUND(SYS TRUNC(SYS --------- --------- --------14-JUL-08 01-JUL-08 01-JUL-08 SQL> 2 3 4 5

SELECT SYSDATE-30, ROUND(SYSDATE-30,'MONTH'), TRUNC(SYSDATE-30,'MONTH') FROM DUAL;

24-JUN-08 01-JUL-08 01-JUN-08 52

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT SYSDATE, ROUND(SYSDATE,'YEAR'), TRUNC(SYSDATE,'YEAR') FROM DUAL; SYSDATE ROUND(SYS TRUNC(SYS --------- --------- --------24-JUL-08 01-JAN-09 01-JAN-08

SQL> 2 3 4 5

SELECT SYSDATE-10, ROUND(SYSDATE-10,'YEAR'), TRUNC(SYSDATE-10,'YEAR') FROM DUAL;

SYSDATE-1 ROUND(SYS TRUNC(SYS --------- --------- --------14-JUL-08 01-JAN-09 01-JAN-08

SQL> 2 3 4 5

SELECT SYSDATE-30, ROUND(SYSDATE-30,'MONTH'), TRUNC(SYSDATE-30,'MONTH') FROM DUAL;

SYSDATE-3 ROUND(SYS TRUNC(SYS --------- --------- --------24-JUN-08 01-JUL-08 01-JUN-08

SQL> 2 3 4 5 6

SELECT SYSDATE, NEXT_DAY(SYSDATE,'SUNDAY') COMMING_SUNDAY, ROUND(SYSDATE,'DAY') COMMING_SUNDAY, TRUNC(SYSDATE,'DAY') LAST_SUNDAY FROM DUAL;

SYSDATE COMMING_S COMMING_S LAST_SUND --------- --------- --------- --------24-JUL-08 27-JUL-08 27-JUL-08 20-JUL-08

Suppose date is 24-JUL-2008 and time is 13:55 SQL> SELECT SYSDATE, ROUND(SYSDATE), TRUNC(SYSDATE) FROM DUAL; SYSDATE ROUND(SYS TRUNC(SYS --------- --------- --------24-JUL-08 25-JUL-08 24-JUL-08 Note: Oracle also store time with date. When comparing date column without time portion, it is recommended to use trunc() function with that column. Because trunc ( ) eliminate time portion. Remember TRUNC (DD) remove time portion and TRUNC(DD) is default. SQL> SELECT * FROM EMP WHERE TRUNC(HIREDATE)='17-DEC-1980'; EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO --------- ---------- --------- --------- --------- --------- --------- --------7369 SMITH CLERK 7902 17-DEC-80 800 20

53

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Conversion Functions In addition to Oracle data types, columns of tables in an Oracle9i database can be defined using ANSI, DB2, and SQL/DS data types. However, the Oracle server internally converts such data types to Oracle data types. In some cases, Oracle server uses data of one data type where it expects data of a different data type. When this happens, Oracle server can automatically convert the data to the expected data type. This data type conversion can be done implicitly by Oracle server, or explicitly by the user. Implicit data type conversions work according to the rules explained in the next two slides. Explicit data type conversions are done by using the conversion functions. Conversion functions convert a value from one data type to another. Generally, the form of the function names follows the convention data type TO data type. The first data type is the input data type; the last data type is the output. Note: Although implicit data type conversion is available, it is recommended that you do explicit data type conversion to ensure the reliability of your SQL statements.

Explicit Data Type Conversion

TO_NUMBER

NUMBER

TO_DATE

CHARACTER

TO_CHAR

DATE

TO_CHAR

54

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Using the TO_CHAR Function with Dates Displaying a Date in a Specific Format Previously, all Oracle date values were displayed in the DD-MON-YY format. You can use the TO_CHAR function to convert a date from this default format to one specified by you. The format model: • Must be enclosed in single quotation marks and is case sensitive • Can include any valid date format element • Has an fm element to remove padded blanks or suppress leading zeros • Is separated from the date value by a comma DD MON Mon MONTH Month YY RR YEAR Year HH12 HH24 AM PM MI SS DY Dy DAY Day

01-31 JAN, FEB, ... DEC Jan, Feb, ... Dec JANUARY, FEBRUARY, ... DECEMBER January, February, ... December 01, 02, 03 ... (Century) 01, 02, 03 ... (Century) SPELL OUT YEAR Spell Out Year 1 - 12 0 - 23

01 - 59 MINUTES 01 - 59 SECONDS MON, TUE, .... SUN Mon, Tue, .... Sun MONDAY, TUESDAY, ... SUNDAY Monday, Tuesday, ... Sunday

How to display time portion SQL> SELECT TO_CHAR(SYSDATE,'DD-MON-YY HH24:MI:SS') FROM DUAL;

24-JUL-08 14:29:37 SQL> SELECT TO_CHAR(SYSDATE,'DD-MON-YY HH12:MI:SS AM') FROM DUAL;

24-JUL-08 02:29:41 PM SQL> SELECT TO_CHAR(SYSDATE,'DD-MON-YY HH12:MI:SS') FROM DUAL;

24-JUL-08 02:30:03 SQL> SELECT TO_CHAR(SYSDATE,'HH12:MI:SS') FROM DUAL;

02:31:40 SQL> SELECT TO_CHAR(SYSDATE,'HH12:MI:SS AM') FROM DUAL;

02:31:55 PM SQL> SELECT TO_CHAR(SYSDATE,'HH24:MI:SS') FROM DUAL;

14:32:05 55

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT TO_CHAR(SYSDATE,'DD/MM/YY HH12:MI:SS AM') FROM DUAL;

24/07/08 02:38:33 PM SQL> SELECT TO_CHAR(SYSDATE,'DD/MM/RR HH12:MI:SS AM') FROM DUAL;

24/07/08 02:38:44 PM SQL> SELECT TO_CHAR(SYSDATE,'DD/MM/RRRR HH12:MI:SS AM') FROM DUAL;

24/07/2008 02:38:49 PM Adding 3 Days SQL> SELECT TO_CHAR(SYSDATE,'DD-MON-RR HH24:MI:SS'), 2 TO_CHAR(SYSDATE+3,'DD-MON-RR HH24:MI:SS') 3 FROM DUAL;

24-JUL-08 15:16:18 27-JUL-08 15:16:18 Adding 3 Hours SQL> SELECT TO_CHAR(SYSDATE,'DD-MON-RR HH24:MI:SS'), 2 TO_CHAR(SYSDATE+3/24,'DD-MON-RR HH24:MI:SS') 3 FROM DUAL;

24-JUL-08 15:16:44

24-JUL-08 18:16:44

SQL> SELECT TO_CHAR(SYSDATE,'DAY, MONTH DD RRRR') FROM DUAL;

THURSDAY , JULY

24 2008

SQL> SELECT TO_CHAR(SYSDATE,'Day, Month DD RRRR') FROM DUAL;

Thursday , July

24 2008

SQL> SELECT TO_CHAR(SYSDATE,'Day, Mon DD RRRR') FROM DUAL;

Thursday , Jul 24 2008 SQL> SELECT TO_CHAR(SYSDATE,'Dy, Mon DD RRRR') FROM DUAL;

Thu, Jul 24 2008 SQL> SELECT TO_CHAR(SYSDATE,'DAY Day DY Dy') from dual;

THURSDAY

Thursday

THU Thu

56

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT TO_CHAR(SYSDATE,'DD DDTH DDSP DDSPTH Ddth DdSP DdSPTH') FROM DUAL;

24 24TH TWENTY-FOUR TWENTY-FOURTH 24th Twenty-Four Twenty-Fourth SQL> SELECT TO_CHAR(SYSDATE,'MM MmTH MmSP MmSPTH MON Mon MONTH Month') FROM DUAL;

07 07th Seven Seventh JUL Jul JULY

July

SQL> SELECT TO_CHAR(SYSDATE,'YY RR YYYY RRRR YEAR, Year') FROM DUAL;

08 08 2008 2008 TWO THOUSAND EIGHT, Two Thousand Eight SQL> SELECT ENAME, HIREDATE, TO_CHAR(HIREDATE,'Day, Month dd, rrrr') HIREDATE FROM EMP; ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

HIREDATE --------17-DEC-80 20-FEB-81 22-FEB-81 02-APR-81 28-SEP-81 01-MAY-81 09-JUN-81 19-APR-87 17-NOV-81 08-SEP-81 23-MAY-87 03-DEC-81 03-DEC-81 23-JAN-82

HIREDATE ----------------------------Wednesday, December 17, 1980 Friday , February 20, 1981 Sunday , February 22, 1981 Thursday , April 02, 1981 Monday , September 28, 1981 Friday , May 01, 1981 Tuesday , June 09, 1981 Sunday , April 19, 1987 Tuesday , November 17, 1981 Tuesday , September 08, 1981 Saturday , May 23, 1987 Thursday , December 03, 1981 Thursday , December 03, 1981 Saturday , January 23, 1982

SQL> SELECT ENAME, HIREDATE, TO_CHAR(HIREDATE,'fmDay, Month dd, rrrr') HIREDATE FROM EMP; ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

HIREDATE --------17-DEC-80 20-FEB-81 22-FEB-81 02-APR-81 28-SEP-81 01-MAY-81 09-JUN-81 19-APR-87 17-NOV-81 08-SEP-81 23-MAY-87 03-DEC-81 03-DEC-81 23-JAN-82

HIREDATE ----------------------------Wednesday, December 17, 1980 Friday, February 20, 1981 Sunday, February 22, 1981 Thursday, April 2, 1981 Monday, September 28, 1981 Friday, May 1, 1981 Tuesday, June 9, 1981 Sunday, April 19, 1987 Tuesday, November 17, 1981 Tuesday, September 8, 1981 Saturday, May 23, 1987 Thursday, December 3, 1981 Thursday, December 3, 1981 Saturday, January 23, 1982

SQL> SELECT TO_CHAR(SYSDATE,'DdTH "of" Month RRRR') FROM DUAL;

24th of July

2008 57

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Using the TO_CHAR Function with Numbers SQL> 2 3 4 5 6

SELECT TO_CHAR(58,'99.9') A, TO_CHAR(58,'00.0') B, TO_CHAR(58,'$99.9') C, TO_CHAR(58,'$00.0') D FROM DUAL;

A B C D ----- ----- ------ -----58.0 58.0 $58.0 $58.0

SQL> 2 3 4 5 6

SELECT TO_CHAR(58,'999.99') A, TO_CHAR(58,'000.00') B, TO_CHAR(58,'$999.99') C, TO_CHAR(58,'$000.00') D FROM DUAL;

A B C D ------- ------- -------- -------58.00 058.00 $58.00 $058.00

SQL> 2 3 4 5 6

SELECT TO_CHAR(58,'99,999.99') A, TO_CHAR(58,'00,000.00') B, TO_CHAR(58,'$99,999.99') C, TO_CHAR(58,'$00,000.00') D FROM DUAL;

A B C D ---------- ---------- ----------- ----------58.00 00,058.00 $58.00 $00,058.00

SQL> 2 3 4 5 6

SELECT TO_CHAR(58755,'99,999.99') A, TO_CHAR(58755,'00,000.00') B, TO_CHAR(58755,'$99,999.99') C, TO_CHAR(58755,'$00,000.00') D FROM DUAL;

A B C D ---------- ---------- ----------- ----------58,755.00 58,755.00 $58,755.00 $58,755.00 SQL> 2 3 4 5 6

SELECT TO_CHAR(5858755,'99,999.99') A, TO_CHAR(5858755,'00,000.00') B, TO_CHAR(5858755,'$99,999.99') C, TO_CHAR(5858755,'$00,000.00') D FROM DUAL;

A B C D ---------- ---------- ----------- ----------########## ########## ########### ########### 58

[email protected]

Prepared by Muhammad Raheem

Oracle SQL SQL> 2 3 4 5 6 7

Phone: 021-4265550, Cell: 0321-4265550

SELECT EMPNO, ENAME, HIREDATE, TO_CHAR(HIREDATE,'DD DDSP') "DATE", TO_CHAR(HIREDATE,'MON-RRRR') MON_YEAR, TO_CHAR(HIREDATE,'RRRR') YEAR, TO_CHAR(SAL,'99,999.99') SALARY FROM EMP;

EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

HIREDATE --------17-DEC-80 20-FEB-81 22-FEB-81 02-APR-81 28-SEP-81 01-MAY-81 09-JUN-81 19-APR-87 17-NOV-81 08-SEP-81 23-MAY-87 03-DEC-81 03-DEC-81 23-JAN-82

DATE -------------------17 SEVENTEEN 20 TWENTY 22 TWENTY-TWO 02 TWO 28 TWENTY-EIGHT 01 ONE 09 NINE 19 NINETEEN 17 SEVENTEEN 08 EIGHT 23 TWENTY-THREE 03 THREE 03 THREE 23 TWENTY-THREE

MON_YEAR -------DEC-1980 FEB-1981 FEB-1981 APR-1981 SEP-1981 MAY-1981 JUN-1981 APR-1987 NOV-1981 SEP-1981 MAY-1987 DEC-1981 DEC-1981 JAN-1982

YEAR SALARY ---- ---------1980 800.00 1981 1,600.00 1981 1,250.00 1981 2,975.00 1981 1,250.00 1981 2,850.00 1981 2,450.00 1987 3,000.00 1981 5,000.00 1981 1,500.00 1987 1,100.00 1981 950.00 1981 3,000.00 1982 1,300.00

14 rows selected. SQL> 2 3 4 5 6 7 8

SELECT ENAME, HIREDATE, TO_CHAR(HIREDATE,'Day') HIRE_DAY, NEXT_DAY(HIREDATE,'SUNDAY') SUNDAY, TO_CHAR(NEXT_DAY(HIREDATE,'SUNDAY'),'DD') SUNDAY, TO_CHAR(LAST_DAY(HIREDATE),'Day') LAST_DAY, TO_CHAR(ADD_MONTHS(HIREDATE,1),'Day') AFTER_2_MONTHS, TO_CHAR(SAL,'09,999.99') SALARY FROM EMP;

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

HIREDATE --------17-DEC-80 20-FEB-81 22-FEB-81 02-APR-81 28-SEP-81 01-MAY-81 09-JUN-81 19-APR-87 17-NOV-81 08-SEP-81 23-MAY-87 03-DEC-81 03-DEC-81 23-JAN-82

HIRE_DAY --------Wednesday Friday Sunday Thursday Monday Friday Tuesday Sunday Tuesday Tuesday Saturday Thursday Thursday Saturday

SUNDAY --------21-DEC-80 22-FEB-81 01-MAR-81 05-APR-81 04-OCT-81 03-MAY-81 14-JUN-81 26-APR-87 22-NOV-81 13-SEP-81 24-MAY-87 06-DEC-81 06-DEC-81 24-JAN-82

SU -21 22 01 05 04 03 14 26 22 13 24 06 06 24

LAST_DAY --------Wednesday Saturday Saturday Thursday Wednesday Sunday Tuesday Thursday Monday Wednesday Sunday Thursday Thursday Sunday

AFTER_2_M SALARY --------- ---------Saturday 00,800.00 Friday 01,600.00 Sunday 01,250.00 Saturday 02,975.00 Wednesday 01,250.00 Monday 02,850.00 Thursday 02,450.00 Tuesday 03,000.00 Thursday 05,000.00 Thursday 01,500.00 Tuesday 01,100.00 Sunday 00,950.00 Sunday 03,000.00 Tuesday 01,300.00

Assignment 1. Find all employees who were hired on Friday or Sunday. 2. Find all employees who were hired in FEB 3. Find all employees who were hired in 1981 59

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

TO_NUMBER ( ) SQL> SELECT 4+3 FROM DUAL; 4+3 --------7 SQL> SELECT '4'+'3' FROM DUAL; '4'+'3' --------7

SQL> SELECT TO_NUMBER('4')+TO_NUMBER('3') FROM DUAL; TO_NUMBER('4')+TO_NUMBER('3') ----------------------------7 SQL> 2 3 4 5 6

SELECT SUBSTR('SECTOR 5',-1,1), SUBSTR('SECTOR 6',-1,1), TO_NUMBER(SUBSTR('SECTOR 5',-1,1)), TO_NUMBER(SUBSTR('SECTOR 6',-1,1)) FROM DUAL;

S S TO_NUMBER(SUBSTR('SECTOR5',-1,1)) TO_NUMBER(SUBSTR('SECTOR6',-1,1)) - - --------------------------------- --------------------------------5 6 5 6

SQL> SELECT SUBSTR('HOUSE # 5, SEC 11, KARACHI',9,1)*10 FROM DUAL; SUBSTR('HOUSE#5,SEC11,KARACHI',9,1)*10 -------------------------------------50

TO_DATE ( ) SQL> SELECT '14-AUG-1947' A FROM DUAL; 14-AUG-1947

SQL> SELECT TO_DATE('14-AUG-1947') A FROM DUAL; 14-AUG-47

SQL> SELECT NEXT_DAY('14-AUG-1947','SUNDAY') A FROM DUAL; 17-AUG-47

SQL> SELECT NEXT_DAY(TO_DATE('14-AUG-1947'),'SUNDAY') A FROM DUAL; 17-AUG-47 60

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT TO_CHAR('14-AUG-1947','RRRR') A FROM DUAL; SELECT TO_CHAR('14-AUG-1947','RRRR') FROM DUAL * ERROR at line 1: ORA-01722: invalid number SQL> 2 3 4 5

SELECT TO_CHAR(SYSDATE,'RRRR') TO_CHAR(TO_DATE('14-AUG-1947'),'RRRR') TOT_YEARS FROM DUAL;

TOT_YEARS --------61 SQL> 2 3 4 5

SELECT TO_NUMBER(TO_CHAR(SYSDATE,'RRRR')) TO_NUMBER(TO_CHAR(TO_DATE('14-AUG-1947'),'RRRR')) TOT_YEARS FROM DUAL;

TOT_YEARS --------61 SQL> SELECT TO_DATE('14-AUG-1947') A FROM DUAL; 14-AUG-47

SQL> SELECT TO_DATE('14-AUG-1947','DD-MON-RRRR') A FROM DUAL; 14-AUG-47

SQL> SELECT TO_DATE('AUGUST 14, 1947','MONTH DD, RRRR') A FROM DUAL; 14-AUG-47

SQL> 2 3 4 5 6 7 8 9 10

SELECT TO_DATE('AUGUST 14, 1947','MONTH DD, RRRR') A, TO_DATE('AUGUST 14, 1947','MON DD, RRRR') B, TO_DATE('AUG 14, 1947','Mon DD, RRRR') C, TO_DATE('14 AUG 1947','DD MONTH RRRR') D, TO_DATE('AUG 1947','MONTH RRRR') E, TO_DATE('1947','RRRR') F, TO_DATE('AUG','MON') G, TO_DATE('14','DD') H FROM DUAL;

A B C D E F G H --------- --------- --------- --------- --------- --------- --------- --------14-AUG-47 14-AUG-47 14-AUG-47 14-AUG-47 01-AUG-47 01-JUL-47 01-AUG-08 14-JUL-08 SQL> SELECT * FROM EMP WHERE HIREDATE=TO_DATE('17/12/1980','DD/MM/RRRR'); EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO --------- ---------- --------- --------- --------- --------- --------- --------7369 SMITH CLERK 7902 17-DEC-80 800 20 61

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Nesting Functions Single-row functions can be nested to any depth. Nested functions are evaluated from the innermost level to the outermost level.

F3(F2(F1(col,arg1),arg2),arg3) TO_NUMBER(TO_CHAR(TO_DATE('14-AUG-1947'),'RRRR')) NVL function Converts a null to an actual value. • Data types that can be used are date, character, and number. • Data types must match: – NVL(commission_pct,0) – NVL(hire_date,'01-JAN-97') – NVL(job_id,'No Job Yet') SQL> SELECT EMPNO, ENAME, JOB, SAL, COMM, NVL(COMM,0), SAL+NVL(COMM,0) FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

JOB SAL COMM NVL(COMM,0) SAL+NVL(COMM,0) --------- --------- --------- ----------- --------------CLERK 800 0 800 SALESMAN 1600 300 300 1900 SALESMAN 1250 500 500 1750 MANAGER 2975 0 2975 SALESMAN 1250 1400 1400 2650 MANAGER 2850 0 2850 MANAGER 2450 0 2450 ANALYST 3000 0 3000 PRESIDENT 5000 0 5000 SALESMAN 1500 0 0 1500 CLERK 1100 0 1100 CLERK 950 0 950 ANALYST 3000 0 3000 CLERK 1300 0 1300

14 rows selected. SQL> SELECT ENAME, COMM, NVL(COMM,0), NVL(TO_CHAR(COMM),'NO COMMISSION') FROM EMP;

ENAME COMM NVL(COMM,0) NVL(TO_CHAR(COMM),'NOCOMMISSION') ---------- --------- ----------- ---------------------------------------SMITH 0 NO COMMISSION ALLEN 300 300 300 WARD 500 500 500 JONES 0 NO COMMISSION MARTIN 1400 1400 1400 BLAKE 0 NO COMMISSION CLARK 0 NO COMMISSION SCOTT 0 NO COMMISSION KING 0 NO COMMISSION TURNER 0 0 0 ADAMS 0 NO COMMISSION JAMES 0 NO COMMISSION FORD 0 NO COMMISSION MILLER 0 NO COMMISSION 62

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

COALESCE Function SQL> SELECT EMPNO, ENAME, JOB, COMM, SAL, COALESCE(COMM,SAL,100) SALARY FROM EMP;

EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

JOB COMM SAL SALARY --------- --------- --------- --------CLERK 800 800 SALESMAN 300 1600 300 SALESMAN 500 1250 500 MANAGER 2975 2975 SALESMAN 1400 1250 1400 MANAGER 2850 2850 MANAGER 2450 2450 ANALYST 3000 3000 PRESIDENT 5000 5000 SALESMAN 0 1500 0 CLERK 1100 1100 CLERK 950 950 ANALYST 3000 3000 CLERK 1300 1300

14 rows selected. SQL> SELECT ENAME, COMM, NVL(COMM,0), COALESCE(COMM,0), COALESCE(COMM,SAL,0) FROM EMP; ENAME COMM NVL(COMM,0) COALESCE(COMM,0) COALESCE(COMM,SAL,0) ---------- --------- ----------- ---------------- -------------------SMITH 0 0 800 ALLEN 300 300 300 300 WARD 500 500 500 500 JONES 0 0 2975 MARTIN 1400 1400 1400 1400 BLAKE 0 0 2850 CLARK 0 0 2450 SCOTT 0 0 3000 KING 0 0 5000 TURNER 0 0 0 0 ADAMS 0 0 1100 JAMES 0 0 950 FORD 0 0 3000 MILLER 0 0 1300

SELECT EMPNO, COALESCE(PHONE_NO, CELL_NO, EMAIL, ADDRESS) CONTACT FROM EMP; SELECT EMPNO, COALESCE(NEW_NIC, OLD_NIC,

63

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Conditional Expressions Facilitates conditional inquiries by doing the work of a CASE or IF-THEN-ELSE statement: SQL> SELECT EMPNO, ENAME, DEPTNO, 2 DECODE(DEPTNO,10,'ACCOUNTS',20,'RESEARCH',30,'SALES','INVALID') DNAME 3 FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME DEPTNO DNAME ---------- --------- -------SMITH 20 RESEARCH ALLEN 30 SALES WARD 30 SALES JONES 20 RESEARCH MARTIN 30 SALES BLAKE 30 SALES CLARK 10 ACCOUNTS SCOTT 20 RESEARCH KING 10 ACCOUNTS TURNER 30 SALES ADAMS 20 RESEARCH JAMES 30 SALES FORD 20 RESEARCH MILLER 10 ACCOUNTS

Management has decided to revise salary according to the following: PRESIDENT SALESMAN

15% 8%

MANAGER OTHER

12% 6%

ANALYST

10%

The result of the following three queries is same: SELECT EMPNO, ENAME, JOB, SAL, DECODE(JOB,'PRESIDENT',SAL+SAL*15/100,'MANAGER',SAL+SAL*12/100, 'ANALYST',SAL+SAL*10/100,'SALESMAN',SAL+SAL*8/100,SAL+SAL*6/100) "INCREMENT" FROM EMP; SELECT EMPNO, ENAME, JOB, SAL, DECODE(JOB,'PRESIDENT',SAL+SAL*.15,'MANAGER',SAL+SAL*.12, 'ANALYST',SAL+SAL*.1,'SALESMAN',SAL+SAL*.08,SAL+SAL*.06) "INCREMENT" FROM EMP; SQL> SELECT EMPNO, ENAME, JOB, SAL, 2 DECODE(JOB,'PRESIDENT',SAL*1.15,'MANAGER',SAL*1.12, 3 'ANALYST',SAL*1.1,'SALESMAN',SAL*1.08,SAL*1.06) "INCREMENT" 4 FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

JOB SAL INCREMENT --------- --------- --------CLERK 800 848 SALESMAN 1600 1728 SALESMAN 1250 1350 MANAGER 2975 3332 SALESMAN 1250 1350 MANAGER 2850 3192 MANAGER 2450 2744 ANALYST 3000 3300 PRESIDENT 5000 5750 SALESMAN 1500 1620 CLERK 1100 1166 CLERK 950 1007 ANALYST 3000 3300 CLERK 1300 1378 64

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Tables in the Oracle Database (Part 1) •

User Tables: – Are a collection of tables created and maintained by the user – Contain user information



Data Dictionary: – Is a collection of tables created and maintained by the Oracle Server – Contain database information

Creating a table Create tables to store data by using CREATE TABLE statement. Create Table is a DDL Statement.

Create a table to store student information. SQL> 2 3 4 5 6 7 8

CREATE TABLE STUDENT ( RNO NUMBER(4) PRIMARY KEY, NAME VARCHAR2(20) NOT NULL, DOB DATE, NIC NUMBER(13) UNIQUE, GENDER CHAR(1) );

Table created.

Create a table to store class information. SQL> 2 3 4 5

CREATE TABLE CLASS ( CID NUMBER(2) PRIMARY KEY, CDESC VARCHAR2(20) );

Table created.

Create a table to store marks information. SQL> 2 3 4 5 6

CREATE ( RNO CID PER );

TABLE STD_MARKS NUMBER(4) REFERENCES STUDENT (RNO), NUMBER(2) REFERENCES CLASS (CID), NUMBER(5,2)

Table created.

Create a table to store grade criteria. SQL> CREATE TABLE STD_GRADE 2 (GRADE VARCHAR2(2), 3 MIN_PER NUMBER(5,2), 4 MAX_PER NUMBER(5,2) 5 ); Table created. 65

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

How to verify table creation? By a data dictionary view Æ USER_TABLES

or

(TABS)

SQL> SELECT TABLE_NAME FROM USER_TABLES; TABLE_NAME -----------------------------DEPT EMP BONUS SALGRADE STD_GRADE STD_MARKS CLASS STUDENT 8 rows selected.

By a data dictionary view Æ USER_OBJECTS

or

(OBJ)

SQL> SELECT OBJECT_NAME FROM USER_OBJECTS WHERE OBJECT_TYPE='TABLE'; OBJECT_NAME --------------------------------------------------------------------DEPT EMP BONUS SALGRADE STD_GRADE STD_MARKS CLASS STUDENT 8 rows selected.

By a data dictionary view Æ USER_CATALOG

or

(CAT)

SQL> SELECT * FROM USER_CATALOG WHERE TABLE_TYPE='TABLE'; TABLE_NAME -----------------------------DEPT EMP BONUS SALGRADE STD_GRADE STD_MARKS CLASS STUDENT

TABLE_TYPE ----------TABLE TABLE TABLE TABLE TABLE TABLE TABLE TABLE

8 rows selected.

66

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

By a data dictionary view Æ TAB

or

(TAB)

SQL> SELECT * FROM TAB WHERE TABTYPE='TABLE'; TNAME -----------------------------DEPT EMP BONUS SALGRADE STD_GRADE STD_MARKS CLASS STUDENT

TABTYPE CLUSTERID ------- --------TABLE TABLE TABLE TABLE TABLE TABLE TABLE TABLE

8 rows selected.

By DESC / DESCRIBE Command SQL> DESC STUDENT Name ------------------------------RNO NAME DOB NIC GENDER

Null? -------NOT NULL NOT NULL

Type ---NUMBER(4) VARCHAR2(20) DATE NUMBER(13) CHAR(1)

SQL> DESC CLASS Name Null? ------------------------------- -------CID NOT NULL CDESC

Type ---NUMBER(2) VARCHAR2(20)

SQL> DESC STD_MARKS Name Null? ------------------------------- -------RNO CID PER

Type ---NUMBER(4) NUMBER(2) NUMBER(5,2)

SQL> DESC STD_GRADE Name Null? ------------------------------- -------GRADE MIN_PER MAX_PER

Type ---VARCHAR2(2) NUMBER(5,2) NUMBER(5,2)

SQL>

By SELECT Statement SQL> SELECT * FROM STUDENT; no rows selected SQL>

67

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Insertion in a Table (Part 1) You can add new rows to a table by using the INSERT statement. SQL> 2 3 4

There is a Column List before VALUES keyword. INSERT INTO STUDENT (RNO, NAME, DOB, NIC, GENDER) VALUES (1,'MUHAMMAD ASLAM','23-JAN-1986',1452412345671,'M');

1 row created.

• •

Insert a new row containing values for each column. Optionally, list the columns in the INSERT clause.

SQL> 2 3 4

INSERT INTO STUDENT (RNO, NAME, DOB, NIC, GENDER) VALUES (2,'SAMINA KHAN','31-MAR-1987',4567712345645,'F');

1 row created.

There is not any Column List before VALUES keyword.

SQL> INSERT INTO STUDENT 2 VALUES 3 (3,'AAMIR','25-FEB-1982',1234567891231,'M'); If you do not use the column list, the values must be listed according to the default order of the columns in the table, and a value must be provided for each column. SQL> DESC STUDENT Name ------------------------------RNO NAME DOB NIC GENDER

SQL> 2 3 4

Null? -------NOT NULL NOT NULL

Type ---NUMBER(4) VARCHAR2(20) DATE NUMBER(13) CHAR(1)

INSERT INTO STUDENT (RNO, NAME, DOB, NIC, GENDER) VALUES (4,'RAJ KUMAR','25-APR-1997',NULL,'M');

In this example NULL value is moved in NIC column by using NULL keyword for NIC column. SQL> 2 3 4

INSERT INTO STUDENT (RNO, NAME, DOB, GENDER) VALUES (5,'ZOBIA KHAN','12-AUG-1997','F');

In this example NULL value is moved in NIC column by excluding NIC column from column list. 68

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

INSERT INSERT INSERT INSERT INSERT

INTO INTO INTO INTO INTO

CLASS CLASS CLASS CLASS CLASS

VALUES VALUES VALUES VALUES VALUES

(1,'CLASS (2,'CLASS (3,'CLASS (4,'CLASS (5,'CLASS

ONE'); TWO'); THREE'); FOUR'); FIVE');

INSERT INSERT INSERT INSERT

INTO INTO INTO INTO

STD_MARKS STD_MARKS STD_MARKS STD_MARKS

VALUES VALUES VALUES VALUES

(1, (2, (3, (4,

INSERT INSERT INSERT INSERT INSERT INSERT

INTO INTO INTO INTO INTO INTO

STD_GRADE STD_GRADE STD_GRADE STD_GRADE STD_GRADE STD_GRADE

VALUES VALUES VALUES VALUES VALUES VALUES

('A1',90,100); ('A',80,89.99); ('B',70,79.99); ('C',60,69.99); ('D',50,59.99); ('F',0,49.99);

1, 1, 1, 1,

75.32); 61.16); 48.95); 89.91);

SQL> SELECT * FROM STUDENT; RNO ------------1 2 3 4 5 SQL>

NAME -------------------MUHAMMAD ASLAM SAMINA KHAN AAMIR RAJ KUMAR ZOBIA KHAN

DOB --------23-JAN-86 31-MAR-87 25-FEB-82 25-APR-97 12-AUG-97

NIC ------------1452412345671 4567712345645 1234567891231

G M F M M F

SELECT * FROM CLASS;

CID ---------1 2 3 4 5

CDESC -------------------CLASS ONE CLASS TWO CLASS THREE CLASS FOUR CLASS FIVE

SQL> SELECT * FROM STD_MARKS; RNO CID PER ---------- ---------- ---------1 1 75.32 2 1 61.16 3 1 48.95 4 1 89.91 SQL> SELECT * FROM STD_GRADE; GR MIN_PER MAX_PER -- ---------- ---------A1 90 100 A 80 89.99 B 70 79.99 C 60 69.99 D 50 59.99 F 0 49.99 6 rows selected. 69

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Chapter 4

Displaying Data from Multiple Tables Data from Multiple Tables Sometimes you need to use data from more than one table. • EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM exist in the EMP table. • DEPTNO exist in both the EMP and DEPT tables. • DNAME & LOC exist in the DEPT table. To produce the result, you need to link the EMP and DEPT tables and access data from both of them.

EMP TABLE EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 MANAGER 7839 02-APR-81 2975 20 SALESMAN 7698 28-SEP-81 1250 1400 30 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 SALESMAN 7698 08-SEP-81 1500 0 30 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 ANALYST 7566 03-DEC-81 3000 20 CLERK 7782 23-JAN-82 1300 10

DEPT TABLE DEPTNO --------10 20 30 40

DNAME -------------ACCOUNTING RESEARCH SALES OPERATIONS

LOC ------------NEW YORK DALLAS CHICAGO BOSTON

Data retrieved from both tables (EMP & DEPT tables) EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

JOB SAL DEPTNO DNAME --------- --------- --------- -------------CLERK 800 20 RESEARCH SALESMAN 1600 30 SALES SALESMAN 1250 30 SALES MANAGER 2975 20 RESEARCH SALESMAN 1250 30 SALES MANAGER 2850 30 SALES MANAGER 2450 10 ACCOUNTING ANALYST 3000 20 RESEARCH PRESIDENT 5000 10 ACCOUNTING SALESMAN 1500 30 SALES CLERK 1100 20 RESEARCH CLERK 950 30 SALES ANALYST 3000 20 RESEARCH CLERK 1300 10 ACCOUNTING 70

LOC ------------DALLAS CHICAGO CHICAGO DALLAS CHICAGO CHICAGO NEW YORK DALLAS NEW YORK CHICAGO DALLAS CHICAGO DALLAS NEW YORK [email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Types of Joins Oracle Proprietary Joins (8i and prior): • • • •

Equijoin Non-equijoin Outer join Self join

Defining Joins When data from more than one table in the database is required, a join condition is used. Rows in one table can be joined to rows in another table according to common values existing in corresponding columns, that is, usually primary and foreign key columns. To display data from two or more related tables, write a simple join condition in the WHERE clause. In the syntax: table1.column denotes the table and column from which data is retrieved table1.column1 = is the condition that joins (or relates) the tables together table2.column2 Guidelines • • •

When writing a SELECT statement that joins tables, precede the column name with the table name for clarity and to enhance database access. If the same column name appears in more than one table, the column name must be prefixed with the table name. To join n tables together, you need a minimum of n-1 join conditions. For example, to join four tables, a minimum of three joins is required. This rule may not apply if your table has a concatenated primary key, in which case more than one column is required to uniquely identify each row.

Equijoin To determine an employee’s department name, you compare the value in the DEPTNO column in the EMP table with the DEPTNO values in the DEPT table. The relationship between the EMP and DEPT tables is an equijoin—that is, values in the DEPTNO column on both tables must be equal. Frequently, this type of join involves primary and foreign key complements. Note: Equijoins are also called simple joins or inner joins. EMP TABLE

DEPT TABLE

EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 .... ....

DEPTNO --------10 20 30 40

ENAME DEPTNO ---------- --------SMITH 20 ALLEN 30 WARD 30 JONES 20 MARTIN 30 BLAKE 30 CLARK 10 SCOTT 20 ...... .. ...... .. 71

DNAME -----------ACCOUNTING RESEARCH SALES OPERATIONS

LOC ---------NEW YORK DALLAS CHICAGO BOSTON

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Insert a record in EMP table by using the following query: SQL> 2 3 4

INSERT INTO EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO) VALUES (1,'ASLAM','CLERK',7566,SYSDATE,1200,NULL,NULL);

1 row created. SQL> COMMIT; Commit complete. SQL> SELECT * FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934 1

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER ASLAM

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 MANAGER 7839 02-APR-81 2975 20 SALESMAN 7698 28-SEP-81 1250 1400 30 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 SALESMAN 7698 08-SEP-81 1500 0 30 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 ANALYST 7566 03-DEC-81 3000 20 CLERK 7782 23-JAN-82 1300 10 CLERK 7566 26-JUL-08 1200

15 rows selected. The above select statement retrieves 15 rows. Employee ASLAM does not belong to any department, because there is a NULL value in DEPTNO column of ASLAM’s record.

SQL> SELECT * FROM DEPT; DEPTNO --------10 20 30 40

DNAME -------------ACCOUNTING RESEARCH SALES OPERATIONS

LOC ------------NEW YORK DALLAS CHICAGO BOSTON

The above select statement retrieves 4 rows. There is a DEPTNO 40, while there is not any employee in EMP table who belong to department 40.

72

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Retrieving Records with Equijoins Display all employees with their department names and location. Employee information is stored in EMP table Department information is stored in DEPT table There is a column DEPTNO which exists in both tables Match the value in DEPTNO of EMP table with DEPTNO of DEPT table. SQL> SELECT EMPNO, ENAME, JOB, SAL, EMP.DEPTNO, DNAME, LOC 2 FROM EMP, DEPT 3 WHERE EMP.DEPTNO=DEPT.DEPTNO; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

JOB SAL DEPTNO DNAME --------- --------- --------- -------------CLERK 800 20 RESEARCH SALESMAN 1600 30 SALES SALESMAN 1250 30 SALES MANAGER 2975 20 RESEARCH SALESMAN 1250 30 SALES MANAGER 2850 30 SALES MANAGER 2450 10 ACCOUNTING ANALYST 3000 20 RESEARCH PRESIDENT 5000 10 ACCOUNTING SALESMAN 1500 30 SALES CLERK 1100 20 RESEARCH CLERK 950 30 SALES ANALYST 3000 20 RESEARCH CLERK 1300 10 ACCOUNTING

LOC ------------DALLAS CHICAGO CHICAGO DALLAS CHICAGO CHICAGO NEW YORK DALLAS NEW YORK CHICAGO DALLAS CHICAGO DALLAS NEW YORK

14 rows selected. The query retrieve 14 rows, ASLAM’s record did not retrieved. Why? In the example: • The SELECT clause specifies the column names to retrieve: • employee number, name, job, salary, and department number, which are columns in the EMP table • department name, and location, which are columns in the DEPT table • The FROM clause specifies the two tables that the database must access: • EMP table • DEPT table • The WHERE clause specifies how the tables are to be joined: EMP.DEPTNO = DEPT.DEPTNO Because the DEPTNO column is common to both tables, it must be prefixed by the table name to avoid ambiguity or Use table prefixes to qualify column names that are in multiple tables.

Improve performance by using table prefixes SELECT EMP.EMPNO, EMP.ENAME, EMP.JOB, EMP.SAL, EMP.DEPTNO, DEPT.DNAME, DEPT.LOC FROM EMP, DEPT WHERE EMP.DEPTNO=DEPT.DEPTNO;

Using Table Alias SELECT E.EMPNO, E.ENAME, E.JOB, E.SAL, E.DEPTNO, D.DNAME, D.LOC FROM EMP E, DEPT D WHERE E.DEPTNO=D.DEPTNO; 73

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Additional Search Conditions SQL> 2 3 4

SELECT EMPNO, ENAME, JOB, SAL, E.DEPTNO, DNAME, LOC FROM EMP E, DEPT D WHERE E.DEPTNO=D.DEPTNO AND SAL>2000;

EMPNO --------7566 7698 7782 7788 7839 7902

ENAME ---------JONES BLAKE CLARK SCOTT KING FORD

JOB SAL DEPTNO DNAME --------- --------- --------- -------------MANAGER 2975 20 RESEARCH MANAGER 2850 30 SALES MANAGER 2450 10 ACCOUNTING ANALYST 3000 20 RESEARCH PRESIDENT 5000 10 ACCOUNTING ANALYST 3000 20 RESEARCH

LOC ------------DALLAS CHICAGO NEW YORK DALLAS NEW YORK DALLAS

6 rows selected.

SQL> 2 3 4

SELECT EMPNO, ENAME, JOB, SAL, E.DEPTNO, DNAME, LOC FROM EMP E, DEPT D WHERE E.DEPTNO=D.DEPTNO AND DNAME='SALES';

OR SQL> 2 3 4

SELECT EMPNO, ENAME, JOB, SAL, E.DEPTNO, DNAME, LOC FROM EMP E, DEPT D WHERE E.DEPTNO=D.DEPTNO AND E.DEPTNO=30;

EMPNO --------7499 7521 7654 7698 7844 7900

ENAME ---------ALLEN WARD MARTIN BLAKE TURNER JAMES

JOB SAL DEPTNO DNAME --------- --------- --------- -------------SALESMAN 1600 30 SALES SALESMAN 1250 30 SALES SALESMAN 1250 30 SALES MANAGER 2850 30 SALES SALESMAN 1500 30 SALES CLERK 950 30 SALES

LOC ------------CHICAGO CHICAGO CHICAGO CHICAGO CHICAGO CHICAGO

6 rows selected.

Is there any difference in the following two queries? SELECT EMPNO, ENAME, JOB, SAL, E.DEPTNO, DNAME, LOC FROM EMP E, DEPT D WHERE E.DEPTNO=D.DEPTNO AND SAL>2000; SELECT EMPNO, ENAME, JOB, SAL, E.DEPTNO, DNAME, LOC FROM EMP E, DEPT D WHERE SAL>2000 AND E.DEPTNO=D.DEPTNO;

Cartesian / Cross Products •



(rows of one table multiply with rows of another table)

A Cartesian product is formed when: – A join condition is omitted – A join condition is invalid – All rows in the first table are joined to all rows in the second table To avoid a Cartesian product, always include a valid join condition in a WHERE clause.

SELECT EMPNO, ENAME, JOB, SAL, E.DEPTNO, DNAME FROM EMP E, DEPT D 74

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Non-Equijoins A non-equijoin is a join condition containing something other than an equality operator. The relationship between the EMP table and the SALGRADE table has an example of a nonequijoin. A relationship between the two tables is that the SAL column in the EMPL table must be between the values in the LOSAL and HISAL columns of the SALGRADE table. The relationship is obtained using an operator other than equals (=). SQL> SELECT * FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 MANAGER 7839 02-APR-81 2975 20 SALESMAN 7698 28-SEP-81 1250 1400 30 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 SALESMAN 7698 08-SEP-81 1500 0 30 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 ANALYST 7566 03-DEC-81 3000 20 CLERK 7782 23-JAN-82 1300 10

14 rows selected. SQL> SELECT * FROM SALGRADE; GRADE LOSAL HISAL --------- --------- --------1 700 1200 2 1201 1400 3 1401 2000 4 2001 3000 5 3001 9999 SQL> SELECT E.EMPNO, E.ENAME, E.JOB, E.SAL, G.GRADE 2 FROM EMP E, SALGRADE G 3 WHERE E.SAL BETWEEN G.LOSAL AND G.HISAL; EMPNO --------7369 7900 7876 7521 7654 7934 7844 7499 7782 7698 7566 7788 7902 7839

ENAME ---------SMITH JAMES ADAMS WARD MARTIN MILLER TURNER ALLEN CLARK BLAKE JONES SCOTT FORD KING

JOB SAL GRADE --------- --------- --------CLERK 800 1 CLERK 950 1 CLERK 1100 1 SALESMAN 1250 2 SALESMAN 1250 2 CLERK 1300 2 SALESMAN 1500 3 SALESMAN 1600 3 MANAGER 2450 4 MANAGER 2850 4 MANAGER 2975 4 ANALYST 3000 4 ANALYST 3000 4 PRESIDENT 5000 5

14 rows selected. 75

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Non-Equijoins (continued) The example creates a non-equijoin to evaluate an employee’s salary grade. The salary must be between any pair of the low and high salary ranges. It is important to note that all employees appear exactly once when this query is executed. No employee is repeated in the list. There are two reasons for this: • None of the rows in the job grade table contain grades that overlap. That is, the salary value for an employee can lie only between the low salary and high salary values of one of the rows in the salary grade table. • All of the employees’ salaries lie within the limits provided by the salgrade table. That is, no employee earns less than the lowest value contained in the LOSAL column or more than the highest value contained in the HISAL column. Note: Other conditions, such as = can be used, but BETWEEN is the simplest. Remember to specify the low value first and the high value last when using BETWEEN. Table aliases have been specified in the slide example for performance reasons, not because of possible ambiguity. More examples of Non-Equijoins SQL> SELECT * FROM STD_MARKS; RNO CID PER ---------- ---------- ---------1 1 75.32 2 1 61.16 3 1 48.95 4 1 89.91 SQL> SELECT * FROM STD_GRADE; GR MIN_PER MAX_PER -- ---------- ---------A1 90 100 A 80 89.99 B 70 79.99 C 60 69.99 D 50 59.99 F 0 49.99 6 rows selected. SQL> 2 3 4

SELECT RNO, PER, GRADE FROM STD_MARKS, STD_GRADE WHERE PER BETWEEN MIN_PER AND MAX_PER ORDER BY 1;

RNO PER GR ---------- ---------- -1 75.32 B 2 61.16 C 3 48.95 F 4 89.91 A SQL>

76

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Outer Joins Returning Records with No Direct Match with Outer Joins If a row does not satisfy a join condition, the row will not appear in the query result. For example, in the equijoin condition of EMP and DEPT tables, employee ASLAM does not appear because there is no department number recorded for his in the EMP table. Instead of seeing 15 employees in the result set, you see 14 records. SQL> SELECT * FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934 1

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER ASLAM

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 MANAGER 7839 02-APR-81 2975 20 SALESMAN 7698 28-SEP-81 1250 1400 30 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 SALESMAN 7698 08-SEP-81 1500 0 30 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 ANALYST 7566 03-DEC-81 3000 20 CLERK 7782 23-JAN-82 1300 10 CLERK 7566 26-JUL-08 1200

15 rows selected. DEPTNO is missing

SQL> SELECT * FROM DEPT; DEPTNO --------10 20 30 40

DNAME -------------ACCOUNTING RESEARCH SALES OPERATIONS

LOC ------------NEW YORK DALLAS CHICAGO BOSTON

No Employee is working in DEPTNO 40

SQL> SELECT EMPNO, ENAME, JOB, SAL, EMP.DEPTNO, DNAME, LOC 2 FROM EMP, DEPT 3 WHERE EMP.DEPTNO=DEPT.DEPTNO; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

JOB SAL DEPTNO DNAME --------- --------- --------- -------------CLERK 800 20 RESEARCH SALESMAN 1600 30 SALES SALESMAN 1250 30 SALES MANAGER 2975 20 RESEARCH SALESMAN 1250 30 SALES MANAGER 2850 30 SALES MANAGER 2450 10 ACCOUNTING ANALYST 3000 20 RESEARCH PRESIDENT 5000 10 ACCOUNTING SALESMAN 1500 30 SALES CLERK 1100 20 RESEARCH CLERK 950 30 SALES ANALYST 3000 20 RESEARCH CLERK 1300 10 ACCOUNTING

LOC ------------DALLAS CHICAGO CHICAGO DALLAS CHICAGO CHICAGO NEW YORK DALLAS NEW YORK CHICAGO DALLAS CHICAGO DALLAS NEW YORK

14 rows selected. 77

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

When joining EMP and DEPT tables: ASLAM’s record is not displaying from EMP table Operations’s record is not displaying from DEPT table Aslam does not belong to any department because there is a null value in DEPTNO column. So when you join EMP and DEPT tables using equijoin, the values of DEPTNO column of EMP table matches with the values of DEPTNO column of DEPT table, and only those records will be displayed which values matches. There is an Opeations’s department, DEPTNO 40 in DEPT table, but No Employee is working in DEPTNO 40 in EMP table, so value is not matching. Only those records will by displayed using equijoin which values matches in both tables.

Why we use Outer Joins? We use outer join when mismatched values to be displayed. or Using Outer Joins to Return Records with No Direct Match The missing rows can be returned if an outer join operator is used in the join condition. The operator is a plus sign enclosed in parentheses (+), and it is placed on the “side” of the join that is deficient in information. This operator has the effect of creating one or more null rows, to which one or more rows from the nondeficient table can be joined. In the syntax: table1.column = is the condition that joins (or relates) the tables together. table2.column (+) is the outer join symbol, which can be placed on either side of the WHERE clause condition, but not on both sides. (Place the outer join symbol following the name of the column in the table without the matching rows.) SQL> SELECT EMPNO, ENAME, JOB, SAL, EMP.DEPTNO, DNAME, LOC 2 FROM EMP, DEPT 3 WHERE EMP.DEPTNO=DEPT.DEPTNO(+); EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934 1

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER ASLAM

JOB SAL DEPTNO DNAME --------- --------- --------- -------------CLERK 800 20 RESEARCH SALESMAN 1600 30 SALES SALESMAN 1250 30 SALES MANAGER 2975 20 RESEARCH SALESMAN 1250 30 SALES MANAGER 2850 30 SALES MANAGER 2450 10 ACCOUNTING ANALYST 3000 20 RESEARCH PRESIDENT 5000 10 ACCOUNTING SALESMAN 1500 30 SALES CLERK 1100 20 RESEARCH CLERK 950 30 SALES ANALYST 3000 20 RESEARCH CLERK 1300 10 ACCOUNTING CLERK 1200

LOC ------------DALLAS CHICAGO CHICAGO DALLAS CHICAGO CHICAGO NEW YORK DALLAS NEW YORK CHICAGO DALLAS CHICAGO DALLAS NEW YORK

15 rows selected. Placed (+) on the “side” of the join that is deficient (missing) in information. Aslam’s record exists in EMP table, but NULL DEPTNO does not exists in DEPT table, so put (+) on DEPT side because DEPT side is missing information. 78

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT EMPNO, ENAME, JOB, SAL, EMP.DEPTNO, DNAME, LOC 2 FROM EMP, DEPT 3 WHERE EMP.DEPTNO(+)=DEPT.DEPTNO; EMPNO --------7782 7934 7839 7566 7369 7788 7902 7876 7521 7844 7499 7900 7654 7698

ENAME ---------CLARK MILLER KING JONES SMITH SCOTT FORD ADAMS WARD TURNER ALLEN JAMES MARTIN BLAKE

JOB SAL DEPTNO DNAME --------- --------- --------- -------------MANAGER 2450 10 ACCOUNTING CLERK 1300 10 ACCOUNTING PRESIDENT 5000 10 ACCOUNTING MANAGER 2975 20 RESEARCH CLERK 800 20 RESEARCH ANALYST 3000 20 RESEARCH ANALYST 3000 20 RESEARCH CLERK 1100 20 RESEARCH SALESMAN 1250 30 SALES SALESMAN 1500 30 SALES SALESMAN 1600 30 SALES CLERK 950 30 SALES SALESMAN 1250 30 SALES MANAGER 2850 30 SALES OPERATIONS

LOC ------------NEW YORK NEW YORK NEW YORK DALLAS DALLAS DALLAS DALLAS DALLAS CHICAGO CHICAGO CHICAGO CHICAGO CHICAGO CHICAGO BOSTON

15 rows selected. Placed (+) on the “side” of the join that is deficient (missing) in information. Operations department DEPTNO 40 exists in DEPT table, but DEPTNO 40 is not assigned to any employee, so put (+) on EMP side because EMPT side is missing information.

Display all departments in which no employee was hired. SQL> 2 3 4

SELECT EMPNO, ENAME, JOB, SAL, EMP.DEPTNO, DNAME, LOC FROM EMP, DEPT WHERE EMP.DEPTNO(+)=DEPT.DEPTNO AND EMP.DEPTNO IS NULL;

EMPNO ENAME JOB SAL DEPTNO DNAME LOC --------- ---------- --------- --------- --------- -------------- ------------OPERATIONS BOSTON

Outer Join Restrictions •



The outer join operator can appear on only one side of the expression—the side that has information missing. It returns those rows from one table that have no direct match in the other table. A condition involving an outer join cannot use the IN operator or be linked to another condition by the OR operator.

79

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Self Joins Sometimes you need to join a table to itself. To find the name of each employee’s manager, you need to join the EMP table to itself, or perform a self join. For example, to find the name of ALLEN’s manager, you need to: • Find ALLEN in the EMP table by looking at ENAME column. • Find the manager number for ALLEN by looking at the MGR column. ALLEN’s manager number is 7698. • Find the name of the manager with MGR 7698 by looking at the ENAME column. BLAKE’s employee number is 7698, so BLAKE is ALLEN’s manager. In this process, you look in the table twice. The first time you look in the table to find ALLEN in the ENAME column and MGR value of 7698. The second time you look in EMPNO column to find 7698 and the ENAME column to find BLAKE. SQL> SELECT * FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934 1

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER ASLAM

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 MANAGER 7839 02-APR-81 2975 20 SALESMAN 7698 28-SEP-81 1250 1400 30 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 SALESMAN 7698 08-SEP-81 1500 0 30 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 ANALYST 7566 03-DEC-81 3000 20 CLERK 7782 23-JAN-82 1300 10 CLERK 7566 26-JUL-08 1200

15 rows selected. SQL> SELECT W.EMPNO, W.ENAME, M.EMPNO MGR, M.ENAME 2 FROM EMP W, EMP M 3 WHERE W.MGR=M.EMPNO; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7844 7876 7900 7902 7934 1

ENAME MGR ENAME ---------- --------- ---------SMITH 7902 FORD ALLEN 7698 BLAKE WARD 7698 BLAKE JONES 7839 KING MARTIN 7698 BLAKE BLAKE 7839 KING CLARK 7839 KING SCOTT 7566 JONES TURNER 7698 BLAKE ADAMS 7788 SCOTT JAMES 7698 BLAKE FORD 7566 JONES MILLER 7782 CLARK ASLAM 7566 JONES

14 rows selected. KING’s record did not display because KING’s MGR is null, which did not match with any EMPNO. 80

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

To display KING’s record, you have to use outer join condition, because KING’s MGR is null which, which did not match with any EMPNO. You have to put (+) on manager side because manager is missing but worker (KING) exists. In another words KING’s manager is missing and you have to put (+) on missing side. SQL> SELECT W.EMPNO, W.ENAME, M.EMPNO MGR, M.ENAME 2 FROM EMP W, EMP M 3 WHERE W.MGR=M.EMPNO(+); EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934 1

ENAME MGR ENAME ---------- --------- ---------SMITH 7902 FORD ALLEN 7698 BLAKE WARD 7698 BLAKE JONES 7839 KING MARTIN 7698 BLAKE BLAKE 7839 KING CLARK 7839 KING SCOTT 7566 JONES KING TURNER 7698 BLAKE ADAMS 7788 SCOTT JAMES 7698 BLAKE FORD 7566 JONES MILLER 7782 CLARK ASLAM 7566 JONES

15 rows selected. The example joins the EMP table to itself. To simulate two tables in the FROM clause, there are two aliases, namely w and m, for the same table, EMP. In this example, the WHERE clause contains the join that means “where a worker’s manager number matches the employee number for the manager.”

The DELETE clause The DELETE statement is used to remove row from table. How to remove ASLAM’S record? Aslam’s EMPNO is 1. SQL> DELETE EMP WHERE EMPNO=1; 1 row deleted.

The COMMIT statement The COMMIT statement is used to save data permanently into database. All DDL and DCL statements execute automatic commit. Commit is also executed automatically in some other cases that will be discussed later. After DML statements you have to use COMMIT statement for permanently saving. SQL> COMMIT; Commit complete. Note: CREATE TABLE, INSERT, DELETE and COMMIT will be discussed late in detail. 81

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Chapter 5

Aggregating Data Using Group Functions Group Functions Unlike single-row functions, group functions operate on sets of rows to give one result per group. These sets may be the whole table or the table split into groups. Types • • • • •

of Group Functions AVG COUNT MAX MIN SUM

Guidelines for Using Group Functions • DISTINCT makes the function consider only nonduplicate values; ALL makes it consider every value including duplicates. The default is ALL and therefore does not need to be specified. • The data types for the functions with an expr argument may be CHAR, VARCHAR2, NUMBER, or DATE. • All group functions ignore null values. To substitute a value for null values, use the NVL, NVL2, or COALESCE functions. • The Oracle server implicitly sorts the result set in ascending order when using a GROUP BY clause. To override this default ordering, DESC can be used in an ORDER BY clause. SQL> SELECT SUM(SAL) FROM EMP; SUM(SAL) --------29025 SQL> SELECT SUM(SAL) FROM EMP WHERE DEPTNO=10; SUM(SAL) --------8750 You can use AVG, SUM, MIN, and MAX functions against columns that can store numeric data. The example the sum, highest, lowest and average of monthly salaries of all employees. SQL> SELECT SUM(SAL), AVG(SAL), MAX(SAL), MIN(SAL) FROM EMP; SUM(SAL) AVG(SAL) MAX(SAL) MIN(SAL) --------- --------- --------- --------29025 2073.2143 5000 800 You can use the MAX and MIN functions for any data type. The example displays the most junior and most senior employee. SQL> SELECT MAX(HIREDATE), MIN(HIREDATE) FROM EMP; MAX(HIRED MIN(HIRED --------- --------23-MAY-87 17-DEC-80 The following example displays the employee name that is first and the employee name that is the last in an alphabetized list of all employees. SQL> SELECT MIN(ENAME), MAX(ENAME) FROM EMP; MIN(ENAME) MAX(ENAME) ---------- ---------ADAMS WARD 82

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

The COUNT Function The COUNT function is used to return the number of rows in a table. The COUNT function has three formats: • COUNT(*) • COUNT(expr) • COUNT(DISTINCT expr) COUNT(*) returns the number of rows in a table that satisfy the criteria of the SELECT statement, including duplicate rows and rows containing null values in any of the columns. SQL> SELECT COUNT(*) FROM EMP; COUNT(*) --------14 If a WHERE clause is included in the SELECT statement, COUNT(*) returns the number of rows that satisfies the condition in the WHERE clause. SQL> SELECT COUNT(*) FROM EMP WHERE DEPTNO=10; COUNT(*) --------3 SQL> SELECT COUNT(*) FROM EMP WHERE JOB='CLERK'; COUNT(*) --------4 COUNT(expr) returns the number of non-null values in the column identified by expr. SQL> SELECT COUNT(EMPNO), COUNT(MGR), COUNT(COMM) FROM EMP; COUNT(EMPNO) COUNT(MGR) COUNT(COMM) ------------ ---------- ----------14 13 4 COUNT(DISTINCT expr) returns the number of unique, non-null values in the column identified by expr. Or Use the DISTINCT keyword to suppress the counting of any duplicate values within a column. SQL> SELECT COUNT(JOB), COUNT(DISTINCT JOB), COUNT(DISTINCT DEPTNO) FROM EMP; COUNT(JOB) COUNT(DISTINCTJOB) COUNT(DISTINCTDEPTNO) ---------- ------------------ --------------------14 5 3 The following example displays the number of employees who are earning more than 2000. SQL> SELECT COUNT(*) FROM EMP WHERE SAL>2000; COUNT(*) --------6 SQL> SELECT COUNT(*) FROM EMP WHERE TO_CHAR(HIREDATE,'RRRR')=1981; COUNT(*) --------10 83

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Group Functions and Null Values All group functions ignore null values in the column. In the example, the average is calculated based only on the rows in the table where a valid value is stored in the COMM column. The average is calculated as the total commission paid to all employees divided by the number of employees receiving a commission (four). SQL> SELECT * FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 MANAGER 7839 02-APR-81 2975 20 SALESMAN 7698 28-SEP-81 1250 1400 30 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 SALESMAN 7698 08-SEP-81 1500 0 30 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 ANALYST 7566 03-DEC-81 3000 20 CLERK 7782 23-JAN-82 1300 10

14 rows selected. SQL> SELECT COUNT(*), COUNT(COMM), AVG(COMM), SUM(COMM), SUM(COMM)/COUNT(COMM) FROM EMP; COUNT(*) COUNT(COMM) AVG(COMM) SUM(COMM) SUM(COMM)/COUNT(COMM) --------- ----------- --------- --------- --------------------14 4 550 2200 550

Using the NVL Function with Group Functions The NVL function forces group functions to include null values. In the example, the average is calculated based on all rows in the table, regardless of whether null values are stored in the COMM column. The average is calculated as the total commission paid to all employees divided by the total number of employees in the company (14). SQL> 2 3 4

SELECT SUM(COMM), COUNT(COMM), AVG(COMM), COUNT(NVL(COMM,0)), AVG(NVL(COMM,0)) FROM EMP;

SUM(COMM) COUNT(COMM) AVG(COMM) COUNT(NVL(COMM,0)) AVG(NVL(COMM,0)) --------- ----------- --------- ------------------ ---------------2200 4 550 14 157.14286

84

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Creating Groups of Data by using GROUP BY clause Until now, all group functions have treated the table as one large group of information. At times, you need to divide the table of information into smaller groups. This can be done by using the GROUP BY clause. You can use the GROUP BY clause to divide the rows in a table into groups. You can then use the group functions to return summary information for each group. Guidelines • If you include a group function in a SELECT clause, you cannot select individual results as well, unless the individual column appears in the GROUP BY clause. You receive an error message if you fail to include the column list in the GROUP BY clause. • Using a WHERE clause, you can exclude rows before dividing them into groups. • You must include the columns in the GROUP BY clause. • You cannot use a column alias in the GROUP BY clause. • By default, rows are sorted by ascending order of the columns included in the GROUP BY list. You can override this by using the ORDER BY clause. The GROUP BY Clause (continued) When using the GROUP BY clause, make sure that all columns in the SELECT list that are not group functions are included in the GROUP BY clause. The example displays the department number and the average salary for each department. Here is how this SELECT statement, containing a GROUP BY clause, is evaluated: • The SELECT clause specifies the columns to be retrieved: • Department number column in the EMP table • The average of all the salaries in the group you specified in the GROUP BY clause • The FROM clause specifies the tables that the database must access: the EMP table. • The WHERE clause specifies the rows to be retrieved. Since there is no WHERE clause, all rows are retrieved by default. • The GROUP BY clause specifies how the rows should be grouped. The rows are being grouped by department number, so the AVG function that is being applied to the salary column will calculate the average salary for each department. SQL> SELECT DEPTNO, AVG(SAL) 2 FROM EMP 3 GROUP BY DEPTNO;

SQL> SELECT DEPTNO, COUNT(*), SUM(SAL) 2 FROM EMP 3 GROUP BY DEPTNO;

DEPTNO AVG(SAL) --------- --------30 1566.6667 20 2175 10 2916.6667

DEPTNO COUNT(*) SUM(SAL) --------- --------- --------30 6 9400 20 5 10875 10 3 8750

The GROUP BY column does not have to be in the SELECT clause. For example, the SELECT statement in the example displays the average salaries for each department without displaying the respective department numbers. Without the department numbers, however, the results do not look meaningful. SQL> SELECT AVG(SAL) 2 FROM EMP 3 GROUP BY DEPTNO;

SQL> SELECT COUNT(*), SUM(SAL) 2 FROM EMP 3 GROUP BY DEPTNO;

AVG(SAL) --------1566.6667 2175 2916.6667

COUNT(*) SUM(SAL) --------- --------6 9400 5 10875 3 8750 85

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

You can use the group function in the ORDER BY clause. SQL> 2 3 4

SELECT FROM GROUP ORDER BY

DEPTNO, COUNT(*), SUM(SAL), AVG(SAL), MAX(SAL), MIN(SAL) EMP BY DEPTNO SUM(SAL);

DEPTNO COUNT(*) SUM(SAL) AVG(SAL) MAX(SAL) MIN(SAL) --------- --------- --------- --------- --------- --------10 3 8750 2916.6667 5000 1300 30 6 9400 1566.6667 2850 950 20 5 10875 2175 3000 800

Summary information according to job wise SQL> 2 3 4

SELECT FROM GROUP ORDER BY

JOB, COUNT(*), SUM(SAL), AVG(SAL), MAX(SAL), MIN(SAL) EMP BY JOB 2;

JOB COUNT(*) SUM(SAL) AVG(SAL) MAX(SAL) MIN(SAL) --------- --------- --------- --------- --------- --------PRESIDENT 1 5000 5000 5000 5000 ANALYST 2 6000 3000 3000 3000 MANAGER 3 8275 2758.3333 2975 2450 SALESMAN 4 5600 1400 1600 1250 CLERK 4 4150 1037.5 1300 800

Summary information according to year wise SQL> 2 3 4 5

SELECT TO_CHAR(HIREDATE,'RRRR'), COUNT(*), SUM(SAL), MAX(SAL), MIN(SAL), AVG(SAL) FROM EMP GROUP BY TO_CHAR(HIREDATE,'RRRR') ORDER BY 1;

TO_C COUNT(*) SUM(SAL) MAX(SAL) MIN(SAL) AVG(SAL) ---- --------- --------- --------- --------- --------1980 1 800 800 800 800 1981 10 22825 5000 950 2282.5 1987 2 4100 3000 1100 2050 2082 1 1300 1300 1300 1300

Summary information according to mon_year wise SQL> 2 3 4

SELECT FROM GROUP ORDER BY

TO_CHAR(HIREDATE,'MON-RRRR') MON_YEAR, COUNT(*), SUM(SAL) EMP BY TO_CHAR(HIREDATE,'MON-RRRR') 1;

MON_YEAR COUNT(*) SUM(SAL) -------- --------- --------APR-1981 1 2975 APR-1987 1 3000 DEC-1980 1 800 DEC-1981 2 3950 FEB-1981 2 2850 JAN-2082 1 1300 JUN-1981 1 2450 MAY-1981 1 2850 MAY-1987 1 1100 NOV-1981 1 5000 SEP-1981 2 2750

86

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Grouping by More Than One Column Groups within Groups You can return summary results for groups and subgroups by listing more than one GROUP BY column. You can determine the default sort order of the results by the order of the columns in the GROUP BY clause. Here is how the SELECT statement on the slide, containing a GROUP BY clause, is evaluated: • The SELECT clause specifies the column to be retrieved: • Department number and job in the EMP table • The summary of all the salaries in the group that you specified in the GROUP BY clause • The FROM clause specifies the tables that the database must access: the EMP table. • The GROUP BY clause specifies how you must group the rows: • First, the rows are grouped by department number. • Second, within the department number groups, the rows are grouped by job. So the group functions are being applied to the salary column for all job within each department number group. SQL> 2 3 4

SELECT FROM GROUP ORDER BY

DEPTNO --------10 10 10 20 20 20 30 30 30

DEPTNO, JOB, COUNT(*), SUM(SAL), AVG(SAL), MAX(SAL), MIN(SAL) EMP BY DEPTNO, JOB 1,2;

JOB COUNT(*) SUM(SAL) AVG(SAL) MAX(SAL) MIN(SAL) --------- --------- --------- --------- --------- --------CLERK 1 1300 1300 1300 1300 MANAGER 1 2450 2450 2450 2450 PRESIDENT 1 5000 5000 5000 5000 ANALYST 2 6000 3000 3000 3000 CLERK 2 1900 950 1100 800 MANAGER 1 2975 2975 2975 2975 CLERK 1 950 950 950 950 MANAGER 1 2850 2850 2850 2850 SALESMAN 4 5600 1400 1600 1250

9 rows selected. SQL> 2 3 4 5

SELECT TO_CHAR(HIREDATE,'RRRR'), TO_CHAR(HIREDATE,'MON'), COUNT(*), SUM(SAL) FROM EMP GROUP BY TO_CHAR(HIREDATE,'RRRR'), TO_CHAR(HIREDATE,'MON') ORDER BY 1,2;

TO_C ---1980 1981 1981 1981 1981 1981 1981 1981 1987 1987 2082

TO_ COUNT(*) SUM(SAL) --- --------- --------DEC 1 800 APR 1 2975 DEC 2 3950 FEB 2 2850 JUN 1 2450 MAY 1 2850 NOV 1 5000 SEP 2 2750 APR 1 3000 MAY 1 1100 JAN 1 1300

11 rows selected.

87

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Illegal Queries Using Group Functions SQL> SELECT DEPTNO, COUNT(*), SUM(SAL) 2 FROM EMP; SELECT DEPTNO, COUNT(*), SUM(SAL) * ERROR at line 1: ORA-00937: not a single-group group function

SQL> SELECT DEPTNO, COUNT(*), SUM(SAL), AVG(SAL) 2 FROM EMP 3 GROUP BY DEPTNO 4 ORDER BY SAL; ORDER BY SAL * ERROR at line 4: ORA-00979: not a GROUP BY expression Whenever you use a mixture of individual items (DEPTNO) and group functions (COUNT) in the same SELECT statement, you must include a GROUP BY clause that specifies the individual items (in this case, DEPTNO). If the GROUP BY clause is missing, then the error message “not a single-group group function” appears and an asterisk (*) points to the offending column. You can correct the error by adding the GROUP BY clause. SQL> SELECT DEPTNO, COUNT(*), SUM(SAL) 2 FROM EMP 3 GROUP BY DEPTNO; DEPTNO COUNT(*) SUM(SAL) --------- --------- --------30 6 9400 20 5 10875 10 3 8750 Any column or expression in the SELECT list that is not an aggregate function must be in the GROUP BY clause.

• • •

You cannot use the WHERE clause to restrict groups. You use the HAVING clause to restrict groups. You cannot use group functions in the WHERE clause.

SQL> SELECT DEPTNO, COUNT(*), SUM(SAL) 2 FROM EMP 3 WHERE SUM(SAL)>9000 4 GROUP BY DEPTNO; WHERE SUM(SAL)>9000 * ERROR at line 3: ORA-00934: group function is not allowed here

88

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Excluding Group Results: The HAVING Clause

Restricting Group Results In the same way that you use the WHERE clause to restrict the rows that you select, you use the HAVING clause to restrict groups. To find the summation of salary of each department, but show only the departments that have a summation of salary more than 9,000, you need to do the following: 1. Find the summation of salary for each department by grouping by department number. 2. Restrict the groups to those departments with a sum of salary greater than 9,000. SQL> 2 3 4

SELECT FROM HAVING GROUP BY

DEPTNO, COUNT(*), SUM(SAL) EMP SUM(SAL)>9000 DEPTNO;

DEPTNO COUNT(*) SUM(SAL) --------- --------- --------30 6 9400 20 5 10875 The HAVING Clause You use the HAVING clause to specify which groups are to be displayed, and thus, you further restrict the groups on the basis of aggregate information. In the syntax: group_condition restricts the groups of rows returned to those groups for which the specified condition is true The Oracle server performs the following steps when you use the HAVING clause: 1. Rows are grouped. 2. The group function is applied to the group. 3. The groups that match the criteria in the HAVING clause are displayed. The HAVING clause can precede the GROUP BY clause, but it is recommended that you place the GROUP BY clause first because that is more logical. Groups are formed and group functions are calculated before the HAVING clause is applied to the groups in the SELECT list. SQL> 2 3 4

SELECT FROM GROUP BY HAVING

DEPTNO, COUNT(*), SUM(SAL) EMP DEPTNO SUM(SAL)>9000;

DEPTNO COUNT(*) SUM(SAL) --------- --------- --------30 6 9400 20 5 10875 The following example displays department numbers and maximum salaries for those departments whose maximum salary is greater or equal to 3,000. You can use the GROUP BY clause without using a group function in the SELECT list. If you restrict rows based on the result of a group function, you must have a GROUP BY clause as well as the HAVING clause. The following example displays the department numbers and maximum salaries for those departments whose maximum salary is greater than 3,000: SQL> 2 3 4

SQL> 2 3 4

SELECT DEPTNO, MAX(SAL) FROM EMP GROUP BY DEPTNO HAVING MAX(SAL)>=3000;

SELECT DEPTNO FROM EMP GROUP BY DEPTNO HAVING MAX(SAL)>=3000;

DEPTNO --------20 10

DEPTNO MAX(SAL) --------- --------20 3000 10 5000 89

[email protected]

Prepared by Muhammad Raheem

Oracle SQL SQL> 2 3 4 5

Phone: 021-4265550, Cell: 0321-4265550

SELECT TO_CHAR(HIREDATE,'RRRR'), COUNT(*) FROM EMP GROUP BY TO_CHAR(HIREDATE,'RRRR') HAVING COUNT(*)>1 ORDER BY TO_CHAR(HIREDATE,'RRRR');

TO_C COUNT(*) ---- --------1981 10 1987 2

SQL> 2 3 4

SELECT TO_CHAR(HIREDATE,'RRRR'), COUNT(*) FROM EMP GROUP BY TO_CHAR(HIREDATE,'RRRR') ORDER BY TO_CHAR(HIREDATE,'RRRR');

TO_C COUNT(*) ---- --------1980 1 1981 10 1987 2 2082 1

Nesting Group Functions Group functions can be nested to a depth of two. The example displays the maximum average salary. SQL> SELECT MAX(AVG(SAL)) 2 FROM EMP 3 GROUP BY DEPTNO; MAX(AVG(SAL)) ------------2916.6667 SQL> SELECT MAX(SUM(SAL)) 2 FROM EMP 3 GROUP BY DEPTNO; MAX(SUM(SAL)) ------------10875

SQL> SELECT SUM(MAX(SAL)) FROM EMP 2 GROUP BY DEPTNO; SUM(MAX(SAL)) ------------10850

90

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Chapter 6

Subqueries A subquery is a query within a query. In Oracle, you can create subqueries within your SQL statements. These subqueries can reside in the WHERE clause, HAVING clause, the FROM clause, or the SELECT clause. Use a subquery when there is an unknown criteria. For example,

I want to retrieve all employees who are working in SMITH’S department. Smith’s Department is unknown, first find Smith’s department by using the following query: SQL> SELECT DEPTNO FROM EMP WHERE ENAME='SMITH'; DEPTNO --------20 And now use department number 20 for retrieving all employees of that department. SQL> SELECT * FROM EMP WHERE DEPTNO=20; EMPNO --------7369 7566 7788 7876 7902

ENAME ---------SMITH JONES SCOTT ADAMS FORD

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 MANAGER 7839 02-APR-81 2975 20 ANALYST 7566 19-APR-87 3000 20 CLERK 7788 23-MAY-87 1100 20 ANALYST 7566 03-DEC-81 3000 20

But you can achieve the above task by using the following subquery in where clause. SQL> SELECT * FROM EMP WHERE DEPTNO=(SELECT DEPTNO FROM EMP WHERE ENAME='SMITH'); EMPNO --------7369 7566 7788 7876 7902

ENAME ---------SMITH JONES SCOTT ADAMS FORD

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 MANAGER 7839 02-APR-81 2975 20 ANALYST 7566 19-APR-87 3000 20 CLERK 7788 23-MAY-87 1100 20 ANALYST 7566 03-DEC-81 3000 20

In the above example, the inner query determines the department of employee SMITHl. The outer query takes the result of the inner query and uses this result to display all the employees who belong to this department.

Display all employees who are earning more than JONES. Without subquery: SQL> SELECT SAL FROM EMP WHERE ENAME='JONES'; SQL> SELECT * FROM EMP WHERE SAL>2975;

Æ 2975

Using subquery: SQL> SELECT * FROM EMP WHERE SAL>(SELECT SAL FROM EMP WHERE ENAME='JONES'); 91

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Display all employees who are working on the same post as BLAKE BLAKE’s job is unknown, first find BLAKE’s job by using the following query: SQL> SELECT JOB FROM EMP WHERE ENAME='BLAKE'; JOB --------MANAGER And now use MANAGER in criteria for retrieving all employees of that job. SQL> SELECT * FROM EMP WHERE JOB='MANAGER'; EMPNO --------7566 7698 7782

ENAME ---------JONES BLAKE CLARK

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 02-APR-81 2975 20 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10

But you can achieve the above task by using the following subquery in where clause. SQL> SELECT * FROM EMP WHERE JOB=(SELECT JOB FROM EMP WHERE ENAME='BLAKE'); EMPNO --------7566 7698 7782

ENAME ---------JONES BLAKE CLARK

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 02-APR-81 2975 20 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10

Display all employees who are working in SALES department Department names are not saved in EMP table. Now you have to use DEPT table in subquery because DEPT table contains department names. SQL> SELECT * FROM DEPT; DEPTNO --------10 20 30 40

DNAME -------------ACCOUNTING RESEARCH SALES OPERATIONS

LOC ------------NEW YORK DALLAS CHICAGO BOSTON

In the following query you used two tables DEPT in inner query and EMP in outer query. SQL> SELECT * FROM EMP WHERE DEPTNO=(SELECT DEPTNO FROM DEPT WHERE DNAME='SALES'); EMPNO --------7499 7521 7654 7698 7844 7900

ENAME ---------ALLEN WARD MARTIN BLAKE TURNER JAMES

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 SALESMAN 7698 28-SEP-81 1250 1400 30 MANAGER 7839 01-MAY-81 2850 30 SALESMAN 7698 08-SEP-81 1500 0 30 CLERK 7698 03-DEC-81 950 30 92

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Using Group Functions in a Subquery

You can display data from a main query by using a group function in a subquery to return a single row. The subquery is in parentheses and is placed after the comparison condition.

Display employee who is (are) earning maximum salary First find maximum salary by using the following query: SQL> SELECT MAX(SAL) FROM EMP; MAX(SAL) --------5000 Then put 5000 in WHERE clause for matching criteria: SQL> SELECT * FROM EMP WHERE SAL=5000; EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO --------- ---------- --------- --------- --------- --------- --------- --------7839 KING PRESIDENT 17-NOV-81 5000 10 But you can use the following subquery: SQL> SELECT * FROM EMP WHERE SAL=(SELECT MAX(SAL) FROM EMP); EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO --------- ---------- --------- --------- --------- --------- --------- --------7839 KING PRESIDENT 17-NOV-81 5000 10

Guidelines for Using Subqueries • • • • • Write 1. 2. 3. 4. 5. 6. 7. 8.

A subquery must be enclosed in parentheses. Place the subquery on the right side of the comparison condition for readability. The ORDER BY clause in the subquery is not needed unless you are performing Top-N analysis. Two classes of comparison conditions are used in subqueries: single-row operators and multiple-row operators. Use single-row operators with single-row subqueries and use multiple-row operators with multiple-row subqueries.

queries of the following: Subordinates list of BLAKE (manager) Employees working with ALLEN in the same department Manager's record of Mr. SMITH Employees who are working in NEW YORK Employees who are senior than SCOTT Employee with least salary in the company Complete information of most experienced employee in the company Display all employees who are working on the same job as SMITH'S job and are earning more than ADAMS

What is the meaning of following queries? SELECT * FROM EMP WHERE TO_CHAR(HIREDATE,'RRRR') = (SELECT TO_CHAR(HIREDATE,'RRRR') FROM EMP WHERE ENAME='JONES'); SELECT * FROM EMP WHERE LENGTH(ENAME)=(SELECT LENGTH(ENAME) FROM EMP WHERE EMPNO=7521); SELECT * FROM EMP WHERE SUBSTR(ENAME,2,1)=(SELECT SUBSTR(ENAME,2,1) FROM EMP WHERE EMPNO=7902); 93

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Types of Subqueries • •

Single-row subqueries: Queries that return only one row from the inner SELECT statement Multiple-row subqueries: Queries that return more than one row from the inner SELECT statement

Note: There are also multiple-column subqueries: Queries that return more than one column from the inner SELECT statement.

Single-Row Subqueries A single-row subquery is one that returns one row from the inner SELECT statement. This type of subquery uses a single-row operator.

Operator = > >= < (SELECT SAL FROM EMP WHERE EMPNO=7900); The HAVING Clause with Subqueries You can use subqueries not only in the WHERE clause, but also in the HAVING clause. The Oracle server executes the subquery, and the results are returned into the HAVING clause of the main query. The SQL statement on in the following example displays all the departments that have a minimum salary greater than that of department 30. SQL> SELECT DEPTNO, MIN(SAL) FROM EMP 2 GROUP BY DEPTNO 3 HAVING MIN(SAL)>(SELECT MIN(SAL) FROM EMP WHERE DEPTNO=30); DEPTNO MIN(SAL) --------- --------10 1300 SQL> SELECT DEPTNO, MIN(SAL) FROM EMP 2 GROUP BY DEPTNO; DEPTNO MIN(SAL) --------- --------30 950 20 800 10 1300 SQL> SELECT MIN(SAL) FROM EMP WHERE DEPTNO=30; MIN(SAL) --------950 94

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Multiple-Row Subqueries Subqueries that return more than one row are called multiple-row subqueries. You use a multiple-row operator, instead of a single-row operator, with a multiple-row subquery. The multiple-row operator expects one or more values.

Operator IN ANY ALL

Meaning Equal to any member in the list Compare value to each value returned by the subquery Compare value to every value returned by the subquery

What is wrong with this Statement? SQL> SELECT * FROM EMP 2 WHERE SAL = (SELECT MAX(SAL) FROM EMP GROUP BY DEPTNO); WHERE SAL = (SELECT MAX(SAL) FROM EMP GROUP BY DEPTNO) * ERROR at line 2: ORA-01427: single-row subquery returns more than one row

One common error with subqueries is more than one row returned for a single-row subquery. In the SQL statement in the above example, the subquery contains a GROUP BY clause, which implies that the subquery will return multiple rows, one for each group it finds. In this case, the result of the subquery will be 2850, 3000 and 5000. SQL> SELECT MAX(SAL) FROM EMP GROUP BY DEPTNO; MAX(SAL) --------2850 3000 5000 The outer query takes the results of the subquery (2850, 3000, 5000) and uses these results in its WHERE clause. The WHERE clause contains an equal (=) operator, a single-row comparison operator expecting only one value. The = operator cannot accept more than one value from the subquery and therefore generates the error. To correct this error, change the = operator to IN. Find the employees who earn the same salary as the minimum salary for each department. SQL> SELECT * FROM EMP 2 WHERE SAL IN (SELECT MAX(SAL) FROM EMP GROUP BY DEPTNO); EMPNO --------7698 7902 7788 7839

ENAME ---------BLAKE FORD SCOTT KING

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 01-MAY-81 2850 30 ANALYST 7566 03-DEC-81 3000 20 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10

The inner query is executed first, producing a query result. The main query block is then processed and uses the values returned by the inner query to complete its search condition. In fact, the main query would appear to the Oracle server as follows: SELECT last_name, salary, department_id FROM employees WHERE salary IN (2850, 3000, 5000); 95

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Display all employees who are working on the same post of department number 10 employees SQL> SELECT * FROM EMP WHERE JOB IN (SELECT JOB FROM EMP WHERE DEPTNO=10); EMPNO --------7782 7698 7566 7839 7934 7900 7876 7369

ENAME ---------CLARK BLAKE JONES KING MILLER JAMES ADAMS SMITH

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 09-JUN-81 2450 10 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 02-APR-81 2975 20 PRESIDENT 17-NOV-81 5000 10 CLERK 7782 23-JAN-82 1300 10 CLERK 7698 03-DEC-81 950 30 CLERK 7788 23-MAY-87 1100 20 CLERK 7902 17-DEC-80 800 20

8 rows selected. Find all available jobs/posts of department number 10 SQL> SELECT JOB FROM EMP WHERE DEPTNO=10; JOB --------MANAGER PRESIDENT CLERK SQL> SELECT * FROM EMP WHERE JOB IN ('MANAGER','PRESIDENT','CLERK'); EMPNO --------7369 7566 7698 7782 7839 7876 7900 7934

ENAME ---------SMITH JONES BLAKE CLARK KING ADAMS JAMES MILLER

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 MANAGER 7839 02-APR-81 2975 20 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 PRESIDENT 17-NOV-81 5000 10 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 CLERK 7782 23-JAN-82 1300 10

8 rows selected.

Retrieve all managers of CLERK SQL> SELECT * FROM EMP WHERE EMPNO IN (SELECT MGR FROM EMP WHERE JOB='CLERK'); EMPNO --------7698 7782 7788 7902

ENAME ---------BLAKE CLARK SCOTT FORD

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 ANALYST 7566 19-APR-87 3000 20 ANALYST 7566 03-DEC-81 3000 20

SQL> SELECT MGR FROM EMP WHERE JOB='CLERK'; Result of the above query 7902 7788 7698

7782 96

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Using ANY and ALL Operator in Multiple-Row Subqueries ANY

Æ

OR

>ANY means more than the minimum. ALL means more than the maximum. ANY Operator List all employees having salaries more then the minimum salary of department # 30 SQL> SELECT SAL FROM EMP WHERE DEPTNO=30; SAL --------1600 1250 1250 2850 1500 950 6 rows selected. SQL> SELECT MIN(SAL) FROM EMP WHERE DEPTNO=30; MIN(SAL) --------950 SQL> SELECT * FROM EMP WHERE SAL>(SELECT MIN(SAL) FROM EMP WHERE DEPTNO=30); EMPNO --------7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7902 7934

ENAME ---------ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS FORD MILLER

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 MANAGER 7839 02-APR-81 2975 20 SALESMAN 7698 28-SEP-81 1250 1400 30 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 SALESMAN 7698 08-SEP-81 1500 0 30 CLERK 7788 23-MAY-87 1100 20 ANALYST 7566 03-DEC-81 3000 20 CLERK 7782 23-JAN-82 1300 10

12 rows selected. SQL> 97

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT * FROM EMP 2 WHERE SAL > ANY (SELECT SAL FROM EMP WHERE DEPTNO = 30); EMPNO --------7839 7902 7788 7566 7698 7782 7499 7844 7934 7521 7654 7876

ENAME ---------KING FORD SCOTT JONES BLAKE CLARK ALLEN TURNER MILLER WARD MARTIN ADAMS

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------PRESIDENT 17-NOV-81 5000 10 ANALYST 7566 03-DEC-81 3000 20 ANALYST 7566 19-APR-87 3000 20 MANAGER 7839 02-APR-81 2975 20 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 08-SEP-81 1500 0 30 CLERK 7782 23-JAN-82 1300 10 SALESMAN 7698 22-FEB-81 1250 500 30 SALESMAN 7698 28-SEP-81 1250 1400 30 CLERK 7788 23-MAY-87 1100 20

12 rows selected. SQL> SELECT * FROM EMP 2 WHERE SAL > ANY (950,1250,1500,1600,2850); EMPNO --------7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7902 7934

ENAME ---------ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS FORD MILLER

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 MANAGER 7839 02-APR-81 2975 20 SALESMAN 7698 28-SEP-81 1250 1400 30 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 SALESMAN 7698 08-SEP-81 1500 0 30 CLERK 7788 23-MAY-87 1100 20 ANALYST 7566 03-DEC-81 3000 20 CLERK 7782 23-JAN-82 1300 10

12 rows selected. SQL> SELECT * FROM EMP 2 WHERE SAL>950 OR SAL>1250 OR SAL>1500 OR SAL>1600 OR SAL>2850; EMPNO --------7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7902 7934

ENAME ---------ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS FORD MILLER

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 MANAGER 7839 02-APR-81 2975 20 SALESMAN 7698 28-SEP-81 1250 1400 30 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 SALESMAN 7698 08-SEP-81 1500 0 30 CLERK 7788 23-MAY-87 1100 20 ANALYST 7566 03-DEC-81 3000 20 CLERK 7782 23-JAN-82 1300 10

12 rows selected. 98

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

The SELECT SAL FROM EMP WHERE DEPTNO=30; SAL --------1600 1250 1250 2850 1500 950 6 rows selected. SQL> SELECT MAX(SAL) FROM EMP WHERE DEPTNO=30; 2850 SQL> SELECT * FROM EMP 2 WHERE SAL SELECT * FROM EMP 2 WHERE SAL < ANY (SELECT SAL FROM EMP WHERE DEPTNO = 30); EMPNO --------7369 7900 7876 7521 7654 7934 7844 7499 7782

ENAME ---------SMITH JAMES ADAMS WARD MARTIN MILLER TURNER ALLEN CLARK

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 CLERK 7698 03-DEC-81 950 30 CLERK 7788 23-MAY-87 1100 20 SALESMAN 7698 22-FEB-81 1250 500 30 SALESMAN 7698 28-SEP-81 1250 1400 30 CLERK 7782 23-JAN-82 1300 10 SALESMAN 7698 08-SEP-81 1500 0 30 SALESMAN 7698 20-FEB-81 1600 300 30 MANAGER 7839 09-JUN-81 2450 10

9 rows selected. SQL> SELECT * FROM EMP 2 WHERE SAL < ANY (950,1250,1500,1600,2850); SQL> SELECT * FROM EMP 2 WHERE SALALL Operator List of all employees having salaries more then the maximum salary of department # 30 SQL> SELECT SAL FROM EMP WHERE DEPTNO = 30; SAL --------1600 1250 1250 2850 1500 950 6 rows selected. SQL> SELECT MAX(SAL) FROM EMP WHERE DEPTNO = 30; 2850 SQL> SELECT * FROM EMP 2 WHERE SAL > (SELECT MAX(SAL) FROM EMP WHERE DEPTNO = 30); EMPNO --------7566 7788 7839 7902

ENAME ---------JONES SCOTT KING FORD

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 02-APR-81 2975 20 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 ANALYST 7566 03-DEC-81 3000 20

SQL> SELECT * FROM EMP 2 WHERE SAL > ALL (SELECT SAL FROM EMP WHERE DEPTNO = 30); EMPNO --------7566 7788 7839 7902

ENAME ---------JONES SCOTT KING FORD

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 02-APR-81 2975 20 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 ANALYST 7566 03-DEC-81 3000 20

SQL> SELECT * FROM EMP 2 WHERE SAL > ALL (950,1250,1500,1600,2850); EMPNO --------7566 7788 7839 7902

ENAME ---------JONES SCOTT KING FORD

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 02-APR-81 2975 20 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 ANALYST 7566 03-DEC-81 3000 20

SQL> SELECT * FROM EMP 2 WHERE SAL>950 AND SAL>1250 AND SAL>1500 AND SAL>1600 AND SAL>2850; EMPNO --------7566 7788 7839 7902

ENAME ---------JONES SCOTT KING FORD

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 02-APR-81 2975 20 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 ANALYST 7566 03-DEC-81 3000 20 101

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

The SELECT SAL FROM EMP WHERE DEPTNO = 30; SAL --------1600 1250 1250 2850 1500 950 6 rows selected. SQL> SELECT MIN(SAL) FROM EMP WHERE DEPTNO = 30; MIN(SAL) --------950 SQL> SELECT * FROM EMP 2 WHERE SAL < (SELECT MIN(SAL) FROM EMP WHERE DEPTNO = 30); EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO --------- ---------- --------- --------- --------- --------- --------- --------7369 SMITH CLERK 7902 17-DEC-80 800 20 SQL> SELECT * FROM EMP 2 WHERE SAL < ALL (SELECT SAL FROM EMP WHERE DEPTNO = 30); EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO --------- ---------- --------- --------- --------- --------- --------- --------7369 SMITH CLERK 7902 17-DEC-80 800 20 SQL> SELECT * FROM EMP 2 WHERE SAL < ALL (950,1250,1500,1600,2850); EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO --------- ---------- --------- --------- --------- --------- --------- --------7369 SMITH CLERK 7902 17-DEC-80 800 20

= SELECT * FROM EMP 2 WHERE SAL = ALL (SELECT SAL FROM EMP WHERE DEPTNO = 30); no rows selected SQL>

102

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

List all employees having salaries less then the maximum salary of any "CLERK". Do not display any "CLERK". SQL> SELECT * FROM EMP WHERE SAL < (SELECT MAX(SAL) FROM EMP WHERE JOB='CLERK'); EMPNO --------7369 7521 7654 7876 7900

ENAME ---------SMITH WARD MARTIN ADAMS JAMES

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 SALESMAN 7698 22-FEB-81 1250 500 30 SALESMAN 7698 28-SEP-81 1250 1400 30 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30

SQL> SELECT * FROM EMP WHERE SAL SELECT * FROM EMP WHERE SAL SELECT * FROM EMP WHERE SAL >ALL (SELECT AVG(SAL) FROM EMP GROUP BY DEPTNO); EMPNO --------7566 7788 7839 7902

ENAME ---------JONES SCOTT KING FORD

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 02-APR-81 2975 20 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 ANALYST 7566 03-DEC-81 3000 20

SQL> SELECT AVG(SAL) FROM EMP GROUP BY DEPTNO; AVG(SAL) --------1566.6667 2175 2916.6667

103

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

What happened if inner query return null A common problem with subqueries is no rows being returned by the inner query. In the following SQL statement, the subquery contains a WHERE clause. Presumably, the intention is to find the employee whose commission is equal to SMITH’s commission. The statement is correct but selects no rows when executed. There is no commission for SMITH, So the subquery returns no rows. The outer query takes the results of the subquery (null) and uses these results in its WHERE clause. The outer query finds no employee with a COMM equal to null, and so returns no rows. If a COMM existed with a value of null, the row is not returned because comparison of two null values yields a null, therefore the WHERE condition is not true. SQL> SELECT * FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 MANAGER 7839 02-APR-81 2975 20 SALESMAN 7698 28-SEP-81 1250 1400 30 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 SALESMAN 7698 08-SEP-81 1500 0 30 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 ANALYST 7566 03-DEC-81 3000 20 CLERK 7782 23-JAN-82 1300 10

14 rows selected.

Display all employees whose commission is equal to SMITH’s commission. SQL> SELECT COMM FROM EMP WHERE ENAME='SMITH'; COMM ---------

SQL> SELECT * FROM EMP 2 WHERE COMM=(SELECT COMM FROM EMP WHERE ENAME='SMITH'); no rows selected SQL> SELECT * FROM EMP 2 WHERE NVL(COMM,-1)=(SELECT NVL(COMM,-1) FROM EMP WHERE ENAME='SMITH'); EMPNO --------7369 7566 7698 7782 7788 7839 7876 7900 7902 7934

ENAME ---------SMITH JONES BLAKE CLARK SCOTT KING ADAMS JAMES FORD MILLER

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 MANAGER 7839 02-APR-81 2975 20 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 ANALYST 7566 03-DEC-81 3000 20 CLERK 7782 23-JAN-82 1300 10

10 rows selected. 104

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

List all employees having at least one subordinate. SQL> SELECT * FROM EMP 2 WHERE EMPNO IN (SELECT MGR FROM EMP); EMPNO --------7566 7698 7782 7788 7839 7902

ENAME ---------JONES BLAKE CLARK SCOTT KING FORD

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 02-APR-81 2975 20 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 ANALYST 7566 03-DEC-81 3000 20

6 rows selected.

List of all employees having no sub-ordinate. SQL> SELECT * FROM EMP 2 WHERE EMPNO NOT IN (SELECT MGR FROM EMP); no rows selected

The SQL statement on the slide attempts to display all the employees who do not have any subordinates. Logically, this SQL statement should have returned 8 rows. However, the SQL statement does not return any rows. One of the values returned by the inner query is a null value, and hence the entire query returns no rows. The reason is that all conditions that compare a null value result in a null. So whenever null values are likely to be part of the results set of a subquery, do not use the NOT IN operator. Alternatively, a WHERE clause can be included in the subquery to display all employees who do not have any subordinates: SQL> SELECT * FROM EMP 2 WHERE EMPNO NOT IN (SELECT NVL(MGR,0) FROM EMP); EMPNO --------7369 7499 7521 7654 7844 7876 7900 7934

ENAME ---------SMITH ALLEN WARD MARTIN TURNER ADAMS JAMES MILLER

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 SALESMAN 7698 28-SEP-81 1250 1400 30 SALESMAN 7698 08-SEP-81 1500 0 30 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 CLERK 7782 23-JAN-82 1300 10

8 rows selected. SQL> SELECT * FROM EMP 2 WHERE EMPNO NOT IN (SELECT MGR FROM EMP WHERE MGR IS NOT NULL); EMPNO --------7369 7499 7521 7654 7844 7876 7900 7934

ENAME ---------SMITH ALLEN WARD MARTIN TURNER ADAMS JAMES MILLER

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 SALESMAN 7698 28-SEP-81 1250 1400 30 SALESMAN 7698 08-SEP-81 1500 0 30 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 CLERK 7782 23-JAN-82 1300 10

8 rows selected. 105

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Chapter 7

Producing Readable Output with SQL*Plus Substitution Variables A variable can be thought of as a container in which the values are temporarily stored. When the statement is run, the value is substituted. In SQL*Plus, you can use single ampersand (&) substitution variables to temporarily store values. You can predefine variables in SQL*Plus by using the DEFINE command. DEFINE creates and assigns a value to a variable. Use SQL*Plus substitution variables to: • Temporarily store values – Single ampersand (&) – Double ampersand (&&) – DEFINE command • Pass variable values between SQL statements

Display environmental variables by using [DEF]INE command SQL> DEFINE DEFINE _SQLPLUS_RELEASE = "800060000" (CHAR) DEFINE _EDITOR = "Notepad" (CHAR) DEFINE _O_VERSION = "Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production With the Partitioning, OLAP and Data Mining options" (CHAR) DEFINE _O_RELEASE = "1002000100" (CHAR) DEFINE _RC = "1" (CHAR) SQL> DEF DEFINE _SQLPLUS_RELEASE = "800060000" (CHAR) DEFINE _EDITOR = "Notepad" (CHAR) DEFINE _O_VERSION = "Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production With the Partitioning, OLAP and Data Mining options" (CHAR) DEFINE _O_RELEASE = "1002000100" (CHAR)

Declare variables in SQL Plus environment by using DEFINE Command SQL> DEFINE A=10 SQL> DEFINE B=SMITH SQL> DEFINE C=ALLEN SQL> DEFINE DEFINE _SQLPLUS_RELEASE = "800060000" (CHAR) DEFINE _EDITOR = "Notepad" (CHAR) DEFINE _O_VERSION = "Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production With the Partitioning, OLAP and Data Mining options" (CHAR) DEFINE _O_RELEASE = "1002000100" (CHAR) DEFINE _RC = "1" (CHAR) DEFINE A = "10" (CHAR) DEFINE B = "SMITH" (CHAR) DEFINE C = "ALLEN" (CHAR) 106

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Remove defined variables in SQL Plus environment by using UNDEFINE Command SQL> UNDEFINE C

Display value of specific variable SQL> DEF DEFINE A SQL> DEF DEFINE B SQL> DEF symbol c

A = "10" (CHAR) B = "SMITH" (CHAR) C is UNDEFINED

Using defined variables in SQL statements by using single & SQL> SELECT * FROM EMP WHERE DEPTNO=&A; old 1: SELECT * FROM EMP WHERE DEPTNO=&A new 1: SELECT * FROM EMP WHERE DEPTNO=10 EMPNO --------7782 7839 7934

ENAME ---------CLARK KING MILLER

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 09-JUN-81 2450 10 PRESIDENT 17-NOV-81 5000 10 CLERK 7782 23-JAN-82 1300 10

SQL> SELECT * FROM EMP WHERE ENAME='&B'; old 1: SELECT * FROM EMP WHERE ENAME='&B' new 1: SELECT * FROM EMP WHERE ENAME='SMITH' EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO --------- ---------- --------- --------- --------- --------- --------- --------7369 SMITH CLERK 7902 17-DEC-80 800 20 SQL> SET VERIFY OFF SQL> SELECT * FROM EMP WHERE DEPTNO=&A; EMPNO --------7782 7839 7934

ENAME ---------CLARK KING MILLER

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 09-JUN-81 2450 10 PRESIDENT 17-NOV-81 5000 10 CLERK 7782 23-JAN-82 1300 10

SQL> SELECT * FROM EMP WHERE ENAME='&B'; EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO --------- ---------- --------- --------- --------- --------- --------- --------7369 SMITH CLERK 7902 17-DEC-80 800 20

Use singe & Substitution Variable if you want to use already defined variable i.e. A or B Enclose Char and Date in single quote

107

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

If you use & single substitution variable in SQL statement which is not defined then it will prompt (ask) each time for the value and variable will not be created. SQL> SET VERIFY ON SQL> SELECT * FROM EMP Enter value for aslam: old 1: SELECT * FROM new 1: SELECT * FROM EMPNO --------7782 7839 7934

ENAME ---------CLARK KING MILLER

WHERE DEPTNO=&ASLAM; 10 EMP WHERE DEPTNO=&ASLAM EMP WHERE DEPTNO=10

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 09-JUN-81 2450 10 PRESIDENT 17-NOV-81 5000 10 CLERK 7782 23-JAN-82 1300 10

SQL> SELECT * FROM EMP WHERE DEPTNO=&DEPARTMENT_NO; Enter value for department_no: 20 old 1: SELECT * FROM EMP WHERE DEPTNO=&DEPARTMENT_NO new 1: SELECT * FROM EMP WHERE DEPTNO=20 EMPNO --------7369 7566 7788 7876 7902

ENAME ---------SMITH JONES SCOTT ADAMS FORD

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 MANAGER 7839 02-APR-81 2975 20 ANALYST 7566 19-APR-87 3000 20 CLERK 7788 23-MAY-87 1100 20 ANALYST 7566 03-DEC-81 3000 20

SQL> SELECT * FROM EMP WHERE JOB='&JOB_TITLE'; Enter value for job_title: CLERK old 1: SELECT * FROM EMP WHERE JOB='&JOB_TITLE' new 1: SELECT * FROM EMP WHERE JOB='CLERK' EMPNO --------7369 7876 7900 7934

ENAME ---------SMITH ADAMS JAMES MILLER

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 CLERK 7782 23-JAN-82 1300 10

SQL> SELECT * FROM EMP WHERE SAL>&SALARY; Enter value for salary: 2000 old 1: SELECT * FROM EMP WHERE SAL>&SALARY new 1: SELECT * FROM EMP WHERE SAL>2000 EMPNO --------7566 7698 7782 7788 7839 7902

ENAME ---------JONES BLAKE CLARK SCOTT KING FORD

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 02-APR-81 2975 20 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 ANALYST 7566 03-DEC-81 3000 20

108

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT * FROM EMP WHERE HIREDATE&&EMPLOYEE_SALARY new 1: SELECT * FROM EMP WHERE SAL>3000 EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO --------- ---------- --------- --------- --------- --------- --------- --------7839 KING PRESIDENT 17-NOV-81 5000 10

109

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Notice that DEPT_NO and EMPLOYEE_SALARY variable have been created by using && double substitution variable. SQL> DEFINE DEFINE _SQLPLUS_RELEASE = "800060000" (CHAR) DEFINE _EDITOR = "Notepad" (CHAR) DEFINE _O_VERSION = "Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production With the Partitioning, OLAP and Data Mining options" (CHAR) DEFINE _O_RELEASE = "1002000100" (CHAR) DEFINE _RC = "1" (CHAR) DEFINE A = "10" (CHAR) DEFINE B = "SMITH" (CHAR) DEFINE DEPT_NO = "10" (CHAR) DEFINE EMPLOYEE_SALARY = "3000" (CHAR)

You can use DEPT_NO and EMPLOYEE_SALARY variables in SQL statements SQL> SET VERIFY OFF SQL> SELECT * FROM EMP WHERE SAL=&EMPLOYEE_SALARY; EMPNO --------7788 7902

ENAME ---------SCOTT FORD

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------ANALYST 7566 19-APR-87 3000 20 ANALYST 7566 03-DEC-81 3000 20

SQL> SELECT * FROM EMP 2 WHERE JOB='CLERK' AND DEPTNO=&DEPT_NO; EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO --------- ---------- --------- --------- --------- --------- --------- --------7934 MILLER CLERK 7782 23-JAN-82 1300 10

SQL> SELECT * FROM EMP 2 WHERE JOB='CLERK' AND DEPTNO=&&DEPT_NO; EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO --------- ---------- --------- --------- --------- --------- --------- --------7934 MILLER CLERK 7782 23-JAN-82 1300 10 • • • •

Both & and && first search for variable in memory. Both & and && use existing value of the variable if exist. Both will collect input from user if variable does not exist. & destroy variable after query if it does not already exist but && store variable value in memory for later use.

Variable can be defined by using DEFINE command or by using && substitution variable. Variable can be destroy by using UNDEFINE command or variable will be destroy when you exit from the current session.

110

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Use of & and && in different clauses SQL> SELECT Enter value Enter value Enter value Enter value EMPNO --------7788 7839 7902

ENAME SAL ---------- --------SCOTT 3000 KING 5000 FORD 3000

SQL> SELECT Enter value Enter value Enter value Enter value DEPTNO --------10 20 30 40

&COL1, &COL2, &COL3 FROM &TABLE_NAME; for col1: DEPTNO for col2: DNAME for col3: LOC for table_name: DEPT

DNAME -------------ACCOUNTING RESEARCH SALES OPERATIONS

SQL> SELECT Enter value Enter value Enter value Enter value EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

&COL1, &COL2, &COL3 FROM EMP WHERE SAL>=&SALARY; for col1: EMPNO for col2: ENAME for col3: SAL for salary: 3000

&COL1, &COL2, &COL3 FROM &TABLE_NAME; for col1: EMPNO for col2: JOB for col3: ENAME for table_name: EMP

JOB --------CLERK SALESMAN SALESMAN MANAGER SALESMAN MANAGER MANAGER ANALYST PRESIDENT SALESMAN CLERK CLERK ANALYST CLERK

SQL> SELECT Enter value Enter value Enter value Enter value

LOC ------------NEW YORK DALLAS CHICAGO BOSTON

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

&COL1, &COL2, &COL3 FROM &TABLE_NAME; for col1: EMPNO, ENAME, JOB for col2: SAL for col3: DEPTNO for table_name: EMP

111

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT * FROM EMP 2 WHERE SAL = (&QUERY); Enter value for query: SELECT SAL FROM EMP WHERE ENAME = 'ALLEN' EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO --------- ---------- --------- --------- --------- --------- --------- --------7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30

Environmental Setting ------------------- SET FEEDBACK [ON/OFF/n] ------------------SQL> SET FEEDBACK 3 SQL> SELECT * FROM EMP WHERE DEPTNO=10; EMPNO --------7782 7839 7934

ENAME ---------CLARK KING MILLER

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 09-JUN-81 2450 10 PRESIDENT 17-NOV-81 5000 10 CLERK 7782 23-JAN-82 1300 10

3 rows selected. SQL> SET FEEDBACK 5 SQL> SELECT * FROM EMP WHERE DEPTNO=10; EMPNO --------7782 7839 7934

ENAME ---------CLARK KING MILLER

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 09-JUN-81 2450 10 PRESIDENT 17-NOV-81 5000 10 CLERK 7782 23-JAN-82 1300 10

------------------- SET HEADING ON/OFF ------------------SQL> SET HEADING OFF SQL> SELECT * FROM EMP WHERE DEPTNO=10; 7782 CLARK 7839 KING 7934 MILLER

MANAGER PRESIDENT CLERK

7839 09-JUN-81 17-NOV-81 7782 23-JAN-82

2450 5000 1300

10 10 10

SQL> SET HEADING ON SQL> SELECT * FROM EMP WHERE DEPTNO=10; EMPNO --------7782 7839 7934

ENAME ---------CLARK KING MILLER

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 09-JUN-81 2450 10 PRESIDENT 17-NOV-81 5000 10 CLERK 7782 23-JAN-82 1300 10

------------------- SHOW ------------------SQL> SHOW HEADING heading ON SQL> SHOW FEEDBACK FEEDBACK ON for 5 or more rows SQL> SHOW ALL 112

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

---------------- SET LINESIZE -------------------SHOW LINES SELECT * FROM EMP; SET LINES 100; SHOW LINESIZE SHOW LINES ---------------- SET PAGESIZE -------------------SHOW PAGESIZE SHOW PAGES SET PAGESIZE 25

The COLUMN Command SQL> SQL> SQL> SQL>

COL COL COL COL

ENAME HEADING EMPLOYEE JOB HEADING JOB_TITLE COMM HEADING CMSN NULL NOT_APP SAL FORMAT 9,999.99

SQL> SELECT * FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

EMPLOYEE ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

JOB_TITLE MGR HIREDATE SAL CMSN DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 8,00 NOT_APP 20 SALESMAN 7698 20-FEB-81 16,00 300 30 SALESMAN 7698 22-FEB-81 12,50 500 30 MANAGER 7839 02-APR-81 29,75 NOT_APP 20 SALESMAN 7698 28-SEP-81 12,50 1400 30 MANAGER 7839 01-MAY-81 28,50 NOT_APP 30 MANAGER 7839 09-JUN-81 24,50 NOT_APP 10 ANALYST 7566 19-APR-87 30,00 NOT_APP 20 PRESIDENT 17-NOV-81 50,00 NOT_APP 10 SALESMAN 7698 08-SEP-81 15,00 0 30 CLERK 7788 23-MAY-87 11,00 NOT_APP 20 CLERK 7698 03-DEC-81 9,50 NOT_APP 30 ANALYST 7566 03-DEC-81 30,00 NOT_APP 20 CLERK 7782 23-JAN-82 13,00 NOT_APP 10

View setting of specific column SQL> COL SAL COLUMN SAL ON FORMAT 9,999.99

View setting of all columns SQL> COL

Clear format of specific column SQL> SQL> SQL> SQL>

COL COL COL COL

SAL CLEAR COMM CLEAR JOB CLEAR ENAME CLEAR

Clear format of all columns SQL> CLEAR COLUMNS 113

[email protected]

Prepared by Muhammad Raheem

Oracle SQL SQL> SQL> SQL> SQL>

Phone: 021-4265550, Cell: 0321-4265550

COL SAL NOPRINT COL COMM NOPRINT COL ENAME FORMAT A20 HEADING EMPLOYEE_NAME SELECT * FROM EMP;

EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

EMPLOYEE_NAME -------------------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

JOB MGR HIREDATE DEPTNO --------- --------- --------- --------CLERK 7902 17-DEC-80 20 SALESMAN 7698 20-FEB-81 30 SALESMAN 7698 22-FEB-81 30 MANAGER 7839 02-APR-81 20 SALESMAN 7698 28-SEP-81 30 MANAGER 7839 01-MAY-81 30 MANAGER 7839 09-JUN-81 10 ANALYST 7566 19-APR-87 20 PRESIDENT 17-NOV-81 10 SALESMAN 7698 08-SEP-81 30 CLERK 7788 23-MAY-87 20 CLERK 7698 03-DEC-81 30 ANALYST 7566 03-DEC-81 20 CLERK 7782 23-JAN-82 10

14 rows selected. SQL> COL SAL PRINT SQL> COL ENAME FORMAT A10 HEADING NAME JUSTIFY CENTER SQL> COL COMM CLEAR SQL> SELECT * FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

NAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 MANAGER 7839 02-APR-81 2975 20 SALESMAN 7698 28-SEP-81 1250 1400 30 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 SALESMAN 7698 08-SEP-81 1500 0 30 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 ANALYST 7566 03-DEC-81 3000 20 CLERK 7782 23-JAN-82 1300 10

14 rows selected.

What is DEMOBLD.SQL? DEMOBLD.SQL is a script file created by oracle. It contains tables for practice. E:\oracle\ora92\sqlplus\demo\demobld.sql

114

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

SQL Statements Versus SQL*Plus Commands SQL*Plus

SQL

• • • •

SQL> 2 3 4

A language ANSI standard Keyword cannot be abbreviated Statements manipulate data and table definitions in the databa

• • • •

An environment

• •

Runs on a browser



Do not require statement terminator



Command does not store in buffer

Oracle proprietary Keywords can be abbreviated Commands do not allow manipulation of values in the database

Centrally loaded, does not have to be implemented on each machine

SELECT EMPNO, ENAME, JOB, SAL FROM EMP WHERE DEPTNO=10 ORDER BY EMPNO;

EMPNO ENAME JOB SAL --------- ---------- --------- --------7782 CLARK MANAGER 2450 7839 KING PRESIDENT 5000 se 7934 MILLER CLERK 1300 Require statement terminator ;

• • Last query stores in buffer The LIST command SQL> 1 2 3 4*

L SELECT EMPNO, ENAME, JOB, SAL FROM EMP WHERE DEPTNO=10 ORDER BY EMPNO

SQL> 1 2 3* SQL> 1* SQL>

L 1 3 SELECT EMPNO, ENAME, JOB, SAL FROM EMP WHERE DEPTNO=10 L 1 SELECT EMPNO, ENAME, JOB, SAL

The SAVE command To save your query in a text file for later use SQL> SAVE D:\Q1 Created file D:\Q1 Use REPLACE/REP if you want to overwrite previous file. SQL> SAVE Q1 REP 115

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

The START or @ command To load and execute already saved query without listing a query. SQL> @D:\Q1 EMPNO --------7782 7839 7934

ENAME ---------CLARK KING MILLER

JOB SAL --------- --------MANAGER 2450 PRESIDENT 5000 CLERK 1300

SQL> START D:\Q1 EMPNO --------7782 7839 7934

ENAME ---------CLARK KING MILLER

JOB SAL --------- --------MANAGER 2450 PRESIDENT 5000 CLERK 1300

The RUN or R command To load and execute already saved query with listing a query. SQL> 1 2 3 4*

RUN D:\Q1 SELECT EMPNO, ENAME, JOB, SAL FROM EMP WHERE DEPTNO=10 ORDER BY EMPNO

EMPNO --------7782 7839 7934

ENAME ---------CLARK KING MILLER

JOB SAL --------- --------MANAGER 2450 PRESIDENT 5000 CLERK 1300

To run already loaded query in a buffer. SQL> 1 2 3 4*

R SELECT EMPNO, ENAME, JOB, SAL FROM EMP WHERE DEPTNO=10 ORDER BY EMPNO

EMPNO --------7782 7839 7934

ENAME ---------CLARK KING MILLER

JOB SAL --------- --------MANAGER 2450 PRESIDENT 5000 CLERK 1300

The GET command

The / Command

Only load already saved query into buffer.

To execute a query already loaded in buffer.

SQL> 1 2 3 4* SQL>

SQL> /

GET D:\Q1 SELECT EMPNO, ENAME, JOB, SAL FROM EMP WHERE DEPTNO=10 ORDER BY EMPNO

EMPNO --------7782 7839 7934 116

ENAME ---------CLARK KING MILLER

JOB SAL --------- --------MANAGER 2450 PRESIDENT 5000 CLERK 1300 [email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Chapter 8

Manipulating Data Data Manipulation Language •



A DML statement is executed when you: – Add new rows to a table – Modify existing rows in a table – Remove existing rows from a table A transaction consists of a collection of DML statements that form a logical unit of work.

The INSERT Statement You can add new rows to a table by issuing the INSERT statement. Inserting New Rows • • • • SQL> 2 3 4

Insert a new row containing values for each column. List values in the default order of the columns in the table. Optionally, list the columns in the INSERT clause. Enclose character and date values within single quotation marks. INSERT INTO DEPT (DEPTNO, DNAME, LOC) VALUES (55, 'IT','KARACHI');

1 row created. Because you can insert a new row that contains values for each column, the column list is not required in the INSERT clause. However, if you do not use the column list, the values must be listed according to the default order of the columns in the table, and a value must be provided for each column.

Inserting Rows with Null Values by using NULL in value list SQL> 2 3 4

INSERT INTO DEPT (DEPTNO, DNAME, LOC) VALUES (60,'PURCHASE',NULL);

1 row created. Explicit method: Specify the NULL keyword in the VALUES clause.

Inserting Rows with Null Values by excluding column from column list. SQL> 2 3 4

INSERT INTO DEPT (DEPTNO, DNAME) VALUES (65,'AUDIT');

1 row created. Implicit method: Omit the column from the column list. Only one row is inserted at a time if VALUES clause is used for insertion with INSERT. 117

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

You can not insert null value in not null column. So be care full when you are inserting rows in a table. Null value can be inserted by NULL key word or by omitting column from column list. SQL> INSERT INTO DEPT 2 (DNAME, LOC) 3 VALUES 4 ('HR','LAHORE'); INSERT INTO DEPT * ERROR at line 1: ORA-01400: cannot insert NULL into ("SCOTT"."DEPT"."DEPTNO") You are inserting NULL value in DEPTNO column, and null is not allowed for DEPTNO column.

When inserting rows in a table any constraint may violate, so be care full. SQL> INSERT INTO DEPT 2 (DEPTNO, DNAME, LOC) 3 VALUES 4 (10,'MIS','LAHORE'); INSERT INTO DEPT * ERROR at line 1: ORA-00001: unique constraint (SCOTT.PK_DEPT) violated You are inserting duplicate value in DEPTNO column, DEPTNO is primary key.

SQL> INSERT INTO EMP 2 (EMPNO, ENAME, JOB, DEPTNO) 3 VALUES 4 (4,'ALI','MANAGER',70); INSERT INTO EMP * ERROR at line 1: ORA-02291: integrity constraint (SCOTT.FK_DEPTNO) violated - parent key not found You are inserting a value 70 in DEPTNO column which is not present in DEPT table.

Inserting Special Values SQL> 2 3 4

INSERT INTO EMP (EMPNO, ENAME, JOB, HIREDATE, DEPTNO) VALUES (1,USER,'CLERK',SYSDATE,55);

1 row created.

Inserting Specific Date Values SQL> 2 3 4

INSERT INTO EMP (EMPNO, ENAME, JOB, HIREDATE) VALUES (2,'ASLAM','MANAGER',TO_DATE('JULY 28, 2008','MONTH DD, RRRR'));

1 row created. The DD-MON-YY format is usually used to insert a date value. If a date must be entered in a format other than the default format, you must use the TO_DATE function. 118

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Creating a Script • •

Use & substitution in a SQL statement to prompt for values. & is a placeholder for the variable value.

SQL> INSERT INTO EMP 2 (EMPNO, ENAME, JOB, SAL, HIREDATE, DEPTNO) 3 VALUES 4 (&EMPNO, '&ENAME','&JOB',&SALARY,'&HIREDATE',&DEPTNO); Enter value for empno: 3 Enter value for ename: SALEEM Enter value for job: CLERK Enter value for salary: 2000 Enter value for hiredate: 10-JAN-2007 Enter value for deptno: 10 old 4: (&EMPNO, '&ENAME','&JOB',&SALARY,'&HIREDATE',&DEPTNO) new 4: (3, 'SALEEM','CLERK',2000,'10-JAN-2007',10) 1 row created.

Verify new insertion SQL> SELECT * FROM DEPT; DEPTNO --------10 20 30 40 55 60 65

DNAME -------------ACCOUNTING RESEARCH SALES OPERATIONS IT PURCHASE AUDIT

LOC ------------NEW YORK DALLAS CHICAGO BOSTON KARACHI

7 rows selected. SQL> SELECT * FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934 1 2 3

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER SCOTT ASLAM SALEEM

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 MANAGER 7839 02-APR-81 2975 20 SALESMAN 7698 28-SEP-81 1250 1400 30 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 SALESMAN 7698 08-SEP-81 1500 0 30 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 ANALYST 7566 03-DEC-81 3000 20 CLERK 7782 23-JAN-82 1300 10 CLERK 06-AUG-08 55 MANAGER 28-JUL-08 CLERK 10-JAN-07 2000 10

17 rows selected.

119

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT * FROM EMP WHERE DEPTNO=10; EMPNO --------7782 7839 7934 3

ENAME ---------CLARK KING MILLER SALEEM

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 09-JUN-81 2450 10 PRESIDENT 17-NOV-81 5000 10 CLERK 7782 23-JAN-82 1300 10 CLERK 10-JAN-07 2000 10

SQL> SELECT * FROM EMP WHERE JOB IN ('CLERK','MANAGER'); EMPNO --------7369 7566 7698 7782 7876 7900 7934 1 2 3

ENAME ---------SMITH JONES BLAKE CLARK ADAMS JAMES MILLER SCOTT ASLAM SALEEM

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 MANAGER 7839 02-APR-81 2975 20 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 CLERK 7782 23-JAN-82 1300 10 CLERK 06-AUG-08 55 MANAGER 28-JUL-08 CLERK 10-JAN-07 2000 10

10 rows selected.

Is the following query working correctly? What about ASLAM’s record? Aslam is MANAGER and department is not assigned to him. What is the meaning of the following query? SQL> SELECT EMPNO, ENAME, JOB, SAL, DEPTNO 2 FROM EMP 3 WHERE DEPTNO 10 AND JOB IN ('CLERK','MANAGER'); EMPNO --------7369 7566 7698 7876 7900 1

ENAME ---------SMITH JONES BLAKE ADAMS JAMES SCOTT

JOB SAL DEPTNO --------- --------- --------CLERK 800 20 MANAGER 2975 20 MANAGER 2850 30 CLERK 1100 20 CLERK 950 30 CLERK 55

6 rows selected.

120

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

You have to change your condition in where clause. SQL> SELECT EMPNO, ENAME, JOB, SAL, DEPTNO 2 FROM EMP 3 WHERE (DEPTNO10 OR DEPTNO IS NULL) AND JOB IN ('CLERK','MANAGER'); EMPNO --------7369 7566 7698 7876 7900 1 2

ENAME ---------SMITH JONES BLAKE ADAMS JAMES SCOTT ASLAM

JOB SAL DEPTNO --------- --------- --------CLERK 800 20 MANAGER 2975 20 MANAGER 2850 30 CLERK 1100 20 CLERK 950 30 CLERK 55 MANAGER

7 rows selected. SQL> SELECT EMPNO, ENAME, JOB, SAL, DEPTNO 2 FROM EMP 3 WHERE NVL(DEPTNO,0)10 AND JOB IN ('CLERK','MANAGER'); EMPNO --------7369 7566 7698 7876 7900 1 2

ENAME ---------SMITH JONES BLAKE ADAMS JAMES SCOTT ASLAM

JOB SAL DEPTNO --------- --------- --------CLERK 800 20 MANAGER 2975 20 MANAGER 2850 30 CLERK 1100 20 CLERK 950 30 CLERK 55 MANAGER

7 rows selected.

121

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

The following joining query will not show ASLAM’s record, because ASLAM is not assigned any department. The department value of ASLAM’s record mismatched with value in DEPT table. SQL> SELECT E.EMPNO, E.ENAME, E.JOB, E.SAL, E.DEPTNO, D.DNAME, D.LOC 2 FROM EMP E, DEPT D 3 WHERE E.DEPTNO=D.DEPTNO; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934 1 3

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER SCOTT SALEEM

JOB SAL DEPTNO DNAME --------- --------- --------- -------------CLERK 800 20 RESEARCH SALESMAN 1600 30 SALES SALESMAN 1250 30 SALES MANAGER 2975 20 RESEARCH SALESMAN 1250 30 SALES MANAGER 2850 30 SALES MANAGER 2450 10 ACCOUNTING ANALYST 3000 20 RESEARCH PRESIDENT 5000 10 ACCOUNTING SALESMAN 1500 30 SALES CLERK 1100 20 RESEARCH CLERK 950 30 SALES ANALYST 3000 20 RESEARCH CLERK 1300 10 ACCOUNTING CLERK 55 IT CLERK 2000 10 ACCOUNTING

LOC ------------DALLAS CHICAGO CHICAGO DALLAS CHICAGO CHICAGO NEW YORK DALLAS NEW YORK CHICAGO DALLAS CHICAGO DALLAS NEW YORK KARACHI NEW YORK

16 rows selected.

How can I find all employees either value is matched or not? SQL> SELECT E.EMPNO, E.ENAME, E.JOB, E.SAL, E.DEPTNO, D.DNAME, D.LOC 2 FROM EMP E, DEPT D 3 WHERE E.DEPTNO=D.DEPTNO(+); EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934 1 2 3

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER SCOTT ASLAM SALEEM

JOB SAL DEPTNO DNAME --------- --------- --------- -------------CLERK 800 20 RESEARCH SALESMAN 1600 30 SALES SALESMAN 1250 30 SALES MANAGER 2975 20 RESEARCH SALESMAN 1250 30 SALES MANAGER 2850 30 SALES MANAGER 2450 10 ACCOUNTING ANALYST 3000 20 RESEARCH PRESIDENT 5000 10 ACCOUNTING SALESMAN 1500 30 SALES CLERK 1100 20 RESEARCH CLERK 950 30 SALES ANALYST 3000 20 RESEARCH CLERK 1300 10 ACCOUNTING CLERK 55 IT MANAGER CLERK 2000 10 ACCOUNTING

LOC ------------DALLAS CHICAGO CHICAGO DALLAS CHICAGO CHICAGO NEW YORK DALLAS NEW YORK CHICAGO DALLAS CHICAGO DALLAS NEW YORK KARACHI NEW YORK

17 rows selected.

I want to find only those employees whose department value is mismatched? SQL> SELECT E.EMPNO, E.ENAME, E.JOB, E.SAL, E.DEPTNO, D.DNAME, D.LOC 2 FROM EMP E, DEPT D 3 WHERE E.DEPTNO=D.DEPTNO(+) AND E.DEPTNO IS NULL; EMPNO ENAME JOB SAL DEPTNO DNAME LOC --------- ---------- --------- --------- --------- -------------- ------------2 ASLAM MANAGER 122

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

I want to find those departments in which no employee was hired. SQL> SELECT E.EMPNO, E.ENAME, E.JOB, E.SAL, D.DEPTNO, D.DNAME, D.LOC 2 FROM EMP E, DEPT D 3 WHERE E.DEPTNO(+)=D.DEPTNO AND E.EMPNO IS NULL; EMPNO ENAME JOB SAL DEPTNO --------- ---------- --------- --------- --------40 60 65

DNAME LOC -------------- ------------OPERATIONS BOSTON PURCHASE AUDIT

INSERT is a DML statement. For saving data permanently into database, commit may be applied either implicitly or explicitly.

The COMMIT statement For applying explicit commit the COMMIT statement is used. SQL> COMMIT; Commit complete. SQL>

The ROLLBACK statement You can undo or revert data which is changed by DML statements. To revert/undo you have to use rollback, rollback may be applied either implicitly or explicitly. For applying explicit rollback the ROLLBACK statement is used. SQL> ROLLBACK; Rollback complete. SQL> COMMIT and ROLLBACK will be discussed in detail.

123

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Let’s come back to INSERT statement. Execute the following query to create a table for practice INSERT statement. Create a table EMP_INS with the same structure of EMP table. The WHERE 1>2 restrict for copying data. SQL> CREATE TABLE EMP_INS AS SELECT * FROM EMP WHERE 1>2; Table created.

Notice the EMPNO column in both EMP and EMP_INS tables in the below: SQL> DESC EMP Name Null? ------------------------------- -------EMPNO NOT NULL ENAME JOB MGR HIREDATE SAL COMM DEPTNO

Type ---NUMBER(4) VARCHAR2(10) VARCHAR2(9) NUMBER(4) DATE NUMBER(7,2) NUMBER(7,2) NUMBER(2)

SQL> DESC EMP_INS Name Null? ------------------------------- -------EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

Type ---NUMBER(4) VARCHAR2(10) VARCHAR2(9) NUMBER(4) DATE NUMBER(7,2) NUMBER(7,2) NUMBER(2)

SQL> CREATE TABLE DEPT_INS AS SELECT * FROM DEPT; Table created. Note: when you create a table by using subquery like in the above examples, then constrains will not be copied. Create a table DEPT_INS with the same structure of DEPT table as well as with all rows, because the WHERE clause is not used. SQL> SELECT * FROM EMP_INS; no rows selected SQL> SELECT * FROM DEPT_INS;

DEPTNO --------10 20 30 40 55 60 65

DNAME -------------ACCOUNTING RESEARCH SALES OPERATIONS IT PURCHASE AUDIT

LOC ------------NEW YORK DALLAS CHICAGO BOSTON KARACHI

7 rows selected. 124

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Copying Rows from Another Table You can use the INSERT statement to add rows to a table where the values are derived from existing tables. In place of the VALUES clause, you use a subquery. The number of columns and their data types in the column list of the INSERT clause must match the number of values and their data types in the subquery. Do not use the VALUES clause. Insert rows from EMP table to EMP_INS table by using INSERT statement. The following query will copy all employees of department number 10 from EMP table into EMP_INS table. If you do not specify WHERE clause then all rows of EMP table will copy into EMP_INS table. SQL> INSERT INTO EMP_INS 2 SELECT * FROM EMP WHERE DEPTNO=10; 4 rows created. If you do not specify column list in INSERT clause and in the subquery (SELECT clause), its means the structure of both tables are same. The following query will copy EMPNO, ENAME, JOB, SAL & DEPTNO columns of those employees who are working as CLEAR and MANAGER and did not belong to department number 10. SQL> 2 3 4 5

INSERT INTO EMP_INS (EMPNO, ENAME, JOB, SAL, DEPTNO) SELECT EMPNO, ENAME, JOB, SAL, DEPTNO FROM EMP WHERE (DEPTNO 10 OR DEPTNO IS NULL) AND JOB IN ('CLERK','MANAGER');

7 rows created. If structure of both tables are not same then you must provide the corresponding columns for insertion in INSERT clause and in the subquery (SELECT clause).

SQL> SELECT * FROM EMP_INS; EMPNO --------7782 7839 7934 3 7369 7566 7698 7876 7900 1 2

ENAME ---------CLARK KING MILLER SALEEM SMITH JONES BLAKE ADAMS JAMES SCOTT ASLAM

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 09-JUN-81 2450 10 PRESIDENT 17-NOV-81 5000 10 CLERK 7782 23-JAN-82 1300 10 CLERK 10-JAN-07 2000 10 CLERK 800 20 MANAGER 2975 20 MANAGER 2850 30 CLERK 1100 20 CLERK 950 30 CLERK 55 MANAGER

11 rows selected.

125

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Changing Data in a Table You can modify existing rows by using the UPDATE statement. • •

Specific row or rows are modified if you specify the WHERE clause. All rows in the table are modified if you omit the WHERE clause.

SQL> UPDATE EMP 2 SET ENAME='S.C.O.T.T.' 3 WHERE EMPNO=1; 1 row updated. SQL> SELECT * FROM EMP WHERE EMPNO=1; EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO --------- ---------- --------- --------- --------- --------- --------- --------1 S.C.O.T.T. CLERK 06-AUG-08 55

SQL> UPDATE EMP 2 SET ENAME='SCOTT', 3 SAL =1000 4 WHERE EMPNO=1; 1 row updated. SQL> SELECT * FROM EMP WHERE EMPNO=1; EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO --------- ---------- --------- --------- --------- --------- --------- --------1 SCOTT CLERK 06-AUG-08 1000 55

Updating with a Subquery SQL> UPDATE EMP 2 SET MGR = 7839, 3 SAL = (SELECT MAX(SAL) FROM EMP WHERE JOB='MANAGER'), 4 DEPTNO = 55 5 WHERE EMPNO = 2; 1 row updated. SQL> SELECT * FROM EMP WHERE EMPNO=2; EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO --------- ---------- --------- --------- --------- --------- --------- --------2 ASLAM MANAGER 7839 28-JUL-08 2975 55

Updating Rows Based on Another Table SQL> UPDATE EMP 2 SET JOB = 'ASST IT', 3 SAL = SAL+SAL*15/100, 4 MGR = 2 , 5 DEPTNO = (SELECT DEPTNO FROM DEPT WHERE DNAME='IT') 6 WHERE EMPNO=3; 1 row updated.

126

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Updating with a Nested Subquery SQL> UPDATE EMP 2 SET MGR=(SELECT EMPNO FROM EMP 3 WHERE JOB='MANAGER' AND 4 DEPTNO=(SELECT DEPTNO FROM DEPT WHERE DNAME='IT') 5 ) 6 WHERE EMPNO=1; 1 row updated. SQL> COMMIT; Commit complete. SQL> SELECT * FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934 1 2 3

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER SCOTT ASLAM SALEEM

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 MANAGER 7839 02-APR-81 2975 20 SALESMAN 7698 28-SEP-81 1250 1400 30 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 SALESMAN 7698 08-SEP-81 1500 0 30 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 ANALYST 7566 03-DEC-81 3000 20 CLERK 7782 23-JAN-82 1300 10 CLERK 2 06-AUG-08 1000 55 MANAGER 7839 28-JUL-08 2975 55 ASST IT 2 10-JAN-07 2300 55

17 rows selected.

Updating Rows: Integrity Constraint Error SQL> UPDATE EMP 2 SET DEPTNO=5 3 WHERE SAL>2000; UPDATE EMP * ERROR at line 1: ORA-02291: integrity constraint (SCOTT.FK_DEPTNO) violated - parent key not found If you attempt to update a record with a value that is tied to an integrity constraint, an error is returned. In the above example, department number 5 does not exist in the parent table, DEPT, and so you receive the parent key violation ORA-02291.

127

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT * FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934 1 2 3

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER SCOTT ASLAM SALEEM

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 MANAGER 7839 02-APR-81 2975 20 SALESMAN 7698 28-SEP-81 1250 1400 30 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 SALESMAN 7698 08-SEP-81 1500 0 30 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 ANALYST 7566 03-DEC-81 3000 20 CLERK 7782 23-JAN-82 1300 10 CLERK 2 06-AUG-08 1000 55 MANAGER 7839 28-JUL-08 2975 55 ASST IT 2 10-JAN-07 2300 55

17 rows selected. Give 10% increment to all employees who have hired before 12 or more months. SQL> UPDATE EMP 2 SET SAL=SAL+SAL*10/100 3 WHERE TRUNC(MONTHS_BETWEEN(SYSDATE,HIREDATE))>=12; 15 rows updated. SQL> SELECT * FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934 1 2 3

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER SCOTT ASLAM SALEEM

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 880 20 SALESMAN 7698 20-FEB-81 1760 300 30 SALESMAN 7698 22-FEB-81 1375 500 30 MANAGER 7839 02-APR-81 3273 20 SALESMAN 7698 28-SEP-81 1375 1400 30 MANAGER 7839 01-MAY-81 3135 30 MANAGER 7839 09-JUN-81 2695 10 ANALYST 7566 19-APR-87 3300 20 PRESIDENT 17-NOV-81 5500 10 SALESMAN 7698 08-SEP-81 1650 0 30 CLERK 7788 23-MAY-87 1210 20 CLERK 7698 03-DEC-81 1045 30 ANALYST 7566 03-DEC-81 3300 20 CLERK 7782 23-JAN-82 1430 10 CLERK 2 06-AUG-08 1000 55 MANAGER 7839 28-JUL-08 2975 55 ASST IT 2 10-JAN-07 2530 55

17 rows selected. SQL> ROLLBACK; Rollback complete.

128

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

SQL> SELECT * FROM EMP_INS; EMPNO --------7782 7839 7934 3 7369 7566 7698 7876 7900 1 2

ENAME ---------CLARK KING MILLER SALEEM SMITH JONES BLAKE ADAMS JAMES SCOTT ASLAM

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 09-JUN-81 2450 10 PRESIDENT 17-NOV-81 5000 10 CLERK 7782 23-JAN-82 1300 10 CLERK 10-JAN-07 2000 10 CLERK 800 20 MANAGER 2975 20 MANAGER 2850 30 CLERK 1100 20 CLERK 950 30 CLERK 55 MANAGER

11 rows selected. SQL> UPDATE EMP_INS SET SAL=NULL; 11 rows updated. SQL> SELECT * FROM EMP_INS; EMPNO --------7782 7839 7934 3 7369 7566 7698 7876 7900 1 2

ENAME ---------CLARK KING MILLER SALEEM SMITH JONES BLAKE ADAMS JAMES SCOTT ASLAM

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 09-JUN-81 10 PRESIDENT 17-NOV-81 10 CLERK 7782 23-JAN-82 10 CLERK 10-JAN-07 10 CLERK 20 MANAGER 20 MANAGER 30 CLERK 20 CLERK 30 CLERK 55 MANAGER

11 rows selected. SQL> UPDATE EMP_INS A 2 SET SAL = (SELECT SAL FROM EMP B WHERE A.EMPNO=B.EMPNO); SQL> SELECT * FROM EMP_INS; EMPNO --------7782 7839 7934 3 7369 7566 7698 7876 7900 1 2

ENAME ---------CLARK KING MILLER SALEEM SMITH JONES BLAKE ADAMS JAMES SCOTT ASLAM

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 09-JUN-81 2450 10 PRESIDENT 17-NOV-81 5000 10 CLERK 7782 23-JAN-82 1300 10 CLERK 10-JAN-07 2300 10 CLERK 800 20 MANAGER 2975 20 MANAGER 2850 30 CLERK 1100 20 CLERK 950 30 CLERK 1000 55 MANAGER 2975

11 rows selected. 129

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Removing a Row from a Table You can remove existing rows by using the DELETE statement.

Specific rows are deleted if you specify the WHERE clause. SQL> DELETE EMP WHERE DEPTNO=10; 3 rows deleted.

SQL> DELETE FROM EMP WHERE DEPTNO=10; 3 rows deleted.

All rows in the table are deleted if you omit the WHERE clause. SQL> DELETE EMP; 14 rows deleted. SQL> DELETE FROM EMP; 14 rows deleted.

SQL> ROLLBACK; Rollback complete.

Deleting Rows Based on Another Table SQL> DELETE EMP WHERE DEPTNO=(SELECT DEPTNO FROM DEPT WHERE DNAME='SALES'); 6 rows deleted.

Deleting Rows: Integrity Constraint Error SQL> DELETE DEPT WHERE DEPTNO=10; DELETE DEPT WHERE DEPTNO=10 * ERROR at line 1: ORA-02292: integrity constraint (SCOTT.FK_DEPTNO) violated - child record found If you attempt to delete a record with a value that is tied to an integrity constraint, an error is returned. In the above example you try to delete department number 10 from the DEPT table, but it results in an error because department number is used as a foreign key in the EMPL table. If the parent record that you attempt to delete has child records, then you receive the child record found violation ORA-02292.

130

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Database Transactions The Oracle server ensures data consistency based on transactions. Transactions give you more flexibility and control when changing data, and they ensure data consistency in the event of user process failure or system failure. Transactions consist of DML statements that make up one consistent change to the data.

When Does a Transaction Start and End? A transaction begins when the first DML statement is encountered and ends when one of the following occurs: • A COMMIT or ROLLBACK statement is issued • A DDL statement, such as CREATE, is issued • A DCL statement is issued • The user exits SQL*Plus • A machine fails or the system crashes After one transaction ends, the next executable SQL statement automatically starts the next transaction. A DDL statement or a DCL statement is automatically committed and therefore implicitly ends a transaction. Explicit Transaction Control Statements You can control the logic of transactions by using the COMMIT, SAVEPOINT, and ROLLBACK statements. Implicit Transaction Processing • An automatic commit occurs under the following circumstances: – DDL statement is issued – DCL statement is issued – Normal exit from SQL*Plus, without explicitly issuing COMMIT or ROLLBACK statements • An automatic rollback occurs under an abnormal termination of SQL*Plus or a system failure. State of the Data Before COMMIT or ROLLBACK • • • •

The previous state of the data can be recovered. The current user can review the results of the DML operations by using the SELECT statement. Other users cannot view the results of the DML statements by the current user. The affected rows are locked; other users cannot change the data within the affected rows.

State of the Data after COMMIT • • • • •

Data changes are made permanent in the database. The previous state of the data is permanently lost. All users can view the results. Locks on the affected rows are released; those rows are available for other users to manipulate. All savepoints are erased.

131

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

State of the Data After ROLLBACK Discard all pending changes by using the ROLLBACK statement: • Data changes are undone. • Previous state of the data is restored. • Locks on the affected rows are released. Committing Data SQL> COMMIT; Commit complete. Rollback Data SQL> ROLLBACK; Rollback complete. Statement-Level Rollback • • • •

If a single DML statement fails during execution, only that statement is rolled back. The Oracle server implements an implicit savepoint. All other changes are retained. The user should terminate transactions explicitly by executing a COMMIT or ROLLBACK statement.

Read Consistency • • •

Read consistency guarantees a consistent view of the data at all times. Changes made by one user do not conflict with changes made by another user. Read consistency ensures that on the same data: – Readers do not wait for writers. – Writers do not wait for readers.

Locking In an • • • • •

Oracle database, locks: Prevent destructive interaction between concurrent transactions Require no user action Automatically use the lowest level of restrictiveness Are held for the duration of the transaction Are of two types: explicit locking and implicit locking

132

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Chapter 9

Creating and Managing Tables Database Objects An Oracle database can contain multiple data structures. Each structure should be outlined in the database design so that it can be created during the build stage of database development. • Table: Stores data • View: Subset of data from one or more tables • Sequence: Numeric value generator • Index: Improves the performance of some queries • Synonym: Gives alternative names to objects Oracle Table Structures • Tables can be created at any time, even while users are using the database. • You do not need to specify the size of any table. The size is ultimately defined by the amount of space allocated to the database as a whole. It is important, however, to estimate how much space a table will use over time. • Table structure can be modified online. Tables can have up to 1,000 columns and must conform to standard database object-naming conventions. The CREATE TABLE Statement Create tables to store data by executing the SQL CREATE TABLE statement. This statement is one of the data definition language (DDL) statements SQL> 2 3 4 5 6

CREATE TABLE DEPT_INFO ( DEPTNO NUMBER(2) PRIMARY KEY, DNAME VARCHAR2(14), LOC VARCHAR2(13) );

Table created. SQL> 2 3 4 5 6 7 8 9 10 11

CREATE TABLE EMP_INFO ( EMPNO NUMBER(4) PRIMARY KEY, ENAME VARCHAR2(10), JOB VARCHAR2(9), MGR NUMBER(4) REFERENCES EMP (EMPNO), HIREDATE DATE, SAL NUMBER(7,2), COMM NUMBER(7,2), DEPTNO REFERENCES DEPT (DEPTNO) );

Table created. SQL> DEPTNO is a primary key in DEPT table, and foreign key in EMP table. EMPNO is a primary key in EMP table.

133

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

How to verify table creation? By DESC / DESCRIBE Command SQL> DESC DEPT_INFO Name Null? ------------------------------- -------DEPTNO NOT NULL DNAME LOC

Type ---NUMBER(2) VARCHAR2(14) VARCHAR2(13)

SQL> DESC EMP_INFO Name Null? ------------------------------- -------EMPNO NOT NULL ENAME JOB MGR HIREDATE SAL COMM DEPTNO

Type ---NUMBER(4) VARCHAR2(10) VARCHAR2(9) NUMBER(4) DATE NUMBER(7,2) NUMBER(7,2) NUMBER(2)

By SELECT Statement SQL> SELECT * FROM DEPT_INFO; no rows selected SQL> SELECT * FROM EMP_INFO; no rows selected

Querying the Data Dictionary By a data dictionary view Æ USER_TABLES

or

(TABS)

SQL> SELECT TABLE_NAME FROM USER_TABLES;

By a data dictionary view Æ USER_OBJECTS

or

(OBJ)

SQL> SELECT OBJECT_NAME FROM USER_OBJECTS WHERE OBJECT_TYPE='TABLE';

By a data dictionary view Æ USER_CATALOG

or

(CAT)

SQL> SELECT * FROM USER_CATALOG WHERE TABLE_TYPE='TABLE';

By a data dictionary view Æ TAB

or

(TAB)

SQL> SELECT * FROM TAB WHERE TABTYPE='TABLE';

134

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Creating a Table by Using a Subquery The following queries will create a table as well as copy all rows: SQL> CREATE TABLE EMP1 2 AS SELECT * FROM EMP; Table created. SQL> CREATE TABLE EMP2 2 AS SELECT EMPNO, ENAME, JOB, SAL FROM EMP; Table created. SQL> CREATE TABLE EMP3 2 AS SELECT EMPNO, ENAME, JOB, SAL FROM EMP WHERE DEPTNO=10; Table created. SQL> CREATE TABLE EMP4 2 (EMP_ID, EMP_NAME, JOB, SALARY) 3 AS SELECT EMPNO, ENAME, JOB, SAL FROM EMP; Table created. SQL> DESC EMP1 Name Null? ------------------------------- -------EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

Type ---NUMBER(4) VARCHAR2(10) VARCHAR2(9) NUMBER(4) DATE NUMBER(7,2) NUMBER(7,2) NUMBER(2)

SQL> DESC EMP2 Name Null? ------------------------------- -------EMPNO ENAME JOB SAL

Type ---NUMBER(4) VARCHAR2(10) VARCHAR2(9) NUMBER(7,2)

SQL> DESC EMP3 Name Null? ------------------------------- -------EMPNO ENAME JOB SAL

Type ---NUMBER(4) VARCHAR2(10) VARCHAR2(9) NUMBER(7,2)

SQL> DESC EMP4 Name Null? ------------------------------- -------EMP_ID EMP_NAME JOB SALARY

Type ---NUMBER(4) VARCHAR2(10) VARCHAR2(9) NUMBER(7,2)

135

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

The ALTER TABLE Statement After you create a table, you may need to change the table structure because: you omitted a column, your column definition needs to be changed, or you need to remove columns. You can do this by using the ALTER TABLE statement. You can add, modify, and drop columns to a table by using the ALTER TABLE statement.

You use the ADD clause to add columns. SQL> ALTER TABLE EMP4 2 ADD HIREDATE DATE; Table altered. SQL> 2 3 4 5 6 7

ALTER TABLE EMP4 ADD ( COMM NUMBER(4), DEPTNO NUMBER(2), NIC VARCHAR2(13) );

Table altered. SQL> DESC EMP4 Name Null? ------------------------------- -------EMP_ID EMP_NAME JOB SALARY HIREDATE COMM DEPTNO NIC

Type ---NUMBER(4) VARCHAR2(10) VARCHAR2(9) NUMBER(7,2) DATE NUMBER(4) NUMBER(2) VARCHAR2(13)

You use the MODIFY clause to add columns. You can modify a column definition by using the ALTER TABLE statement with the MODIFY clause. Column modification can include changes to a column’s data type, size, and default value. SQL> ALTER TABLE EMP4 2 MODIFY COMM NUMBER(7,2); Table altered. SQL> 2 3 4 5 6

ALTER TABLE EMP4 MODIFY ( JOB VARCHAR2(10), NIC VARCHAR2(15) );

Table altered. 136

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

SQL> DESC EMP4 Name Null? ------------------------------- -------EMP_ID EMP_NAME JOB SALARY HIREDATE COMM DEPTNO NIC

Type ---NUMBER(4) VARCHAR2(10) VARCHAR2(10) NUMBER(7,2) DATE NUMBER(7,2) NUMBER(2) VARCHAR2(15)

Guidelines • You can increase the width or precision of a numeric column. • You can increase the width of numeric or character columns. • You can decrease the width of a column only if the column contains only null values or if the table has no rows. • You can change the data type only if the column contains null values. • You can convert a CHAR column to the VARCHAR2 data type or convert a VARCHAR2 column to the CHAR data type only if the column contains null values or if you do not change the size. • A change to the default value of a column affects only subsequent insertions to the table.

Dropping a Column You can drop a column from a table by using the ALTER TABLE statement with the DROP COLUMN clause. This is a feature available in Oracle8i and later. Guidelines • The column may or may not contain data. • Using the ALTER TABLE statement, only one column can be dropped at a time. • The table must have at least one column remaining in it after it is altered. • Once a column is dropped, it cannot be recovered. SQL> ALTER TABLE EMP4 2 DROP COLUMN HIREDATE; Table altered. SQL> ALTER TABLE EMP4 2 DROP (COMM); Table altered. SQL> ALTER TABLE EMP4 2 DROP (DEPTNO, SALARY, NIC); Table altered.

SQL> DESC EMP4 Name Null? ------------------------------- -------EMP_ID EMP_NAME JOB 137

Type ---NUMBER(4) VARCHAR2(10) VARCHAR2(10) [email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Dropping a Table The DROP TABLE statement removes the definition of an Oracle table. When you drop a table, the database loses all the data in the table and all the indexes associated with it. SQL> DROP TABLE EMP1; Table dropped.

Changing the Name of an Object SQL> RENAME EMP2 TO EMP222; Table renamed.

Truncating a Table Another DDL statement is the TRUNCATE TABLE statement, which is used to remove all rows from a table and to release the storage space used by that table. When using the TRUNCATE TABLE statement, you cannot roll back row removal. You must be the owner of the table or have DELETE TABLE system privileges to truncate a table. The DELETE statement can also remove all rows from a table, but it does not release storage space. The TRUNCATE command is faster. Removing rows with the TRUNCATE statement is faster than removing them with the DELETE statement for the following reasons: • The TRUNCATE statement is a data definition language (DDL) statement and generates no rollback information. • Truncating a table does not fire the delete triggers of the table. • If the table is the parent of a referential integrity constraint, you cannot truncate the table. Disable the constraint before issuing the TRUNCATE statement.

SQL> SELECT COUNT(*) FROM EMP222; COUNT(*) --------17 SQL> TRUNCATE TABLE EMP222; Table truncated. SQL> SELECT COUNT(*) FROM EMP222; COUNT(*) --------0

138

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Chapter 10

Including Constraints Constraints The Oracle Server uses constraints to prevent invalid data entry into tables. You can use constraints to do the following: • Enforce rules on the data in a table whenever a row is inserted, updated, or deleted from that table. The constraint must be satisfied for the operation to succeed. • Prevent the deletion of a table if there are dependencies from other tables • Provide rules for Oracle tools, such as Oracle Developer Constraints are usually created at the same time as the table. Constraints can be added to a table after its creation and also temporarily disabled. Constraints can be defined at one of two levels. • Column level constraint • Table level constraint flevel The NOT NULL constraint can be specified only at the column level, not at the table level. The following constraint types are valid: • NOT NULL • UNIQUE • PRIMARY KEY • FOREIGN KEY • CHECK Constraint Guidelines • •

• •

Name a constraint or the Oracle server generates a name by using the SYS_Cn format. Create a constraint either: – At the same time as the table is created, or – After the table has been created Define a constraint at the column or table level. View a constraint in the data dictionary.

Create DEPARTMENT table Define constraints at column level Do not provide constraint name because Oracle will provide constraints name SQL> 2 3 4 5 6

CREATE ( DEPTNO DNAME LOC );

TABLE DEPARTMENT NUMBER(2) PRIMARY KEY, VARCHAR2(10) NOT NULL, VARCHAR2(10) DEFAULT 'KARACHI'

Table created.

139

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Inserting into DEPARTMENT table SQL> INSERT INTO DEPARTMENT VALUES (1,'ADMIN','LAHORE'); 1 row created. SQL> INSERT INTO DEPARTMENT (DEPTNO, DNAME, LOC) VALUES (2,'ACCOUNTS','LAHORE'); 1 row created. SQL> INSERT INTO DEPARTMENT (DEPTNO, DNAME, LOC) VALUES (3,'IT',DEFAULT); 1 row created. SQL> INSERT INTO DEPARTMENT (DEPTNO, DNAME) VALUES (4,'AUDIT'); 1 row created.

SQL> DESC DEPARTMENT Name ------------------------------DEPTNO DNAME LOC

Null? -------NOT NULL NOT NULL

Type ---NUMBER(2) VARCHAR2(10) VARCHAR2(10)

SQL> SELECT * FROM DEPARTMENT; DEPTNO --------1 2 3 4

DNAME ---------ADMIN ACCOUNTS IT AUDIT

LOC ---------LAHORE LAHORE KARACHI KARACHI

Note the errors in the following queries and give the reason of errors SQL> INSERT INTO DEPARTMENT (DEPTNO, DNAME, LOC) VALUES (4,'PURCHASE','LAHORE'); INSERT INTO DEPARTMENT (DEPTNO, DNAME, LOC) VALUES (4,'PURCHASE','LAHORE') * ERROR at line 1: ORA-00001: unique constraint (SCOTT.SYS_C0011127) violated

SQL> INSERT INTO DEPARTMENT (DEPTNO, DNAME, LOC) VALUES (NULL,'PURCHASE','LAHORE'); INSERT INTO DEPARTMENT (DEPTNO, DNAME, LOC) VALUES (NULL,'PURCHASE','LAHORE') * ERROR at line 1: ORA-01400: cannot insert NULL into ("SCOTT"."DEPARTMENT"."DEPTNO")

SQL> INSERT INTO DEPARTMENT (DEPTNO, DNAME, LOC) VALUES (5,NULL,'LAHORE'); INSERT INTO DEPARTMENT (DEPTNO, DNAME, LOC) VALUES (5,NULL,'LAHORE') * ERROR at line 1: ORA-01400: cannot insert NULL into ("SCOTT"."DEPARTMENT"."DNAME") 140

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Use the following data dictionary views for viewing constraints information SQL> DESC USER_CONSTRAINTS Name ------------------------------OWNER CONSTRAINT_NAME CONSTRAINT_TYPE TABLE_NAME SEARCH_CONDITION R_OWNER R_CONSTRAINT_NAME DELETE_RULE STATUS DEFERRABLE DEFERRED VALIDATED GENERATED BAD RELY LAST_CHANGE INDEX_OWNER INDEX_NAME INVALID VIEW_RELATED SQL> DESC USER_CONS_COLUMNS Name ------------------------------OWNER CONSTRAINT_NAME TABLE_NAME COLUMN_NAME POSITION

Null? -------NOT NULL NOT NULL

Type ---VARCHAR2(30) VARCHAR2(30) VARCHAR2(1) NOT NULL VARCHAR2(30) LONG VARCHAR2(30) VARCHAR2(30) VARCHAR2(9) VARCHAR2(8) VARCHAR2(14) VARCHAR2(9) VARCHAR2(13) VARCHAR2(14) VARCHAR2(3) VARCHAR2(4) DATE VARCHAR2(30) VARCHAR2(30) VARCHAR2(7) VARCHAR2(14)

Null? -------NOT NULL NOT NULL NOT NULL

Type ---VARCHAR2(30) VARCHAR2(30) VARCHAR2(30) VARCHAR2(4000) NUMBER

View constraints information of DEPARTMENT table by using data dictionary views: You can view constraints information by using user_constraints but you can not view the column names for which constraints are used. SQL> SELECT CONSTRAINT_NAME, CONSTRAINT_TYPE 2 FROM USER_CONSTRAINTS 3 WHERE TABLE_NAME='DEPARTMENT'; CONSTRAINT_NAME -----------------------------SYS_C0011126 SYS_C0011127

C C P

You have to use user_cons_columns if you want to view column name for which constraints are used but you can not view constraints type by user_cons_columns. SQL> SQL> 2 3

COL COLUMN_NAME FORMAT A15 SELECT CONSTRAINT_NAME, COLUMN_NAME, POSITION FROM USER_CONS_COLUMNS WHERE TABLE_NAME='DEPARTMENT';

CONSTRAINT_NAME -----------------------------SYS_C0011126 SYS_C0011127

COLUMN_NAME POSITION --------------- --------DNAME DEPTNO 1 141

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

If you want to view complete constraint information including constraints type and column information then you have to join user_constraints and user_cons_columns. SQL> SELECT T.CONSTRAINT_NAME, C.COLUMN_NAME, T.CONSTRAINT_TYPE 2 FROM USER_CONSTRAINTS T, USER_CONS_COLUMNS C 3 WHERE C.CONSTRAINT_NAME=T.CONSTRAINT_NAME AND 4 C.TABLE_NAME=T.TABLE_NAME AND 5 T.TABLE_NAME='DEPARTMENT'; CONSTRAINT_NAME -----------------------------SYS_C0011126 SYS_C0011127

COLUMN_NAME --------------DNAME DEPTNO

C C P

Create EMPLOYEE table Define constraints at column level Do not provide constraint name because Oracle will provide constraints name SQL> 2 3 4 5 6 7 8 9 10 11

CREATE TABLE EMPLOYEE ( EMP_ID NUMBER(4) PRIMARY KEY, FIRST_NAME VARCHAR2(10) NOT NULL, LAST_NAME VARCHAR2(10), JOIN_DATE DATE DEFAULT SYSDATE, DESG VARCHAR2(20) DEFAULT 'CLERK', SALARY NUMBER(7,2) CHECK (SALARY BETWEEN 500 AND 99999), NIC VARCHAR2(20) UNIQUE, DEPTNO NUMBER(02) REFERENCES DEPARTMENT (DEPTNO) );

Table created. SQL> DESC EMPLOYEE Name ------------------------------EMP_ID FIRST_NAME LAST_NAME JOIN_DATE DESG SALARY NIC DEPTNO

Null? -------NOT NULL NOT NULL

Type ---NUMBER(4) VARCHAR2(10) VARCHAR2(10) DATE VARCHAR2(20) NUMBER(7,2) VARCHAR2(20) NUMBER(2)

View constraints information of EMPLOYEE table by using data dictionary views: SQL> SELECT T.CONSTRAINT_NAME, C.COLUMN_NAME, T.CONSTRAINT_TYPE 2 FROM USER_CONSTRAINTS T, USER_CONS_COLUMNS C 3 WHERE C.CONSTRAINT_NAME=T.CONSTRAINT_NAME AND 4 C.TABLE_NAME=T.TABLE_NAME AND 5 T.TABLE_NAME='EMPLOYEE'; CONSTRAINT_NAME -----------------------------SYS_C0011128 SYS_C0011129 SYS_C0011130 SYS_C0011131 SYS_C0011132

COLUMN_NAME --------------FIRST_NAME SALARY EMP_ID NIC DEPTNO 142

C C C P U R [email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Create EMPLOYEE2 table with user defined constraint name Define constraints at column level SQL> 2 3 4 5 6 7 8 9 10 11 12 13

CREATE TABLE EMPLOYEE2 ( EMP_ID NUMBER(4) CONSTRAINT EMPLOYEE2_EMP_ID_PK PRIMARY KEY, FIRST_NAME VARCHAR2(10) CONSTRAINT EMPLOYEE2_FIRSTNAME_NN NOT NULL, LAST_NAME VARCHAR2(10), JOIN_DATE DATE DEFAULT SYSDATE, DESG VARCHAR2(20) DEFAULT 'CLERK', SALARY NUMBER(7,2) CONSTRAINT EMPLOYEE2_SALARY_C CHECK (SALARY BETWEEN 500 AND 99999), NIC VARCHAR2(20) CONSTRAINT EMPLOYEE2_NIC_U UNIQUE, DEPTNO NUMBER(02) CONSTRAINT EMPLOYEE2_DEPTNO_FK REFERENCES DEPARTMENT (DEPTNO) );

Table created.

View constraints information of EMPLOYEE2 table by using data dictionary views: SQL> SELECT T.CONSTRAINT_NAME, C.COLUMN_NAME, T.CONSTRAINT_TYPE 2 FROM USER_CONSTRAINTS T, USER_CONS_COLUMNS C 3 WHERE C.CONSTRAINT_NAME=T.CONSTRAINT_NAME AND 4 C.TABLE_NAME=T.TABLE_NAME AND 5 T.TABLE_NAME='EMPLOYEE2'; CONSTRAINT_NAME -----------------------------EMPLOYEE2_FIRSTNAME_NN EMPLOYEE2_SALARY_C EMPLOYEE2_EMP_ID_PK EMPLOYEE2_NIC_U EMPLOYEE2_DEPTNO_FK

COLUMN_NAME --------------FIRST_NAME SALARY EMP_ID NIC DEPTNO

C C C P U R

Inserting into EMPLOYEE2 table SQL> INSERT INTO EMPLOYEE2 2 (EMP_ID, FIRST_NAME, LAST_NAME, JOIN_DATE, DESG, SALARY, NIC, DEPTNO) 3 VALUES 4 (1,'MUHAMMAD','RAHEEM',DEFAULT,'SOFTWARE ENGINEER',50000,'12345-12345671',3); 1 row created.

Note the errors in the following queries and give the reason of errors SQL> INSERT INTO EMPLOYEE2 2 (EMP_ID, FIRST_NAME, LAST_NAME, JOIN_DATE, DESG, SALARY, NIC, DEPTNO) 3 VALUES 4 (1,'MUHAMMAD','ASLAM',DEFAULT,DEFAULT,40000,NULL,3); INSERT INTO EMPLOYEE2 * ERROR at line 1: ORA-00001: unique constraint (SCOTT.EMPLOYEE2_EMP_ID_PK) violated 143

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

SQL> INSERT INTO EMPLOYEE2 2 (EMP_ID, FIRST_NAME, LAST_NAME, JOIN_DATE, DESG, SALARY, NIC, DEPTNO) 3 VALUES 4 (2,NULL,'ASLAM',DEFAULT,DEFAULT,40000,NULL,3); (2,NULL,'ASLAM',DEFAULT,DEFAULT,40000,NULL,3) * ERROR at line 4: ORA-01400: cannot insert NULL into ("SCOTT"."EMPLOYEE2"."FIRST_NAME")

SQL> INSERT INTO EMPLOYEE2 2 (EMP_ID, FIRST_NAME, LAST_NAME, JOIN_DATE, DESG, SALARY, NIC, DEPTNO) 3 VALUES 4 (2,'MUHAMMAD','ASLAM',DEFAULT,DEFAULT,400,NULL,3); INSERT INTO EMPLOYEE2 * ERROR at line 1: ORA-02290: check constraint (SCOTT.EMPLOYEE2_SALARY_C) violated

SQL> INSERT INTO EMPLOYEE2 2 (EMP_ID, FIRST_NAME, LAST_NAME, JOIN_DATE, DESG, SALARY, NIC, DEPTNO) 3 VALUES 4 (2,'MUHAMMAD','ASLAM',DEFAULT,DEFAULT,40000,'12345-1234567-1',3); INSERT INTO EMPLOYEE2 * ERROR at line 1: ORA-00001: unique constraint (SCOTT.EMPLOYEE2_NIC_U) violated

SQL> INSERT INTO EMPLOYEE2 2 (EMP_ID, FIRST_NAME, LAST_NAME, JOIN_DATE, DESG, SALARY, NIC, DEPTNO) 3 VALUES 4 (2,'MUHAMMAD','ASLAM',DEFAULT,DEFAULT,40000,NULL,5); INSERT INTO EMPLOYEE2 * ERROR at line 1: ORA-02291: integrity constraint (SCOTT.EMPLOYEE2_DEPTNO_FK) violated - parent key not found

SQL> 2 3 4

INSERT INTO EMPLOYEE2 (EMP_ID, FIRST_NAME, LAST_NAME, JOIN_DATE, DESG, SALARY, NIC, DEPTNO) VALUES (2,'MUHAMMAD','ASLAM',DEFAULT,DEFAULT,40000,NULL,1);

1 row created.

SQL> SELECT EMP_ID, JOIN_DATE, DESG, SALARY, NIC, DEPTNO FROM EMPLOYEE2; EMP_ID --------1 2

JOIN_DATE --------06-AUG-08 06-AUG-08

DESG SALARY NIC DEPTNO ----------------- --------- --------------- --------SOFTWARE ENGINEER 50000 12345-1234567-1 3 CLERK 40000 1

SQL> 144

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Create EMPLOYEE3 table with user defined constraint name Define constraints at table level SQL> 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

CREATE TABLE EMPLOYEE3 ( EMP_ID NUMBER(4), FIRST_NAME VARCHAR2(10) CONSTRAINT EMPLOYEE3_FIRSTNAME_NN NOT NULL, LAST_NAME VARCHAR2(10), JOIN_DATE DATE DEFAULT SYSDATE, DESG VARCHAR2(20) DEFAULT 'CLERK', SALARY NUMBER(7,2), NIC VARCHAR2(20), DEPTNO NUMBER(02), CONSTRAINT EMPLOYEE3_EMP_ID_PK PRIMARY KEY (EMP_ID), CONSTRAINT EMPLOYEE3_SALARY_C CHECK (SALARY BETWEEN 500 AND 99999), CONSTRAINT EMPLOYEE3_NIC_U UNIQUE (NIC), CONSTRAINT EMPLOYEE3_DEPTNO_FK FOREIGN KEY (DEPTNO) REFERENCES DEPARTMENT (DEPTNO) );

Table created. View constraints information of EMPLOYEE3 table by using data dictionary views: SQL> SELECT T.CONSTRAINT_NAME, C.COLUMN_NAME, T.CONSTRAINT_TYPE 2 FROM USER_CONSTRAINTS T, USER_CONS_COLUMNS C 3 WHERE C.CONSTRAINT_NAME=T.CONSTRAINT_NAME AND 4 C.TABLE_NAME=T.TABLE_NAME AND 5 T.TABLE_NAME='EMPLOYEE3'; CONSTRAINT_NAME -----------------------------EMPLOYEE3_FIRSTNAME_NN EMPLOYEE3_SALARY_C EMPLOYEE3_EMP_ID_PK EMPLOYEE3_NIC_U EMPLOYEE3_DEPTNO_FK

COLUMN_NAME --------------FIRST_NAME SALARY EMP_ID NIC DEPTNO

C C C P U R

Dropping a Constraint To drop a constraint, you can identify the constraint name from the USER_CONSTRAINTS and USER_CONS_COLUMNS data dictionary views. Then use the ALTER TABLE statement with the DROP clause. The CASCADE option of the DROP clause causes any dependent constraints also to be dropped. SQL> ALTER TABLE EMPLOYEE3 2 DROP CONSTRAINT EMPLOYEE3_NIC_U; Table altered. SQL> ALTER TABLE EMPLOYEE3 2 DROP CONSTRAINT EMPLOYEE3_FIRSTNAME_NN; Table altered. SQL> ALTER TABLE EMPLOYEE3 2 DROP CONSTRAINT EMPLOYEE3_DEPTNO_FK; 145

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

View constraints information of EMPLOYEE3 table after dropping EMPLOYEE3_NIC_U and EMPLOYEE3_FIRSTNAME_NN; SQL> SELECT T.CONSTRAINT_NAME, C.COLUMN_NAME, T.CONSTRAINT_TYPE 2 FROM USER_CONSTRAINTS T, USER_CONS_COLUMNS C 3 WHERE C.CONSTRAINT_NAME=T.CONSTRAINT_NAME AND 4 C.TABLE_NAME=T.TABLE_NAME AND 5 T.TABLE_NAME='EMPLOYEE3'; CONSTRAINT_NAME -----------------------------EMPLOYEE3_SALARY_C EMPLOYEE3_EMP_ID_PK

COLUMN_NAME --------------SALARY EMP_ID

C C P

Adding a Constraint You can add a constraint for existing tables by using the ALTER TABLE statement with the ADD clause. SQL> ALTER TABLE EMPLOYEE3 2 ADD CONSTRAINT EMP3_NIC_U UNIQUE (NIC); Table altered.

SQL> ALTER TABLE EMPLOYEE3 2 ADD CONSTRAINT EMP3_DEPTNO_FK FOREIGN KEY (DEPTNO) 3 REFERENCES DEPARTMENT (DEPTNO); Table altered.

SQL> ALTER TABLE EMPLOYEE3 2 MODIFY FIRST_NAME CONSTRAINT EMP3_FIRSTNAME_NN NOT NULL; Table altered.

SQL> SELECT T.CONSTRAINT_NAME, C.COLUMN_NAME, T.CONSTRAINT_TYPE 2 FROM USER_CONSTRAINTS T, USER_CONS_COLUMNS C 3 WHERE C.CONSTRAINT_NAME=T.CONSTRAINT_NAME AND 4 C.TABLE_NAME=T.TABLE_NAME AND 5 T.TABLE_NAME='EMPLOYEE3'; CONSTRAINT_NAME -----------------------------EMP3_NIC_U EMPLOYEE3_SALARY_C EMPLOYEE3_EMP_ID_PK EMP3_DEPTNO_FK EMP3_FIRSTNAME_NN

COLUMN_NAME --------------NIC SALARY EMP_ID DEPTNO FIRST_NAME

C U C P R C

SQL> ALTER TABLE EMPLOYEE3 2 DROP CONSTRAINT EMPLOYEE3_SALARY_C; Table altered. SQL> ALTER TABLE EMPLOYEE3 146

[email protected]

Prepared by Muhammad Raheem

Oracle SQL 2

Phone: 021-4265550, Cell: 0321-4265550

DROP CONSTRAINT EMPLOYEE3_EMP_ID_PK;

Disabling Constraints You can disable a constraint without dropping it or re-creating it by using the ALTER TABLE statement with the DISABLE clause. SQL> ALTER TABLE EMPLOYEE3 2 DISABLE CONSTRAINT EMP3_NIC_U; Table altered. SQL> SELECT T.CONSTRAINT_NAME, C.COLUMN_NAME, T.CONSTRAINT_TYPE, T.STATUS 2 FROM USER_CONSTRAINTS T, USER_CONS_COLUMNS C 3 WHERE C.CONSTRAINT_NAME=T.CONSTRAINT_NAME AND 4 C.TABLE_NAME=T.TABLE_NAME AND 5 T.TABLE_NAME='EMPLOYEE3'; CONSTRAINT_NAME -----------------------------EMP3_NIC_U EMP3_DEPTNO_FK EMP3_FIRSTNAME_NN

COLUMN_NAME --------------NIC DEPTNO FIRST_NAME

C U R C

STATUS -------DISABLED ENABLED ENABLED

Enabling Constraints You can enable a constraint without dropping it or re-creating it by using the ALTER TABLE statement with the ENABLE clause. SQL> ALTER TABLE EMPLOYEE3 2 ENABLE CONSTRAINT EMP3_NIC_U; Table altered. SQL> SELECT T.CONSTRAINT_NAME, C.COLUMN_NAME, T.CONSTRAINT_TYPE, T.STATUS 2 FROM USER_CONSTRAINTS T, USER_CONS_COLUMNS C 3 WHERE C.CONSTRAINT_NAME=T.CONSTRAINT_NAME AND 4 C.TABLE_NAME=T.TABLE_NAME AND 5 T.TABLE_NAME='EMPLOYEE3'; CONSTRAINT_NAME -----------------------------EMP3_NIC_U EMP3_DEPTNO_FK EMP3_FIRSTNAME_NN

COLUMN_NAME --------------NIC DEPTNO FIRST_NAME

C U R C

STATUS -------ENABLED ENABLED ENABLED

Cascading Constraints SQL> ALTER TABLE DEPARTMENT 2 DROP (DEPTNO); DROP (DEPTNO) * ERROR at line 2: ORA-12992: cannot drop parent key column SQL> ALTER TABLE DEPARTMENT 2 DROP (DEPTNO) CASCADE CONSTRAINT; Table altered. 147

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Chapter 11

Creating Views You can present logical subsets or combinations of data by creating views of tables. A view is a logical table based on a table or another view. A view contains no data of its own but is like a window through which data from tables can be viewed or changed. The tables on which a view is based are called base tables. The view is stored as a SELECT statement in the data dictionary. Advantages of Views • Views restrict access to the data because the view can display selective columns from the table. • Views can be used to make simple queries to retrieve the results of complicated queries. For example, views can be used to query information from multiple tables without the user knowing how to write a join statement. • Views provide data independence for ad hoc users and application programs. One view can be used to retrieve data from several tables. • Views provide groups of users access to data according to their particular criteria. Simple Views versus Complex Views There are two classifications for views: simple and complex. The basic difference is related to the DML (INSERT, UPDATE, and DELETE) operations. • A simple view is one that: • Derives data from only one table • Contains no functions or groups of data • Can perform DML operations through the view • A complex view is one that: • Derives data from many tables • Contains functions or groups of data • Does not always allow DML operations through the view The following query will create a view based on EMP table having only six columns. The view is created for restricting users from view salary and commission information.

The CREATE VIEW statement SQL> CREATE VIEW EMP_V1 2 AS SELECT EMPNO, ENAME, JOB, MGR, HIREDATE, DEPTNO FROM EMP; View created. Display structure of a view SQL> DESC EMP_V1 Name Null? ------------------------------- -------EMPNO NOT NULL ENAME JOB MGR HIREDATE DEPTNO

148

Type ---NUMBER(4) VARCHAR2(10) VARCHAR2(9) NUMBER(4) DATE NUMBER(2)

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Retrieving data using view SQL> SELECT * FROM EMP_V1; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934 1 2 3

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER SCOTT ASLAM SALEEM

JOB MGR HIREDATE DEPTNO --------- --------- --------- --------CLERK 7902 17-DEC-80 20 SALESMAN 7698 20-FEB-81 30 SALESMAN 7698 22-FEB-81 30 MANAGER 7839 02-APR-81 20 SALESMAN 7698 28-SEP-81 30 MANAGER 7839 01-MAY-81 30 MANAGER 7839 09-JUN-81 10 ANALYST 7566 19-APR-87 20 PRESIDENT 17-NOV-81 10 SALESMAN 7698 08-SEP-81 30 CLERK 7788 23-MAY-87 20 CLERK 7698 03-DEC-81 30 ANALYST 7566 03-DEC-81 20 CLERK 7782 23-JAN-82 10 CLERK 2 06-AUG-08 55 MANAGER 7839 28-JUL-08 55 ASST IT 2 10-JAN-07 55

17 rows selected.

Inserting using view SQL> 2 3 4

INSERT INTO EMP_V1 (EMPNO, ENAME, JOB, DEPTNO) VALUES (4, 'ZIA','CLERK',10);

1 row created. You inserted into EMP table through EMP_V1 SQL> SELECT * FROM EMP; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 4 7934 1 2 3

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD ZIA MILLER SCOTT ASLAM SALEEM

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 MANAGER 7839 02-APR-81 2975 20 SALESMAN 7698 28-SEP-81 1250 1400 30 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 SALESMAN 7698 08-SEP-81 1500 0 30 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 ANALYST 7566 03-DEC-81 3000 20 CLERK 10 CLERK 7782 23-JAN-82 1300 10 CLERK 2 06-AUG-08 1000 55 MANAGER 7839 28-JUL-08 2975 55 ASST IT 2 10-JAN-07 2300 55

18 rows selected. 149

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Modifying a View With the OR REPLACE option, a view can be created even if one exists with this name already, thus replacing the old version of the view for its owner. This means that the view can be altered without dropping, re-creating, and regranting object privileges. The following view has been creating to view employee department # 10.

SQL> CREATE OR REPLACE VIEW EMP_VIEW_D10 2 AS SELECT * FROM EMP WHERE DEPTNO=10; View created. SQL> DESC EMP_VIEW_D10 Name Null? ------------------------------- -------EMPNO NOT NULL ENAME JOB MGR HIREDATE SAL COMM DEPTNO

Type ---NUMBER(4) VARCHAR2(10) VARCHAR2(9) NUMBER(4) DATE NUMBER(7,2) NUMBER(7,2) NUMBER(2)

SQL> SELECT * FROM EMP_VIEW_D10; EMPNO --------7782 7839 7934

ENAME ---------CLARK KING MILLER

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 09-JUN-81 2450 10 PRESIDENT 17-NOV-81 5000 10 CLERK 7782 23-JAN-82 1300 10

You can add an alias for each column name.

SQL> 2 3 4

CREATE OR REPLACE VIEW EMP_V2 (EMP_ID, EMP_NAME, DESG, SALARY, DEPT_ID) AS SELECT EMPNO, ENAME, JOB, SAL, DEPTNO FROM EMP WHERE SAL>2000;

View created. SQL> DESC EMP_V2 Name Null? ------------------------------- -------EMP_ID NOT NULL EMP_NAME DESG SALARY DEPT_ID

Type ---NUMBER(4) VARCHAR2(10) VARCHAR2(9) NUMBER(7,2) NUMBER(2)

SQL> SELECT * FROM EMP_V2; EMP_ID --------7566 7698 7782 7788 7839 7902 2 3

EMP_NAME ---------JONES BLAKE CLARK SCOTT KING FORD ASLAM SALEEM

DESG SALARY DEPT_ID ----------------- --------- --------MANAGER 2975 20 MANAGER 2850 30 MANAGER 2450 10 ANALYST 3000 20 PRESIDENT 5000 10 ANALYST 3000 20 MANAGER 2975 55 ASST IT 2300 55

8 rows selected. 150

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Creating a Complex View Create a complex view that contains display values from two tables. SQL> 2 3 4

CREATE OR REPLACE VIEW EMP_DEPT AS SELECT E.EMPNO, E.ENAME, E.JOB, E.DEPTNO, D.DNAME, D.LOC FROM EMP E, DEPT D WHERE E.DEPTNO=D.DEPTNO;

View created. SQL> SELECT * FROM EMP_DEPT; EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 4 7934 1 2 3

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD ZIA MILLER SCOTT ASLAM SALEEM

JOB DEPTNO DNAME --------- --------- -------------CLERK 20 RESEARCH SALESMAN 30 SALES SALESMAN 30 SALES MANAGER 20 RESEARCH SALESMAN 30 SALES MANAGER 30 SALES MANAGER 10 ACCOUNTING ANALYST 20 RESEARCH PRESIDENT 10 ACCOUNTING SALESMAN 30 SALES CLERK 20 RESEARCH CLERK 30 SALES ANALYST 20 RESEARCH CLERK 10 ACCOUNTING CLERK 10 ACCOUNTING CLERK 55 IT MANAGER 55 IT ASST IT 55 IT

LOC ------------DALLAS CHICAGO CHICAGO DALLAS CHICAGO CHICAGO NEW YORK DALLAS NEW YORK CHICAGO DALLAS CHICAGO DALLAS NEW YORK NEW YORK KARACHI KARACHI KARACHI

18 rows selected. Create a complex view that contains group functions to display summary information. SQL> 2 3 4

CREATE OR REPLACE VIEW DEPT_SUMMARY AS SELECT DEPTNO, COUNT(*) CNT, SUM(SAL) SUM_SAL, AVG(SAL) AVG_SAL FROM EMP GROUP BY DEPTNO;

View created. SQL> SELECT * FROM DEPT_SUMMARY; DEPTNO CNT SUM_SAL AVG_SAL --------- --------- --------- --------30 6 9400 1566.6667 20 5 10875 2175 55 3 6275 2091.6667 10 4 8750 2916.6667 SQL> CREATE OR REPLACE VIEW AVAILABLE_JOBS AS 2 SELECT DISTINCT JOB FROM EMP; View created. SQL> SELECT * FROM AVAILABLE_JOBS; JOB --------CLERK SALESMAN PRESIDENT MANAGER ANALYST 151

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

ASST IT

Removing a View You use the DROP VIEW statement to remove a view. The statement removes the view definition from the database. Dropping views has no effect on the tables on which the view was based. Views or other applications based on deleted views become invalid. SQL> DROP VIEW EMP_V1; View dropped.

Inline Views • • •

An inline view is a subquery with an alias (or correlation name) that you can use within a SQL statement. A named subquery in the FROM clause of the main query is an example of an inline view. An inline view is not a schema object.

SQL> SELECT EMP_ID, EMP_NAME, DESG 2 FROM (SELECT EMPNO EMP_ID, ENAME EMP_NAME, JOB DESG 3 FROM EMP WHERE DEPTNO=10) A; EMP_ID --------7782 7839 4 7934

EMP_NAME ---------CLARK KING ZIA MILLER

DESG ----------------MANAGER PRESIDENT CLERK CLERK

Top-N Analysis •



Top-N queries ask for the n largest or smallest values of a column. For example: – What are the ten best selling products? – What are the ten worst selling products? Both largest values and smallest values sets are considered Top-N queries.

To display the top three earner names and salaries from the EMP table: SQL> SELECT ROWNUM SNO, ENAME, SAL, DEPTNO 2 FROM ( SELECT ENAME, SAL, DEPTNO 3 FROM EMP WHERE SAL IS NOT NULL 4 ORDER BY SAL DESC ) 5 WHERE ROWNUM CREATE SEQUENCE S1; Sequence created.

Using a Sequence After you create your sequence, it generates sequential numbers for use in your tables. Reference the sequence values by using the NEXTVAL and CURRVAL pseudocolumns.

NEXTVAL and CURRVAL Pseudocolumns • •

NEXTVAL returns the next available sequence value. It returns a unique value every time it is referenced, even for different users. CURRVAL obtains the current sequence value.

SQL> SELECT S1.NEXTVAL FROM DUAL; NEXTVAL --------1 SQL> SELECT S1.NEXTVAL FROM DUAL; NEXTVAL --------2 SQL> SELECT S1.CURRVAL FROM DUAL; CURRVAL --------2 SQL> SELECT S1.NEXTVAL FROM DUAL; NEXTVAL --------3 153

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

SQL> 2 3 4

Phone: 021-4265550, Cell: 0321-4265550

CREATE SEQUENCE S2 START WITH 10 INCREMENT BY 2 MAXVALUE 15;

Sequence created.

SQL> SELECT S2.NEXTVAL FROM DUAL; NEXTVAL --------10 SQL> SELECT S2.NEXTVAL FROM DUAL; NEXTVAL --------12 SQL> SELECT S2.NEXTVAL FROM DUAL; NEXTVAL --------14 SQL> SELECT S2.NEXTVAL FROM DUAL; SELECT S2.NEXTVAL FROM DUAL * ERROR at line 1: ORA-08004: sequence S2.NEXTVAL exceeds MAXVALUE and cannot be instantiated

SQL> SELECT S2.CURRVAL FROM DUAL; CURRVAL --------14

Confirming Sequences Once you have created your sequence, it is documented in the data dictionary. Since a sequence is a database object, you can identify it in the USER_OBJECTS data dictionary table. You can also confirm the settings of the sequence by selecting from the USER_SEQUENCES data dictionary view. SQL> SELECT SEQUENCE_NAME, MIN_VALUE, INCREMENT_BY, LAST_NUMBER FROM USER_SEQUENCES; SEQUENCE_NAME MIN_VALUE INCREMENT_BY LAST_NUMBER ------------------------------ --------- ------------ ----------S1 1 1 21 S2 1 2 16

154

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Modifying a Sequence Altering a Sequence If you reach the MAXVALUE limit for your sequence, no additional values from the sequence are allocated and you will receive an error indicating that the sequence exceeds the MAXVALUE. To continue to use the sequence, you can modify it by using the ALTER SEQUENCE statement. SQL> ALTER SEQUENCE S2 MAXVALUE 100; Sequence altered. SQL> SELECT S2.NEXTVAL FROM DUAL; NEXTVAL --------16 SQL> SELECT S2.NEXTVAL FROM DUAL; NEXTVAL --------18 Guidelines for Modifying Sequences • You must be the owner or have the ALTER privilege for the sequence in order to modify it. • Only future sequence numbers are affected by the ALTER SEQUENCE statement. • The START WITH option cannot be changed using ALTER SEQUENCE. The sequence must be dropped and re-created in order to restart the sequence at a different number. • Some validation is performed. For example, a new MAXVALUE that is less than the current sequence number cannot be imposed. SQL> ALTER SEQUENCE S2 2 MAXVALUE 5000 3 INCREMENT BY 5 4 CYCLE; Sequence altered. SQL> SELECT S2.NEXTVAL FROM DUAL; NEXTVAL --------23 SQL> ALTER SEQUENCE S2 NOCYCLE; Sequence altered. CYCLE | NOCYCLE

specifies whether the sequence continues to generate values after reaching its maximum or minimum value (NOCYCLE is the default option.)

SQL> ALTER SEQUENCE S2 INCREMENT BY -5 MINVALUE 1 CYCLE; Sequence altered. SQL> SELECT S2.NEXTVAL FROM DUAL; NEXTVAL --------155

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

18

Using a Sequence SQL> CREATE SEQUENCE S3 MAXVALUE 9; Sequence created. SQL> 2 3 4

INSERT INTO DEPT (DEPTNO, DNAME, LOC) VALUES (S3.NEXTVAL, 'MAINTENANCE','KARACHI');

1 row created. SQL> / 1 row created. SQL> SELECT * FROM DEPT; DEPTNO --------1 2 10 20 30 40 55 60 65

DNAME -------------MAINTENANCE MAINTENANCE ACCOUNTING RESEARCH SALES OPERATIONS IT PURCHASE AUDIT

LOC ------------KARACHI KARACHI NEW YORK DALLAS CHICAGO BOSTON KARACHI

9 rows selected.

SQL> ROLLBACK; Rollback complete. SQL> CREATE SEQUENCE S4; Sequence created. SQL> ALTER TABLE EMP ADD SNO NUMBER(4); Table altered. SQL> UPDATE EMP SET SNO=S4.NEXTVAL WHERE DEPTNO=10; 4 rows updated. SQL> SELECT EMPNO, ENAME, JOB, SAL, DEPTNO, SNO FROM EMP WHERE DEPTNO=10; EMPNO --------7782 7839 4 7934

ENAME ---------CLARK KING ZIA MILLER

JOB SAL DEPTNO SNO --------- --------- --------- --------MANAGER 2450 10 1 PRESIDENT 5000 10 2 CLERK 10 3 CLERK 1300 10 4

SQL> ALTER TABLE EMP DROP COLUMN SNO; 156

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Table altered.

SQL> 2 3 4

CREATE TABLE EMP_SEQ AS SELECT S5.NEXTVAL EMPNO, ENAME, JOB, SAL, DEPTNO FROM EMP;

Table created. SQL> SELECT * FROM EMP_SEQ; EMPNO --------1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD ZIA MILLER SCOTT ASLAM SALEEM

JOB SAL DEPTNO --------- --------- --------CLERK 800 20 SALESMAN 1600 30 SALESMAN 1250 30 MANAGER 2975 20 SALESMAN 1250 30 MANAGER 2850 30 MANAGER 2450 10 ANALYST 3000 20 PRESIDENT 5000 10 SALESMAN 1500 30 CLERK 1100 20 CLERK 950 30 ANALYST 3000 20 CLERK 10 CLERK 1300 10 CLERK 1000 55 MANAGER 2975 55 ASST IT 2300 55

18 rows selected.

SQL> INSERT INTO EMP_SEQ VALUES (S5.NEXTVAL, 'WAQAS','SYS. ADM',35000,10); 1 row created. SQL> SELECT * FROM EMP_SEQ WHERE ENAME='WAQAS'; EMPNO ENAME JOB SAL DEPTNO --------- ---------- --------- --------- --------19 WAQAS SYS. ADM 35000 10 Gaps in the Sequence Although sequence generators issue sequential numbers without gaps, this action occurs independent of a commit or rollback. Therefore, if you roll back a statement containing a sequence, the number is lost. Another event that can cause gaps in the sequence is a system crash. If the sequence caches values in the memory, then those values are lost if the system crashes. Because sequences are not tied directly to tables, the same sequence can be used for multiple tables. If you do so, each table can contain gaps in the sequential numbers. Removing a Sequence SQL> DROP SEQUENCE S5; 157

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Sequence dropped.

Index An Oracle server index is a schema object that can speed up the retrieval of rows by using a pointer. Indexes can be created explicitly or automatically. If you do not have an index on the column, then a full table scan occurs. An index provides direct and fast access to rows in a table. Its purpose is to reduce the necessity of disk I/O by using an indexed path to locate data quickly. The index is used and maintained automatically by the Oracle server. Once an index is created, no direct activity is required by the user. Indexes are logically and physically independent of the table they index. This means that they can be created or dropped at any time and have no effect on the base tables or other indexes. Note: When you drop a table, corresponding indexes are also dropped. Types of Indexes •

Automatically: A unique index is created automatically when you define a PRIMARY KEY or UNIQUE constraint in a table definition.



Manually: Users can create nonunique indexes on columns to speed up access to the rows.

Note: You can manually create a unique index, but it is recommended that you create a unique constraint, which implicitly creates a unique index.

Creating an Index Create an index on one or more columns by issuing the CREATE INDEX statement. Automatically index creation: Add a new column NIC in EMP table, Add a unique constraint on NIC column Unique index will be created automatically SQL> ALTER TABLE EMP 2 ADD NIC VARCHAR2(15) CONSTRAINT EMP_NIC_U UNIQUE; Table altered. Manually index creation: Create an index on ENAME to improve the speed of query access to the ENAME column in the EMP table. SQL> CREATE INDEX INDX_EMP_ENAME 2 ON EMP (ENAME); Index created. Create an index on SAL, COMM to improve the speed of query access. SQL> CREATE INDEX INDX_EMP_SAL_COMM 2 ON EMP (SAL,COMM); 158

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Index created. Confirming Indexes Confirm the existence of indexes from the USER_INDEXES data dictionary view. SQL> SELECT INDEX_NAME, INDEX_TYPE, UNIQUENESS 2 FROM USER_INDEXES WHERE TABLE_NAME='EMP'; INDEX_NAME -----------------------------PK_EMP INDX_EMP_ENAME EMP_NIC_U INDX_EMP_SAL_COMM

INDEX_TYPE --------------------------NORMAL NORMAL NORMAL NORMAL

UNIQUENES --------UNIQUE NONUNIQUE UNIQUE NONUNIQUE

You can also check the columns involved in an index by querying the USER_IND_COLUMNS view. SQL> COL COLUMN_NAME FORMAT A15 SQL> SELECT INDEX_NAME, COLUMN_NAME, COLUMN_POSITION 2 FROM USER_IND_COLUMNS WHERE TABLE_NAME='EMP'; INDEX_NAME -----------------------------PK_EMP INDX_EMP_ENAME EMP_NIC_U INDX_EMP_SAL_COMM INDX_EMP_SAL_COMM

COLUMN_NAME COLUMN_POSITION --------------- --------------EMPNO 1 ENAME 1 NIC 1 SAL 1 COMM 2

I want to retrieve index information in one query from the above data dictionary. SQL> SELECT T.INDEX_NAME, C.COLUMN_NAME, C.COLUMN_POSITION, T.UNIQUENESS 2 FROM USER_INDEXES T, USER_IND_COLUMNS C 3 WHERE T.INDEX_NAME=C.INDEX_NAME AND 4 T.TABLE_NAME=C.TABLE_NAME AND 5 T.TABLE_NAME='EMP'; INDEX_NAME -------------------PK_EMP INDX_EMP_ENAME EMP_NIC_U INDX_EMP_SAL_COMM INDX_EMP_SAL_COMM

COLUMN_NAME COLUMN_POSITION UNIQUENES --------------- --------------- --------EMPNO 1 UNIQUE ENAME 1 NONUNIQUE NIC 1 UNIQUE SAL 1 NONUNIQUE COMM 2 NONUNIQUE

Creating unique index SQL> CREATE UNIQUE INDEX INDX_NIC 2 ON EMP (NIC); ON EMP (NIC) * ERROR at line 2: ORA-01408: such column list already indexed 159

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Function-Based Indexes • •

A function-based index is an index based on expressions. The index expression is built from table columns, constants, SQL functions, and userdefined functions.

SQL> CREATE INDEX INDX_EMP_UPPER 2 ON EMP (UPPER(ENAME)); Index created. SQL> UPDATE EMP SET ENAME=LOWER(ENAME); 18 rows updated. SQL> SELECT * FROM EMP WHERE UPPER(ENAME)='SMITH'; EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO --------- ---------- --------- --------- --------- --------- --------- --------7369 smith CLERK 7902 17-DEC-80 800 20

Removing an Index You cannot modify indexes. To change an index, you must drop it and then re-create it. Remove an index definition from the data dictionary by issuing the DROP INDEX statement. To drop an index, you must be the owner of the index or have the DROP ANY INDEX privilege. SQL> DROP INDEX INDX_EMP_UPPER; Index dropped.

When to Create an Index You should create an index if: • A column contains a wide range of values • A column contains a large number of null values • One or more columns are frequently used together in a WHERE clause or a join condition • The table is large and most queries are expected to retrieve less than 2 to 4 percent of the rows

When Not to Create an Index It is usually not worth creating an index if: • The table is small • The columns are not often used as a condition in the query • Most queries are expected to retrieve more than 2 to 4 percent of the rows in the table • The table is updated frequently • The indexed columns are referenced as part of an expression

160

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Synonyms Simplify access to objects by creating a synonym (another name for an object). With synonyms, you can: • Ease referring to a table owned by another user • Shorten lengthy object names SQL> SELECT * FROM E; SELECT * FROM E * ERROR at line 1: ORA-00942: table or view does not exist SQL> CREATE SYNONYM E 2 FOR EMP; Synonym created. SQL> SELECT * FROM E WHERE DEPTNO=10; EMPNO --------7782 7839 4 7934

ENAME ---------CLARK KING ZIA MILLER

JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------MANAGER 7839 09-JUN-81 2450 10 PRESIDENT 17-NOV-81 5000 10 CLERK 10 CLERK 7782 23-JAN-82 1300 10

If you want to access objects of another user you may get error MEASURE is a table and it is owned by INVENTORY user. but the following is applied from SCOTT user. SQL> DESC MEASURE ERROR: ORA-04043: object MEASURE does not exist

SQL> SELECT * FROM MEASURE; SELECT * FROM MEASURE * ERROR at line 1: ORA-00942: table or view does not exist

How to access object of other user SQL> SELECT * FROM INVENTORY.MEASURE; MEASURE_ID MEASURE_DESC ---------- ---------------------------------------BAGS BAGS CAN DRUM JAR COTTON 161

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

You can create synonym for accessing objects of other user For example

SCOTT is a user from where I want to access objects of INVENTORY user. I will create a synonym in SCOTT user. SQL> SHOW USER USER is "SCOTT" SQL>

SQL> CREATE SYNONYM MSR 2 FOR INVENTORY.MEASURE; Synonym created. SQL> CREATE SYNONYM MEASURE 2 FOR INVENTORY.MEASURE; Synonym created. Now you can use MEASURE or MSR synonym from SCOTT user. SQL> DESC MSR Name Null? ------------------------------- -------MEASURE_ID NOT NULL MEASURE_DESC

Type ---VARCHAR2(10) VARCHAR2(40)

SQL> DESC MEASURE Name Null? ------------------------------- -------MEASURE_ID NOT NULL MEASURE_DESC

Type ---VARCHAR2(10) VARCHAR2(40)

View Synonym information by using USER_SYNONYMS SQL> SELECT SYNONYM_NAME, TABLE_OWNER, TABLE_NAME FROM USER_SYNONYMS; SYNONYM_NAME -----------------------------E MSR MEASURE

TABLE_OWNER -----------------------------SCOTT INVENTORY INVENTORY

TABLE_NAME ---------------EMP MEASURE MEASURE

You can also user USER_OBJECTS COL OBJECT_NAME FORMAT A15 SQL> SELECT OBJECT_NAME FROM USER_OBJECTS WHERE OBJECT_TYPE='SYNONYM'; OBJECT_NAME --------------MSR E MEASURE

Removing a Synonym To drop a synonym, use the DROP SYNONYM statement. Only the database administrator can drop a public synonym SQL> DROP SYNONYM MSR; 162

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Synonym dropped.

Chapter 13

Controlling User Access Users in Oracle In Oracle terminology, a user is someone who can connect to a database (if granted enough privileges) and optionally (again, if granted the appropriate privileges) can own objects (such as tables) in the database. The objects a user owns are collectively called schema. A schema, on its part, is always bound to exactly one user. Because there is obviously a 1 to 1 relationship between a user and a schema, these two terms are often used interchangeable. In order to find out what users are created on the database, one can use DBA_USERS. Database rights (Privileges) Users can be assigned rights what they're allowed to do in a database and what not. These rights are called privileges. Privileges A privilege is a right to execute an SQL statement or to access another user's object. In Oracle, there are two types of privileges: • System privileges • Object privileges. A privilege can be assigned to a user or a privilege. The set of privileges is fixed, that is, there is no SQL statement like create privilege xyz... System privileges Once a user is created, the DBA can grant specific system privileges to a user. There are quite a few system privileges: in Oracle 9.2, we count 157 of them, and 10g has even 173. Those can be displayed with: SQL> SELECT NAME FROM SYSTEM_PRIVILEGE_MAP Executing this statement, we find privileges like create session, drop user, alter database. Arguably, the most important system privileges are: • CREATE SESSION (A user cannot login without this privilege. If he tries, he gets an ORA-01045). • CREATE TABLE • CREATE VIEW • CREATE PROCEDURE • SYSDBA • SYSOPER System privileges can be displayed using USER_SYS_PRIVS data dictionary view

163

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Object privileges An object privilege is a privilege or right to perform a particular action on a specific object (table, view, sequence, or procedure ect.) Each object has a particular set of grantable privileges. Some objects privileges are: • • • • • •

Tables (SELECT, INSERT, UPDATE, DELETE, ALTER etc.) Views (SELECT, INSERT, UPDATE, DELETE etc.) Sequence (ALTER, SELECT) Packeges, Procedures, Functions (EXECUTE, DEBUG) Directories (READ, WRITE ) …

For a user to be able to access an object in another user's schema, he needs the according object privilege. Object privileges can be displayed using all_tab_privs_made or user_tab_privs_made. Public If a privilege is granted to the special role public, this privilege can be executed by all other users. However, sysdba cannot be granted to public. Role A role is a named group of related privileges that can be granted to the user. This method makes it easier to revoke and maintain privileges. A user can have access to several roles, and several users can be assigned the same role. Roles are typically created for a database application. Predefined Roles Along with the installation, more exactly with the creation of an oracle database, Oracle creates predefined roles. These are: • connect, resource, dba These might not be created anymore in future versions of Oracle. Oracle 9.2 grants create session, alter session, create synonym, create view, create database link, create table, create cluster and create sequence to connect. It also grants create table, create cluster, create sequence, create trigger create procedure, create type, create indextype and create operator to resource. The role dba gets basically everything and that with admin option.

164

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Creating user The DBA creates the user by executing the CREATE USER statement. The user does not have any privileges at this point. The DBA can then grant privileges to that user. These privileges determine what the user can do at the database level. SQL> CONN SYS/ORACLE AS SYSDBA Connected. SQL> SQL> SHOW USER USER is "SYS" SQL> SQL> CREATE USER MRAHEEM IDENTIFIED BY MCS298; User created. The user does not have any privileges at this point. The DBA can then grant privileges to that user. These privileges determine what the user can do at the database level. SQL> CONN MRAHEEM/MCS298 ERROR: ORA-01045: user MRAHEEM lacks CREATE SESSION privilege; logon denied

Warning: You are no longer connected to ORACLE. SQL> Granting System Privileges The DBA uses the GRANT statement to allocate system privileges to the user or role. Once the user has been granted the privileges, the user can immediately use those privileges. In the example, user mraheem has been assigned the privileges to create sessions, tables, sequences, and views. SQL> GRANT CREATE SESSION, CREATE TABLE, CREATE SEQUENCE, CREATE VIEW 2 TO MRAHEEM; Grant succeeded. SQL> CONN MRAHEEM/MCS298 Connected.

Confirming system privileges granted to the user SQL> SELECT * FROM USER_SYS_PRIVS; USERNAME -----------------------------MRAHEEM MRAHEEM MRAHEEM MRAHEEM

PRIVILEGE ---------------------------------------CREATE VIEW CREATE TABLE CREATE SESSION CREATE SEQUENCE 165

ADM --NO NO NO NO

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

SQL>

SQL> DESC USER_USERS Name ----------------------------------------USERNAME USER_ID ACCOUNT_STATUS LOCK_DATE EXPIRY_DATE DEFAULT_TABLESPACE TEMPORARY_TABLESPACE CREATED INITIAL_RSRC_CONSUMER_GROUP EXTERNAL_NAME SQL> SQL> SQL> SQL>

COL COL COL COL

Null? -------NOT NULL NOT NULL NOT NULL

Type ---------------------------VARCHAR2(30) NUMBER VARCHAR2(32) DATE DATE NOT NULL VARCHAR2(30) NOT NULL VARCHAR2(30) NOT NULL DATE VARCHAR2(30) VARCHAR2(4000)

USERNAME FORMAT A10 ACCOUNT_STATUS FORMAT A10 DEFAULT_TABLESPACE FORMAT A10 TEMPORARY_TABLESPACE FORMAT A10

SQL> SELECT USERNAME, ACCOUNT_STATUS, DEFAULT_TABLESPACE, 2 TEMPORARY_TABLESPACE, CREATED FROM USER_USERS; USERNAME ACCOUNT_ST DEFAULT_TA TEMPORARY_ CREATED ---------- ---------- ---------- ---------- --------MRAHEEM OPEN USERS TEMP 07-AUG-08

SQL> CREATE TABLE EMPLOYEE 2 ( 3 EMPNO NUMBER(4) PRIMARY KEY, 4 ENAME VARCHAR2(20) 5 ); CREATE TABLE EMPLOYEE * ERROR at line 1: ORA-01950: no privileges on tablespace 'USERS'

SQL> DESC USER_TS_QUOTAS Name Null? ----------------------------------------- -------TABLESPACE_NAME NOT NULL BYTES MAX_BYTES BLOCKS MAX_BLOCKS DROPPED

Type -------------------------VARCHAR2(30) NUMBER NUMBER NUMBER NUMBER VARCHAR2(3)

SQL> SELECT * FROM USER_TS_QUOTAS; no rows selected

166

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Assigning quota to mraheem on USERS tablespace SQL> CONN SYS/ORACLE AS SYSDBA Connected. SQL> ALTER USER MRAHEEM QUOTA 5M ON USERS; User altered. SQL> CONN MRAHEEM/MCS298 Connected. SQL> SELECT * FROM USER_TS_QUOTAS; TABLESPACE_NAME BYTES MAX_BYTES BLOCKS MAX_BLOCKS DRO ------------------------------ ---------- ---------- ---------- ---------- --USERS 0 5242880 0 640 NO SQL> 2 3 4 5

CREATE TABLE EMPLOYEE ( EMPNO NUMBER(4) PRIMARY KEY, ENAME VARCHAR2(20) );

Table created. SQL> SELECT * FROM USER_TS_QUOTAS; TABLESPACE_NAME BYTES MAX_BYTES BLOCKS MAX_BLOCKS DR ------------------------------ ---------- ---------- ---------- ---------- -USERS 131072 5242880 16 640 NO

SQL> 2 3 4 5 6

CREATE TABLE STUDENT ( GRNO NUMBER(4) PRIMARY KEY, NAME VARCHAR2(20) NOT NULL, FNAME VARCHAR2(20) );

Table created. SQL> SELECT * FROM USER_TS_QUOTAS; TABLESPACE_NAME BYTES MAX_BYTES BLOCKS MAX_BLOCKS DRO ------------------------------ ---------- ---------- ---------- ---------- --USERS 262144 5242880 32 640 NO

SQL> SELECT * FROM USER_SYS_PRIVS; USERNAME -----------------------------MRAHEEM MRAHEEM MRAHEEM MRAHEEM

PRIVILEGE ---------------------------------------CREATE VIEW CREATE TABLE CREATE SESSION CREATE SEQUENCE 167

ADM --NO NO NO NO

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

SQL>

The REVOKE statement You can remove privileges granted to other users by using the REVOKE statement. When you use the REVOKE statement, the privileges that you specify are revoked from the users you name and from any other users to whom those privileges were granted through the WITH GRANT OPTION clause. SQL> CONN SYS/ORACLE AS SYSDBA Connected. SQL> REVOKE CREATE TABLE FROM MRAHEEM; Revoke succeeded. SQL> CONN MRAHEEM/MCS298 Connected. SQL> SQL> SELECT * FROM USER_SYS_PRIVS; USERNAME -----------------------------MRAHEEM MRAHEEM MRAHEEM

PRIVILEGE ---------------------------------------CREATE VIEW CREATE SESSION CREATE SEQUENCE

ADM --NO NO NO

SQL> CREATE TABLE STUDENT 2 ( 3 GRNO NUMBER(4) PRIMARY KEY, 4 NAME VARCHAR2(20) 5 ); CREATE TABLE STUDENT * ERROR at line 1: ORA-01031: insufficient privileges

SQL>

168

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

Granting object privileges You are trying to access EMP table, but you don’t have rights/privileges to access the EMP table. SQL> SHOW USER USER is "MRAHEEM" SQL> SELECT COUNT(*) FROM SCOTT.EMP; SELECT COUNT(*) FROM SCOTT.EMP * ERROR at line 1: ORA-00942: table or view does not exist If you want to access objects of any other user, then you must have rights/privileges on that objects to access them. Owner of objects grants rights on his objects. SQL> CONN SCOTT/TIGER Connected. SQL> GRANT SELECT 2 ON EMP 3 TO MRAHEEM; Grant succeeded. SQL> GRANT SELECT, INSERT, UPDATE, DELETE 2 ON EMP 3 TO MRAHEEM; Grant succeeded.

How to view granted object privileges SQL> SQL> SQL> SQL> SQL> SQL> SQL>

COL COL COL COL COL

GRANTEE FORMAT A10 OWNER FORMAT A10 TABLE_NAME FORMAT A10 GRANTOR FORMAT A10 PRIVILEGE FORMAT A10

SELECT * FROM USER_TAB_PRIVS_MADE;

GRANTEE ---------MRAHEEM MRAHEEM MRAHEEM MRAHEEM

OWNER ---------SCOTT SCOTT SCOTT SCOTT

TABLE_NAME ---------EMP EMP EMP EMP

GRANTOR ---------SCOTT SCOTT SCOTT SCOTT

PRIVILEGE ---------INSERT UPDATE DELETE SELECT

GRA --NO NO NO NO

HIE --NO NO NO NO

SQL> CONN MRAHEEM/MCS298 Connected. SQL> SELECT COUNT(*) FROM SCOTT.EMP; COUNT(*) ---------18 169

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

SQL>

SQL> CONN SYS/ORACLE AS SYSDBA Connected. SQL> CREATE USER MR IDENTIFIED BY MCS298; User created. SQL> GRANT CREATE SESSION, CREATE TABLE TO MR; Grant succeeded. SQL> ALTER USER MR QUOTA 5M ON USERS; User altered. SQL> CONN MR/MCS298 Connected.

SQL> SELECT * FROM SCOTT.EMP; SELECT * FROM SCOTT.EMP * ERROR at line 1: ORA-00942: table or view does not exist

MRAHEEM is not authorized to grant privileges on SCOTT’s EMP table SQL> CONN MRAHEEM/MCS298 Connected. SQL> GRANT SELECT ON SCOTT.EMP TO MR; GRANT SELECT ON SCOTT.EMP TO MR * ERROR at line 1: ORA-01031: insufficient privileges

Grant privilege with grant option (MRAHEEM is now authorized to grant privileges on SCOTT’s EMP table) SQL> CONN SCOTT/TIGER Connected. SQL> GRANT SELECT, INSERT, UPDATE, DELETE ON EMP TO MRAHEEM WITH GRANT OPTION; Grant succeeded.

SQL> CONN MRAHEEM/MCS298 Connected. SQL> GRANT SELECT ON SCOTT.EMP TO MR; Grant succeeded. SQL> 170

[email protected]

Prepared by Muhammad Raheem

Oracle SQL

Phone: 021-4265550, Cell: 0321-4265550

SCOTT can not revoke privileges directly on EMP table from MR user SCOTT can revoke privileges from MRAHEEM user, and indirectly revoke from MR user

SQL> CONN SCOTT/TIGER Connected.

SQL> REVOKE SELECT, INSERT, UPDATE, DELETE ON EMP FROM MR; REVOKE SELECT, INSERT, UPDATE, DELETE ON EMP FROM MR * ERROR at line 1: ORA-01927: cannot REVOKE privileges you did not grant

SQL> REVOKE SELECT, INSERT, UPDATE, DELETE ON EMP FROM MRAHEEM; Revoke succeeded. SQL>

171

[email protected]

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF