SQL Material
SQL Material
SQL Material
Table of Contents
Unit 1 Topic
Introduction to Oracle What is Oracle Oracles role in Client/Server Computing What is Personal Oracle Features of Oracle Database Architecture Overall System Architecture Oracle Instance SGA memory structure Query process Oracle versions Oracle9i Features & Benefits Oracle9i Products What 9i supports Data concurrency and consistency Locking and Read Consistency Environment Summary Exercises OPERATORS AND QUERIES Oracle Data types Introduction to SQL SQL in Application Programming Writing simple queries Expressions, conditions and Operators Arithmetic Operators Comparison Operators Character Operators Concatenation operator Logical Operators Miscellaneous Operators: IN, BETWEEN and DISTINCT Distinct operator Order by clause Exercise FUNCTIONS Predefined functions Group functions Aggregate functions Single row functions Arithmetic Functions Character Functions Conversion Functions Date and Time Functions Miscellaneous Functions Exercise GROUP AND HAVING CLAUSE GROUP BY CLAUSE ERROR with GROUP BY Clause Using Break CUBE and ROLLUP HAVING clause Points to remember Order of Execution Exercise
PageNo 03 - 30
31 57
58-110
111-126
NESTED
SUB QUERIES Single row sub queries Multi row sub queries Multi column sub queries Correlated sub queries.
127-142
143-163
164-180
181-192
193-201
10
202-203
11
204-206
12 13 14 15
ORACLE
Course Day Session Estimated Time : : : : Oracle SQL 1 1 3 Hrs
Topics Introduction to Oracle Oracles Role in Client / Server Computing Oracle Features Database Architecture Overall System Structure Oracle Instance Query Process Oracle versions, features and Benefits Oracle9i ORDBMS Data Concurrency And Consistency Environment Summary Exercise
Presentation
Introduction
It is a DBMS, which manages a large amount of data in a multi user environment so that many users concurrently access the data. It also provides security and Recovery. It stores and manages data using relational model. Oracle is the name of database management system developed by Oracle Corporation. Oracle server manages data in the database. Users access Oracle server using SQL commands. So Oracle server receives SQL commands from users and executes them on the database.
SQL
ORACLE SERVER
CLIENT
Result
Database
CLIENT
Oracle is a database system that runs on the server, and used to manage the data. The other name to database server is Back-End. The latest version of the Oracle server is 9i. Oracle server runs on different platforms. The following are some of the platforms on which Oracle runs. Windows NT. Novel Netware Unix
Data Concurrence
Oracle supports concurrent access to database by multiple users. It automatically locks and unlocks rows to maintain integrity of the data.
Portability
Oracle software can be ported to different operating systems and it is the name on all systems. Application development in Oracle can be ported to any operating system with little or no modifications.
Enforced Integrity
Oracle allows users to define business rules and enforce them. These rules need not be included at the application level.
Data Security
Oracle provides security in different levels system level and object level. It also makes implementation of security easier through Roles.
In any RDBMS we can use 3 levels of data abstractions. Physical level Logical Level View level
Physical Level
The Physical structure of the database is placed in Physical level. It is physically a set of three operating system files. Data Files Redo log files Control files These files automatically create when database is created.
Data Files
It contains the data of the database. Every table that is stored in the database is a part of these files. Only Oracle Server can interpret these data files.
Control Files
Contain information required to verify the integrity of the database, including the names of the other files in the database (Extension of file is ctl) Database Name Names and locations of data files and redo log files. Path We can use this Oracle\oradata\orcl path in the server to see all the 3 types of files
Tablespace
Each Database is a collection of tablespaces. For example we can use a table space called PAYROLL to store all the data related to payroll application. Every database contains SYSTEM tablespace. This is automatically created when a database is created. SYSTEM tablespace contains the data dictionary tables. It is possible to make tablespace temporarily unavailable by making it off-line and makes it available again by changing it to on-line. By making a tablespace off-line, DBA can take the backup.
Segments
Data into table spaces comes in the form of segments. Example Table is a segment An Oracle database requires up to 4 types of segments Data segments Index Segments Rollback segments Temporary segments It is used to store data of tables Used to store indexes Undo information is stored Oracle stores Temporary tables
Extents
The storage space is allocated to segments is in the form of Extents. Each Tablespace contains 65536 data files N number of such Table spaces creates a database. An extent is made with in a data file. N Number of continuous db blocks makes up an Extent.
10
11
12
Database Structures
The relational model has three major aspects: Structures Structures are well-defined objects that store the data of a database. Structures and the data contained within them can be manipulated by operations. Operations Operations are clearly defined actions that allow users to manipulate the data and structures of a database. The operations on a database must adhere to a pre-defined set of integrity rules. Integrity Rule Integrity rules are the laws that govern which operations are allowed on the data and structures of a database. Integrity rules protect the data and the structures of a database. An ORACLE database has both a physical and a logical structure. By separating physical and logical database structure, the physical storage of data can be managed without affecting the access to logical storage structures.
The logical storage structures, including tablespaces, segments, and extents, dictate how the physical space of a database is used. The schema objects and the relationships among them form the relational design of a database.
13
databases and tablespaces An ORACLE database is comprised of one or more logical storage units called tablespaces. The database's data is collectively stored in the database's tablespaces. tablespaces and data files Each tablespace in an ORACLE database is comprised of one or more operating system files called data files. A tablespace's data files physically store the associated database data on disk. databases and data files A database's data is collectively stored in the data files that constitute each tablespace of the database. For example, the simplest ORACLE database would have one tablespace, with one data file. A more complicated database might have three tablespaces, each comprised of two data files (for a total of six data files). schema objects, segments, and tablespaces When a schema object such as a table or index is created, its segment is created within a designated tablespace in the database. For example, suppose a table is created in a specific tablespace using the CREATE TABLE command with the TABLESPACE option. The space for this table's data segment is allocated in one or more of the data files that constitute the specified tablespace. An object's segment allocates space in only one tablespace of a database.
14
A database is divided into one or more logical storage units called tablespaces. A database administrator can use tablespaces to do the following: Control disk space allocation for database data. Assign specific space quotas for database users. Control availability of data by taking individual tablespaces online or offline. Perform partial database backup or recovery operations. Allocate data storage across devices to improve performance.
Every ORACLE database contains a tablespace named SYSTEM, which is automatically created when the database is created. The SYSTEM tablespace always contains the data dictionary tables for the entire database. You can query these data dictionary tables to obtain pertinent information about the database; for example, the names of the tables that are owned by you or ones to which you have access.
15
segment are full, ORACLE allocates another extent for that segment. Because extents are allocated as needed, the extents of a segment may or may not be contiguous on disk, and may or may not span files. An extent cannot span files, though. 16
ORACLE manages the storage space in the data files of a database in units called data blocks. A data block is the smallest unit of I/O used by a database. A data block corresponds to a block of physical bytes on disk, equal to the ORACLE data block size (specifically set when the database is created - 2048). This block size can differ from the standard I/O block size of the operating system that executes ORACLE. The ORACLE block format is similar regardless of whether the data block contains table, index, or clustered data. Figure 4 shows the format of the block.
17
Header (Common and Variable) The header contains general block information, such as block address, segment type, such as data, index, or rollback. While some block overhead is fixed in size (about 107 bytes), the total block overhead size is variable. Table Directory The table directory portion of the block contains information about the tables having rows in this block. Row Directory This portion of the block contains row information about the actual rows in the block (including addresses for each row piece in the row data area). Once the space has been allocated in the row directory of a block's header, this space is not reclaimed when the row is deleted. Row Data This portion of the block contains table or index data. Rows can span blocks.
18
PCTUSED. Before this value is achieved, the free space of the data block can only be used for updates to rows already contained in the
data block. For example, assume that you specify the following parameter within a CREATE TABLE statement:
pctused 40 In this case, a data block used for this table's data segment is not considered for the insertion of any new rows until the amount of used space in the blocks falls to 39\% or less (assuming that the block's used space has previously reached PCTFREE). No matter what type, each segment in a database is created with at least one extent to hold its data. This extent is called the segment's initial extent. If the data blocks of a segment's initial extent become full and more space is required to hold new data, ORACLE automatically allocates an incremental extent for that segment. An incremental extent is a
19
Physical Database Structure An ORACLE database's physical structure is determined by the operating system files that constitute the database. Each ORACLE
database is comprised of these types of files: one or more data files, two or more redo log files, and one or more control files. The files of a database provide the actual physical storage for database information. For more information on these physical storage files, see ``ORACLE7 Server Concepts Manual.''
20
Figure 5. Maintaining the Free Space of Data Blocks with PCTFREE and PCTUSED
21
22
23
Query process
1 Parse 2 Execute 3 Fetch
3
Server Process
DB
1
User Process
2 Client
When User connects to the database, it automatically creates two different processes called as User process and Server Process. The user process is the application program that originates SQL statements. The server process executes the statements sent from the user process. There are three main stages in the processing of a query: Parse Execute Fetch
Parsing
During the parse stage, the SQL statement is passed from the user process to the server process, and a parsed representation of the SQL statement is loaded into a shared SQL area. During the parse, the server process performs the following functions: Searches for an existing copy of the SQL statement in the shared pool validates the SQL statement by checking its syntax Performs data dictionary lookups to validate table and column definitions
24
Fetch
Fetch: Return rows to user process. With each fetch process, it can fetch 20 records at a time.
25
Scalability
9i
Reliability
Internet
Features
Oracle offers a comprehensive high performance infrastructure for ebusiness. It is called Oracle9i.It provides everything needed to develop, deploy and manage Internet applications.
Benefits
Scalability from departments to enterprise e-business sites Reliable, available and secure architecture One development model, easy development options Common skill sets including SQL, PL/SQL,JAVA and XML One Management interface for all applications
26
9i Products
There are two products. They provide a complete and simple infrastructure for Internet applications.
Application Server
9i Application server runs all the applications and 9i database stores our data. Oracle 9i Application server runs Portals or web sites Java Transactional Applications Provides integration between users, applications and data
27
Locking
Oracle uses Locks to control data concurrency. Locks are used to prevent destructive interference. For instance, when user X is modifying a row, it is locked so that other users cannot modify it until X completes modification. However, it doesnt stop users querying the row. That means users reading the data will not be interrupted by user modifying and vice-versa. Note: it is the responsibility of the application developer to unlock rows that are locked by committing or rolling back the transaction.
Read Consistency
For a query, Oracle returns a timepoint-based version of data. That means, the data retrieved is consistent with the time at which the query started. So any changes made to database since query started will not be available.
28
Environment
Oracle uses two types of Environments for executing our SQL statements. SQL*plus and iSQL*plus. ISQL*plus is (Available only from Oracle 9i) An Environment Oracle proprietary Keywords can be abbreviated Runs on a browser Centrally loaded, does not have to be implemented on each machine
29
30
31
Siva Kumar HVK Course Day Session Estimated Time : : : : Oracle 1 2 2 Hrs
Topics
Oracle data types Introduction to SQL An overview of SQL SQL in Application programming Structured Query Language SQL statements Simple Queries Operators, Expressions and Expressions
32
Character Datatypes
The character data types store character (alphanumeric) data in strings, with byte values corresponding to the character.
CHAR datatype
Fixed length character data of length size in bytes.( Default size is 1 and maximum size is 2000). Padded on right with blanks to full length of size.
VARCHAR2 (size)
Variable length characters strings having a maximum size of 4000 bytes (Default size is 1). Truncates leftover blank spaces.
NVARCHAR2(size)
Variable length characters strings having a maximum size of 4000 bytes (Default size is 1) Or characters, depending on the choice of national character set. Truncates leftover blank spaces.
33
LONG
Character data of variable size up to 2GB in length. Only one LONG column is allowed in a table. Long column cannot be used in sub queries, functions, expressions, where clause or indexes.
DATE
Valid date ranges from January 1,4712 BC to December 31,9999 AD. (Default date format DD-MON-YY)
TIMESTAMP(precision)
Date plus time, where precision is the number of digits in the fractional part of the seconds field (default is 6).
RAW(size)
Raw binary date, size bytes long. Maximum size is 2000 bytes.
LONG RAW
Raw binary data, otherwise the same as LONG. These two data types allow storing pictures.
CLOB
Character Large object, up to 4GB in length.
BLOB
34
BFILE
35
Introduction to SQL
A Brief History of SQL
The history of SQL begins in an IBM laboratory in San Jose, California, where SQL was developed in the late 1970s. The initials stand for Structured Query Language, and the language itself is often referred to as "sequel." It was originally developed for IBM's DB2 product (a relational database management system, or RDBMS, that can still be bought today for various platforms and environments). In fact, SQL makes an RDBMS possible. SQL is a nonprocedural language, in contrast to the procedural or third generation languages (3GLs) such as COBOL and C that had been created up to that time. NOTE: Nonprocedural means what rather than how. For example, SQL describes what data to retrieve, delete, or insert, rather than how to perform the operation. The characteristic that differentiates a DBMS from an RDBMS is that the RDBMS provides a set-oriented database language. For most RDBMS, this set-oriented database language is SQL. Set oriented means that SQL processes sets of data in groups. Two standards organizations, the American National Standards Institute (ANSI) and the International Standards Organization (ISO), currently promote SQL standards to industry. The ANSI-92 standard is the standard for the SQL used throughout this book. Although these standard-making bodies prepare standards for database system designers to follow, all database products differ from the ANSI standard to some degree. In technology in a single-user business application positions the application for future growth.
An Overview of SQL
SQL is the standard language used to manipulate and retrieve data from these relational databases. SQL enables a programmer or database administrator to do the following: Modify a database's structure Change system security settings Add user permissions on databases or tables Query a database for information Update the contents of a database
36
SQL Statements
SELECT INSERT UPDATE DELETE MERGE CREATE ALTER DROP RENAME TRUNCATE COMMIT ROLLBACK SAVEPOINT GRANT REVOKE Data retrieval Data manipulation language(DML)
37
It is a building block for data retrieval in SQL. Syntax : SELECT <COLUMNS> FROM <TABLE>;
ANALYSIS: Notice that columns 6 and 8 in the output statement are right justified and that columns 2 and 3 are left justified. This format follows the alignment convention in which numeric data types are right justified and character data types are left justified. The asterisk (*) in select * tells the database to return all the columns associated with the given table described in the FROM clause. The database determines the order in which to return the columns. f ll bl i d h h i h l
38
INPUT: SQL> SELECT empno, ename, sal, job, comm from EMP; OUTPUT
EMPNO ---------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934 ENAME SAL JOB COMM ---------- ---------- --------- ---------SMITH 800 CLERK ALLEN 1600 SALESMAN 300 WARD 1250 SALESMAN 500 JONES 2975 MANAGER MARTIN 1250 SALESMAN 1400 BLAKE 2850 MANAGER CLARK 2450 MANAGER SCOTT 3000 ANALYST KING 5000 PRESIDENT TURNER 1500 SALESMAN 0 ADAMS 1100 CLERK JAMES 950 CLERK FORD 3000 ANALYST MILLER 1300 CLERK
14 rows selected.
39
ANALYSIS: This simple example shows how you can place a condition on the data that you want to retrieve.
40
ANALYSIS:
Displays all the employees other than KING.
Operators
Operators are the elements you use inside an expression to articulate how you want specified conditions to retrieve data. Operators fall into six groups: arithmetic, comparison, character, logical, set, and miscellaneous.
Arithmetic Operators
The arithmetic operators are plus (+), minus (-), divide (/), multiply (*). The first four are self-explanatory. Modulo returns the integer remainder of a division.
41
SELECT * FROM EMP WHERE SAL >= 2000; SELECT * FROM EMP WHERE SAL >= 3000 AND SAL <= 4000; SELECT * FROM EMP WHERE SAL BETWEEN 3000 AND 4000; SELECT * FROM EMP WHERE SAL NOT BETWEEN 3000 AND 4000;
To understand how you could get an Unknown, you need to know a little about the concept of NULL. In database terms NULL is the absence of data in a field. It does not mean a column has a zero or a blank in it. A zero or a blank is a value. NULL means nothing is in that field. If you make a comparison like Field = 9 and the only value for Field is NULL, the comparison will come back Unknown. Because Unknown is an uncomfortable condition, most flavors of SQL change Unknown to FALSE and provide a special operator, IS NULL, to test for a NULL condition.
42
LIKE operator
What if you wanted to select parts of a database that fit a pattern but weren't quite exact matches? You could use the equal sign and run through all the possible cases, but that process would be time-consuming. Instead, you could use LIKE.
INPUT:
SELECT * FROM EMP WHERE ENAME LIKE A%; ANALYSIS Displays all the employees whose names begins with letter A
INPUT:
SELECT * FROM EMP WHERE ENAME NOT LIKE A%; ANALYSIS Displays all the employees whose names not beginning with letter A
43
SELECT * FROM EMP WHERE ENAME LIKE %A%; ANALYSIS Displays all the employees whose names contains letter A (Any number of As)
INPUT:
SELECT * FROM EMP WHERE ENAME LIKE %A%A%; ANALYSIS Displays all the names whose name contains letter A more than one time
INPUT:
SELECT * FROM EMP WHERE HIREDATE LIKE %DEC%; ANALYSIS Displays all the employees who joined in the month of December.
INPUT:
SELECT * FROM EMP WHERE HIREDATE LIKE %81; ANALYSIS Displays all the employees who joined in the year 81.
INPUT:
SELECT * FROM EMP WHERE SAL LIKE 4%; ANALYSIS Displays all the employees whose salary begins with number 4. (Implicit data conversion takes place).
44
INPUT: SQL> SELECT EMPNO,ENAME FROM EMP WHERE ENAME LIKE _A%; OUTPUT:
EMPNO ---------7521 7654 7900 ENAME ---------WARD MARTIN JAMES
INPUT: SQL> SELECT * FROM EMP WHERE ENAME LIKE __A%; OUTPUT:
ENAME ---------BLAKE CLARK ADAMS
ANALYSIS Displays all the employees whose third letter is A (Two underscores followed by A)
INPUT: SQL> SELECT * FROM EMP WHERE ENAME LIKE A%\_% ESCAPE \; OUTPUT:
ENAME ---------AVINASH_K ANAND_VARDAN ADAMS_P
ANALYSIS Displays all the employees with underscore (_). \ Escape character Underscore is used to identify a position in the string. To treat _ as a character we have to use Escape (\) character,
45
ANALYSIS Combines both name and designation as a single string separated by,
46
SELECT ENAME FROM EMP WHERE ENAME LIKE %A% and ENAME NOT LIKE %A%A%
OUTPUT
ENAME ---------ALLEN WARD MARTIN BLAKE CLARK JAMES ANALYSIS
Displays all the employees whose names contains letter A exactly one time.
SELECT * FROM EMP WHERE SAL >= 3000 AND SAL <= 4000; SELECT * FROM EMP WHERE SAL BETWEEN 3000 AND 4000; SELECT * FROM EMP WHERE SAL NOT BETWEEN 3000 AND 4000;
47
INPUT: SQL> SELECT ENAME, JOB FROM EMP WHERE JOB= 'CLERK' OR JOB =MANAGER OR JOB = 'SALESMAN'; OUTPUT:
ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK TURNER ADAMS JAMES MILLER JOB --------CLERK SALESMAN SALESMAN MANAGER SALESMAN MANAGER MANAGER SALESMAN CLERK CLERK CLERK
48
Siva Kumar HVK INPUT: SQL> SELECT ENAME,JOB FROM EMP WHERE JOB NOT IN('CLERK','SALESMAN','MANAGER'); OUTPUT:
ENAME ---------SCOTT KING FORD JOB --------ANALYST PRESIDENT ANALYST
OUTPUT:
ENAME ---------BLAKE SCOTT HIREDATE --------01-MAY-81 09-DEC-82
ANALYSIS
Note : Efficiency is more when we write the query using IN operator rather than OR operator.
49
ANALYSIS
Distinct operator displays unique designations. Distinct operator by default displays the information in ascending order.
50
Siva Kumar HVK Course Day Session Estimated Time : : : : Oracle 1 3 2 Hrs
Topics
51
52
Siva Kumar HVK INPUT SQL> SELECT JOB,ENAME,SAL FROM EMP ORDER BY JOB,ENAME; OUTPUT
JOB --------ANALYST ANALYST CLERK CLERK CLERK CLERK MANAGER MANAGER MANAGER PRESIDENT SALESMAN SALESMAN SALESMAN SALESMAN ANALYSIS ENAME SAL ---------- ---------FORD 3000 SCOTT 3000 ADAMS 1100 JAMES 950 MILLER 1300 SMITH 800 BLAKE 2850 CLARK 2450 JONES 2975 KING 5000 ALLEN 1600 MARTIN 1250 TURNER 1500 WARD 1250
Display employees in ascending order of jobs. With each job it places the information in ascending order of names. INPUT
SQL> SELECT * FROM EMP ORDER BY job, name desc; OUTPUT:
Display employees in ascending order by jobs. With each job it places the information in descending order of names.
INPUT
SQL> SELECT * FROM EMP ORDER BY job desc, ename desc; OUTPUT:
Display employees in descending order by jobs. With each job it places the information in descending order of names.
INPUT
SQL> SELECT * 53 FROM EMP where JOB != CLERK ORDER BY JOB;
We can also use order by clause as INPUT SQL> SELECT * FROM EMP ORDER BY 3; ANALYSIS It places the information in the order of third column in the table.
54
9. Examine the trace instance chart for employee table. You want to display each employee hiredate from earliest to latest. Which SQL statement will you use? (1) SELECT hiredate FROM emp; (2) SELECT hiredate FROM emp ORDER BY hiredate; (3) SELECT emp FROM emp ORDER by hiredate; (4) SELECT hiredate FROM emp ORDER BY hiredate DESC;
10. Which data type should you use for interest rates with varying and unpredictable decimal places such as 1.234, 3.4, 5 and 1.23? (1) LONG. (2) NUMBER. (3) NUMBER(p, s) (4) None 11.Which SQL statement generates the alias Annual Salary for the calculated column SALARY*12? (1) SELECT ename, salary*12 Annual SalaryFROM employees; (2) SELECT ename, salary*12 Annual SalaryFROM employees; (3) SELECT ename, salary*12 AS Annual SalaryFROM employees; (4) SELECT ename, salary*12 AS INITCAP(ANNUAL SALARY)FROM employees
55
2. The employee table contains these columns.LAST_NAME VARCHAR2 (25), FIRST_NAME VARCHAR2(25) DEPT_ID NUMBER(9) You need to display the names of the employees that are not assigned to the department. Evaluate this SQL statement; SELECT last_name, first_name FROM employee WHERE dept_id is NULL which change should you make to achieve the desired result? (1) Create an outer join. (2) Change the column in the where condition. (3) Query executes successfully (4) Add a second condition to the where condition
3. Which statement about SQL is true? (1) Null values are displayed last in the ascending sequences. (2) Data values are displayed in descending order by default. (3) You cannot specify a column alias in an ORDER BY clause. (4) You cannot sort query results by a column that is not included in the SELECT list.
56
FUNCTIONS
A function is a sub program, which executes whenever we call it and returns a value to the calling place. These functions are classified into two types Predefined functions User defined functions
Predefined functions
These functions are again classified into two types Group or Aggregate Functions Single row Functions
Aggregate Functions
These functions are also referred to as group functions. They return a value based on the values in a column.
COUNT
The function COUNT returns the number of rows that satisfy the condition in the WHERE clause. Say you wanted to know how many employees are there.
57
ANALYSIS It counts only those when there is a value in comm. Column Note: Count (comm) faster than count(*) Count(*) count the row when a row present in the table where as Count(comm) counts the row only when there is a value in the column.
INPUT/OUTPUT: SQL> SELECT COUNT(*) FROM EMP WHERE JOB = MANAGER; COUNT(*) ------4
58
Siva Kumar HVK INPUT/OUTPUT: SQL> SELECT count (distinct job) FROM EMP; COUNT (*) ------4
SUM does just that. It returns the sum of all values in a column.
INPUT: SQL> SELECT SUM(SAL) TOTAL_SALARY OUTPUT: TOTAL_SALARY ------------29025 ANALYSIS
FROM EMP;
INPUT/OUTPUT: SQL> SELECT SUM(SAL) TOTAL_SALARY, SUM(COMM) TOTAL_COMM, FROM EMP; TOTAL_SALARY TOTAL_COMM ------------- ---------29025 2200
INPUT/OUTPUT: SQL> SQL> SELECT SUM(SAL) TOTAL_SALARY, SUM(COMM) TOTAL_COMM FROM EMP WHERE JOB = SALESMAN; TOTAL_SALARY TOTAL_COMM ------------- ---------5600 2200
59
INPUT: SQL> SELECT AVG(sal) average_salary 2 FROM EMP; OUTPUT: AVERAGE_SALARY --------------2073.21429 ANALYSIS
INPUT: SQL> SELECT AVG(COMM) average_comm FROM EMP; OUTPUT: AVERAGE_COMM ------------
550
60
Siva Kumar HVK MAX INPUT: SQL> SELECT MAX(SAL) FROM EMP; OUTPUT: MAX(SAL) --------
5000
ANALYSIS Takes the value from one different rows from one particular column
INPUT: SQL> SELECT MAX (hiredate) FROM EMP; OUTPUT: MAX(HIREDATE) -------------
12-JAN-83
61
Siva Kumar HVK MIN INPUT: SQL> SELECT MIN(SAL) FROM EMP; OUTPUT: MIN(SAL) --------
800
INPUT: SQL> SELECT MIN(ENAME) FROM EMP; OUTPUT: MIN (ENAME) --------
ADAMS
INPUT SELECT SUM(SAL),AVG(SAL),MIN(SAL),MAX(SAL),COUNT(*) FROM EMP; OUTPUT SUM(SAL) AVG(SAL) MIN(SAL) MAX(SAL) COUNT(*) -------------- --------------- -------------- -------------- ------------29025 2073.21429 800 5000 14 ANALYSIS All the aggregate functions can be used together in a single SQL statement
62
Siva Kumar HVK Course Day Session Estimated Time : : : : Oracle 1 4 2 Hrs
Revision / Practicals
63
Siva Kumar HVK Course Day Session Estimated Time : : : : Oracle 2 1&2 5 Hrs
64
Arithmetic Functions
Many of the uses you have for the data you retrieve involve mathematics. Most Implementations of SQL provide arithmetic functions similar to that of operators covered here.
ABS
The ABS function returns the absolute value of the number you point to. For example:
INPUT: SQL> SELECT ABS(-10) ABSOLUTE_VALUE FROM dual; OUTPUT ABSOLUTE_VALUE ---------------------------10 ANALYSIS ABS changes all the negative numbers to positive and leaves positive numbers alone. Dual is a system table or dummy table from where we can display system information (i.e. system date and username etc) or we can make our own calculations.
65
CEIL(12.145) ----------------13
CEIL(12.000) ----------------12
ANALYSIS Minimum we require one decimal place , to get the next higher integer number
FLOOR(12.678) ----------------12
INPUT: SQL> SELECT FLOOR(12.000) FROM DUAL; OUTPUT:
FLOOR(12.000) ----------------12
66
INPUT
SQL> SELECT MOD(5,2) FROM DUAL; OUTPUT:
MOD(2,5) --------------2 ANALYSIS When numerator value less than denominator, it returns numerator value as remainder.
67
INPUT: SQL> SELECT SIGN(-10), SIGN(10),SIGN(0) FROM DUAL; OUTPUT: SIGN(-10) SIGN(10) SIGN(0) ---------- ---------- ----------1 1 0
SQRT
The function SQRT returns the square root of an argument. Because the square root of a negative number is undefined, you cannot use SQRT on negative numbers.
68
CHR
CHR returns the character equivalent of the number it uses as an argument. The character it returns depends on the character set of the database. For this example the database is set to ASCII.
CONCAT
It is similar to that of concatenate operator ( | | )
69
70
ANALYSIS: 15 locations allocated to display ename, out of that, name is occupying some space and in the remaining space to the left side of the name pads with *.
71
72
SYNTAX : REPLACE(STRING,SEARCH_STRING,REPLACE_STRING)
INPUT: SQL> SELECT REPLACE (RAMANA,MA, VI) FROM DUAL; OUTPUT RAVINA INPUT SQL> SELECT REPLACE(RAMANA,MA) FROM DUAL; OUTPUT RANA ANALYSIS When the replace string is missing, search string removed from the given string
INPUT SQL> SELECT REPLACE (RAMANA,MA, NULL) FROM DUAL; OUTPUT RANA
73
SUBSTR
This three-argument function enables you to take a piece out of a target string. The first argument is the target string. The second argument is the position of the first character to be output. The third argument is the number of characters to show.
SYNTAX
SUBSTR(STRING,STARTING_POSITION[,NO_OF_CHARACTERS])
74
Siva Kumar HVK INPUT: SQL> SELECT SUBSTR(RAMANA,3,3) FROM DUAL; OUTPUT:
NA ANALYSIS You use a negative number as the second argument, the starting point is determined by counting backwards from the end.
RANA ANALYSIS First two characters and last two characters are combined together as a single string
MANA ANALYSIS When third argument is missing, it takes all the character from starting position
75
ANALYSIS Displays all the employees who joined in the current month SYSDATE is a single row function, which gives the current date.
INSTR
To find out where in a string a particular pattern occurs, use INSTR. Its first argument is the target string. The second argument is the pattern to match. The third and forth are numbers representing where to start looking and which match to report. This example returns a number representing occurrence of O starting with the second the first
INPUT SQL> SELECT INSTR(RAMANA,A) FROM DUAL; OUTPUT 2 ANALYSIS Find the position of the first occurrence of letter A
76
INPUT SQL> SELECT INSTR(RAMANA,A,1,2) FROM DUAL; OUTPUT 4 ANALYSIS Find the position of the second occurrence of letter A from the beginning of the string. Third argument represents from which position, Fourth argument represents, which occurrence.
SQL> SELECT INSTR (RAMANA,a) FROM DUAL; OUTPUT 0 ANALYSIS Function is case sensitive; it returns 0 (zero) when the given character is not found.
INPUT SQL> SELECT INSTR(RAMANA,A,3,2) FROM DUAL; OUTPUT 6 ANALYSIS Find the position of the second occurrence of letter A from 3rd position of the string
77
TO_CHAR
The primary use of TO_CHAR is to convert a number into a character. Different Implementations may also use it to convert other data types, like Date, into a character, or to include different formatting arguments. The following example illustrates the primary use of TO_CHAR:
ANALYSIS After conversion, Converted information is left aligned. So we can say that it is a string.
78
TO_CHAR(SYSDATE,'DD/MM/YYYY') -----------------------------24/03/2007
TO_CHAR(SYSDATE,'DD-MON-YY') -----------------------------24-MAR-07
79
Siva Kumar HVK Date Formats INPUT: SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,DY-MON-YY) FROM DUAL; OUTPUT: SYSDATE --------24-MAR-07 ANALYSIS:
TO_CHAR(SYSDATE,'DY-MON-YY') -----------------------------SAT-MAR-07
INPUT: SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,DAY MONTH YEAR) FROM DUAL; OUTPUT: SYSDATE --------24-MAR-07
ANALYSIS: DAY gives the total day name MONTH gives the total month name YEAR writes the year number in words
80
Siva Kumar HVK INPUT: SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,DDSPTH MONTH YEAR) FROM DUAL; OUTPUT: SYSDATE TO_CHAR(SYSDATE,'DDSPTHMONTHYEAR') --------- ------------------------------------------------------------------24-MAR-07 TWENTY-FOURTH MARCH TWO THOUSAND SEVEN ANALYSIS: DD gives the day number DDSP Writes day number in words TH is the format. Depends upon the number it gives either ST / RD/ST/ND format
INPUT: SQL> SELECT HIREDATE,TO_CHAR(HIREDATE,DDSPTH MONTH YEAR) FROM EMP; OUTPUT: HIREDATE TO_CHAR(HIREDATE,'DDSPTHMONTHYEAR') --------- ------------------------------------------------------------------17-DEC-80 SEVENTEENTH DECEMBER NINETEEN EIGHTY 20-FEB-81 TWENTIETH FEBRUARY NINETEEN EIGHTY-ONE 22-FEB-81 TWENTY-SECOND FEBRUARY NINETEEN EIGHTY-ONE 02-APR-81 SECOND APRIL NINETEEN EIGHTY-ONE 28-SEP-81 TWENTY-EIGHTH SEPTEMBER NINETEEN EIGHTY-ONE 01-MAY-81 FIRST MAY NINETEEN EIGHTY-ONE 09-JUN-81 NINTH JUNE NINETEEN EIGHTY-ONE 09-DEC-82 NINTH DECEMBER NINETEEN EIGHTY-TWO 17-NOV-81 SEVENTEENTH NOVEMBER NINETEEN EIGHTY-ONE 08-SEP-81 EIGHTH SEPTEMBER NINETEEN EIGHTY-ONE 12-JAN-83 TWELFTH JANUARY NINETEEN EIGHTY-THREE 03-DEC-81 THIRD DECEMBER NINETEEN EIGHTY-ONE 03-DEC-81 THIRD DECEMBER NINETEEN EIGHTY-ONE 23-JAN-82 TWENTY-THIRD JANUARY NINETEEN EIGHTY-TWO ANALYSIS: Converts all hire dates in EMP table into Words
81
Siva Kumar HVK INPUT: SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,Q) FROM DUAL; OUTPUT: SYSDATE --------24-MAR-07 ANALYSIS: Gives in the quarter the given date falls
TO_CHAR(SYSDATE,Q) -----------------------------1
INPUT: SQL> SELECT TO_CHAR(TO_DATE(10-SEP-2005),Q) FROM DUAL; OUTPUT: TO_CHAR(TO_DATE('10-SEP-2005'),'Q') ---------------------------------------3 ANALYSIS: To_date is data conversion function, which converts given string into date type
INPUT: SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,W) FROM DUAL; OUTPUT: SYSDATE --------24-MAR-07 ANALYSIS: Gives the week number in the current month ( In which week given date falls in the current month)
TO_CHAR(SYSDATE,W) -----------------------------4
82
Siva Kumar HVK INPUT: SQL> SELECT SYSDATE,TO_CHAR(SYSDATE,WW) FROM DUAL; OUTPUT: SYSDATE TO_CHAR(SYSDATE) -----------------------------------24-MAR-07 12 ANALYSIS: Returns no. of weeks worked during the year.
INPUT: SQL> SELECT TO_CHAR(SYSDATE,HH:MI:SS AM) FROM DUAL; OUTPUT: TO_CHAR(SYS ----------08:40:17 PM ANALYSIS: HH returns Hours MI returns Minutes SS returns Seconds } } Returns time from current date }
INPUT: SQL> SELECT TO_CHAR(SYSDATE,HH24:MI:SS) FROM DUAL; OUTPUT: TO_CHAR( -------20:43:12 ANALYSIS: HH24 returns Hours in 24 hour format MI returns Minutes SS returns Seconds } } Returns time from current date }
83
Siva Kumar HVK INPUT: SQL> SELECT TO_CHAR(12567,99,999.99) FROM DUAL; OUTPUT: TO_CHAR(12567,'99,999.99') ----------------------------12,567.00 ANALYSIS: Converts the given number into comma format with two decimal places
INPUT: SQL> SELECT TO_CHAR(12567,L99,999.99) FROM DUAL; OUTPUT: TO_CHAR(12567,'L99,999.99') ----------------------------$12,567.00 ANALYSIS: Display the local currency symbol
84
Siva Kumar HVK INPUT: SQL> SELECT TO_CHAR(-12567,L99,999.99PR) FROM DUAL; OUTPUT: TO_CHAR(-12567,'L99,999.99PR') ----------------------------------<$12,567.00> ANALYSIS: PR Parenthesis negative number
85
For example: INPUT: SQL> SELECT SAL, TO_NUMBER((TO_CHAR(SAL)) FROM EMP; OUTPUT:
SAL TO_NUMBER(TO_CHAR(SAL)) ---------- ----------------------800 800 1600 1600 1250 1250 2975 2975 1250 1250 2850 2850 2450 2450 3000 3000 5000 5000 1500 1500 1100 1100 950 950 3000 3000 1300 1300
ANALYSIS After conversion, Converted information is right aligned. So we can say that it is a number.
86
ANALYSIS
Find the retirement date of an employee Assume, 33 years of service from date of join is retirement date
LAST_DAY 87
MONTHS_BETWEEN
Used to find the number of months between two given months
ANALYSIS
Finds number of months between sysdate and hiredate . Result is divided with 12 to get the experience
88
INPUT SQL> SELECT LOCALTIMESTAMP FROM DUAL; OUTPUT LOCALTIMESTAMP -----------------------------------25-MAR-07 06.21.02.312000 PM NEW_TIME
This function is used to adjust the time according to the time zone you are in. Here are the time zones you can use with this function: Abbreviation Time Zone AST or ADT Atlantic standard or daylight time BST or BDT Bering standard or daylight time CST or CDT Central standard or daylight time EST or EDT Eastern standard or daylight time GMT Greenwich mean time HST or HDT Alaska-Hawaii standard or daylight time MST or MDT Mountain standard or daylight time NST Newfoundland standard time PST or PDT Pacific standard or daylight time YST or YDT Yukon standard or daylight time You can adjust your time like this:
INPUT SQL> select TO_CHAR(new_time(LOCALTIMESTAMP,'EsT','PDT'),'DD/MM/Y YYY HH : MI :SS PM') from DUAL; OUTPUT TO_CHAR(NEW_TIME(LOCALTIM ------------------------25/03/2007 04 : 32 :55 PM
89
ANALYSIS
Like magic, all the times are in the new time zone and the dates are adjusted.
90
NEXT_DAY( --------26-MAR-07 ANALYSIS If the sysdate is Saturday, March 24, 2007, It display the date of the next coming Monday.
EXTRACT
We can use Extract function in the place of to_char function from Oracle 9i.
SELECT EXTRACT(MONTH FROM SYSDATE) FROM DUAL; SELECT EXTRACT(DAY FROM SYSDATE) FROM DUAL SELECT EXTRACT(YEAR FROM SYSDATE) FROM DUAL
91
Example select (sysdate - to_date('10-jan-2004')) year to month from dual OUTPUT +000000003-10 Analysis Returns the difference. No of years and months between both the dates.
Example Select (sysdate - to_date('10-NOV-2007')) day to second from dual OUTPUT +000000009 11:04:07 Analysis Find the difference with days and time. For sysdate it takes 0.00 hrs as starting time
92
If you enter a date in the first half of the century (i.e. from 0 through 49), RR returns the current century.
If you enter a date in the latter half of the century (i.e. from 50 through 99), RR returns the previous century.
For example select to_char(sysdate,'dd/mm/yyyy') "current date", to_char(to_date('14-oct-88','dd-mon-rr'),'yyyy') "Year 88", to_char(to_date('14-oct-18','dd-mon-rr'),'yyyy') "year 18" from dual OUTPUT current date Year 88 year 18 ------------------------- -------------------- -------------------19/11/2007 1988 2018
When we reach the year 2050, RR will interpret the same dates differently
93
Siva Kumar HVK Going from Numbers to Intervals The NUMTOYMINTERVAL and NUMTODSINTERVAL functions allow you to convert a single numeric value to one of the interval data types. The function NUMTOYMINTERVAL (pronounced num to Y M interval) converts a numeric value an interval of type INTERVAL YEAR TO MONTH. SQL> select numtoyminterval (10.5,'year') from dual; NUMTOYMINTERVAL (10.5,'YEAR') ----------------------------------------------------------------------+000000010-06 SQL> select numtoyminterval (10.3,'year') from dual; NUMTOYMINTERVAL (10.3,'YEAR') ----------------------------------------------------------------------+000000010-03
Try the following formats SELECT NUMTOYMINTERVAL(10.5,MONTH) FROM DUAL; SELECT NUMTOYMINTERVAL(10.5,DAY) FROM DUAL; Name Description Some number of years ranging from 1 through YEAR
MONTH DAY HOUR MINUTE SECOND 999,999,999 Some number Some number Some number Some number of of of of months ranging from 0 through 11 days ranging from 0 through 999,999,999 hours ranging from 0 through 23 minutes ranging from 0 through 59
94
Siva Kumar HVK NUMTODSINTERVAL This function allows converting a single numeric value to one of the interval data types. This function (pronounced num to D S interval) likewise converts a numeric value to an interval of type INTERVAL DAY TO SECOND. Example SQL> select NUMTODSINTERVAL(1440,minute) from dual; OUTPUT +01 00:00.00.000000 ANALYSIS Oracle automatically taken care of normalizing the input value of 1440 minutes to an interval value of 1 day.
95
GREATEST --------83 ANALYSIS Displays the greatest of the given set of values Difference between GREATEST AND MAX IS 1) GREATEST IS SINGLE ROW FUNCTION, MAX IS A GROUP FUNCTION 2) GREATEST TAKES VALUES FROM DIFFERENT COLUMNS FROM EACH ROW, WHERE AS MAX TAKES VALUES FROM DIFFERENT ROWS FROM A COLUMN.
Assume there is a student table ROLLNO 1 2 3 4 NAME RAVI KRIS BABU ANU STUDENT SUB1 SUB2 55 22 78 55 55 22 44 55 SUB3 86 65 44 66 SUB4 45 12 77 88
96
INPUT: SQL> SELECT NAME,SUB1,SUB2,SUB3, SUB4, GREATEST(SUB1,SUB2,SUB3,SUB4) GREATEST_MARK, LEAST(SUB1,SUB2,SUB3,SUB4) LEAST_MARK FROM STUDENT OUTPUT: RNO NAME 1 2 3 4 USER
USER returns the character name of the current user of the database.
SUB1 SUB2 55 78 55 44 22 55 22 55
SUB3 SUB4 86 65 44 66 45 12 77 88
GREATEST MARK 86 78 77 88
LEAST MARK 22 12 22 44
97
The syntax example performs the DECODE function on column1. If column1 has a value of value1, then display output1 instead of the column's current value. If column1 has a value of value2, then display output2 instead of the column's current value. If column1 has a value of anything other than value1 or value2, then display output3 instead of the column's current value.
98
Siva Kumar HVK INPUT SQL> SELECT ENAME, JOB, DECODE(JOB,CLERK,EXEC,SALESMAN, S.OFFICER,ANALYST,PM,MANAGER,VP,JOB) PROMOTION FROM EMP; OUTPUT
ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER JOB --------CLERK SALESMAN SALESMAN MANAGER SALESMAN MANAGER MANAGER ANALYST PRESIDENT SALESMAN CLERK CLERK ANALYST CLERK PROMOTION --------EXEC S.OFFICER S.OFFICER VP S.OFFICER VP VP PM PRESIDENT S.OFFICER EXEC EXEC PM EXEC
ANALYSIS When JOB has a value CLERK , then display EXEC instead of CLERK When JOB has a value SALESMAN , then display S.OFFICER instead of SALESMAN When JOB has a value ANALYST , then display PM instead of ANALYST When JOB has a value MANAGER , then display VP instead of MANAGER OTHERWISE DISPLAY SAME JOB
99
OUTPUT
ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER JOB SAL NEW_SAL --------- ---------- ---------CLERK 800 880 SALESMAN 1600 1920 SALESMAN 1250 1500 MANAGER 2975 3867.5 SALESMAN 1250 1500 MANAGER 2850 3705 MANAGER 2450 3185 ANALYST 3000 3750 PRESIDENT 5000 5000 SALESMAN 1500 1800 CLERK 1100 1210 CLERK 950 1045 ANALYST 3000 3750 CLERK 1300 1430
ANALYSIS When JOB has a value CLERK , then giving 10% increment When JOB has a value SALESMAN , then giving 20% increment When JOB has a value ANALYST , then giving 25% increment When JOB has a value MANAGER , then giving 30% increment OTHERWISE no increment
INPUT SQL> SELECT ENAME, SEX, DECODE(SEX,MALE,MR.||ENAME, MS.||ENAME) FROM EMP; ANALYSIS Adding Mr. or Ms. before the name based on their Gender
100
Example
SQL> SELECT JOB, CASE JOB WHEN 'MANAGER' then 'VP' WHEN 'CLERK' THEN 'EXEC' WHEN 'SALESMAN' THEN 'S.OFFICER' ELSE JOB END FROM EMP; JOB --------CLERK SALESMAN SALESMAN MANAGER SALESMAN MANAGER MANAGER ANALYST PRESIDENT SALESMAN CLERK CLERK ANALYST CLERK CASEJOBWH --------EXEC S.OFFICER S.OFFICER VP S.OFFICER VP VP ANALYST PRESIDENT S.OFFICER EXEC EXEC ANALYST EXEC
101
SYNTAX
NVL(value, substitute)
INPUT SQL> SELECT EMPNO,SAL,COMM, SAL + COMM TOTAL FROM EMP; OUTPUT
EMPNO SAL COMM TOTAL ---------- ---------- ---------- ---------7369 800 7499 1600 300 1900 7521 1250 500 1750 7566 2975 7654 1250 1400 2650 7698 2850 7782 2450 7788 3000 7839 5000 7844 1500 0 1500 7876 1100 7900 950 7902 3000 7934 1300
ANALYSIS Arithmetic operation is possible only when value is there in both columns
102
Siva Kumar HVK INPUT SQL> SELECT EMPNO,SAL,COMM, SAL + NVL(COMM,0) TOTAL FROM EMP; OUTPUT
EMPNO SAL COMM TOTAL ---------- ---------- ---------- ---------7369 800 800 7499 1600 300 1900 7521 1250 500 1750 7566 2975 2975 7654 1250 1400 2650 7698 2850 2850 7782 2450 2450 7788 3000 3000 7839 5000 5000 7844 1500 0 1500 7876 1100 1100 7900 950 950 7902 3000 3000 7934 1300 1300
103
SQL> SELECT ENAME,LENGTH(ENAME) FROM EMP; SQL> SELECT LENGTH(SYSDATE) FROM EMP; SQL> SELECT SAL,LENGTH(SAL) FROM EMP;
ASCII
Finds the ASCII value of the given character
CAST Converts one type of information into another type SQL> SELECT 50 numb, cast(50 as varchar2(2) value from dual;
104
105
Siva Kumar HVK Course Day Session Estimated Time : : : : Oracle 2 3 3 Hrs
Exercise
Annexure
Query - I
106
Siva Kumar HVK Course Day Session Estimated Time : : : : Oracle 2 4 3 Hrs
Revision
107
Topics Group by clause CUBE and ROLLUP functions Having clause Exercise
108
109
INPUT SQL> SELECT JOB, COUNT (*) FROM EMP GROUP BY JOB; OUTPUT
JOB COUNT(*) --------- ---------ANALYST 2 CLERK 4 MANAGER 3 PRESIDENT 1 SALESMAN 4
ANALYSIS
Counts number of employees under each and every job. When we are grouping on job, initially jobs are placed in ascending order in a temporary segment. On the temporary segment, group by clause is applied, so that on each similar job count function applied.
INPUT SQL> SELECT JOB, SUM (SAL) FROM EMP GROUP BY JOB; OUTPUT
JOB SUM(SAL) --------- ---------ANALYST 6000 CLERK 4150 MANAGER 8275 PRESIDENT 5000 SALESMAN 5600
110
INPUT SQL> SELECT JOB,COUNT(*) FROM EMP; OUTPUT SELECT JOB, COUNT (*) FROM EMP * ERROR at line 1: ORA-00937: not a single-group group function ANALYSIS This result occurs because the group functions, such as SUM and COUNT, are designated to tell you something about a group or rows, not the individual rows of the table. This error is avoided by using JOB in the group by clause, which forces the COUNT to count all the rows grouped within each job.
INPUT SQL> SELECT JOB,ENAME,COUNT(*) FROM EMP GROUP BY JOB; OUTPUT SELECT JOB,ENAME,COUNT(*) FROM EMP GROUP BY JOB * ERROR at line 1: ORA-00979: not a GROUP BY expression ANALYSIS In the above query, JOB is only the grouped column where as ENAME column is not a grouped column. What ever the columns we are grouping, the same column is allowed to display.
111
INPUT SQL> SELECT JOB, MIN(SAL),MAX(SAL) FROM EMP GROUP BY JOB; OUTPUT
JOB MIN(SAL) MAX(SAL) --------- ---------- ---------ANALYST 3000 3000 CLERK 800 1300 MANAGER 2450 2975 PRESIDENT 5000 5000 SALESMAN 1250 1600
ANALYSIS
INPUT SQL> SELECT JOB, SUM(SAL),AVG(SAL),MIN(SAL),MAX(SAL) ,COUNT(*) FROM EMP GROUP BY JOB; OUTPUT
JOB SUM(SAL) AVG(SAL) MIN(SAL) MAX(SAL) COUNT(*) --------- ---------- ---------- ---------- ---------- ---------ANALYST 6000 3000 3000 3000 2 CLERK 4150 1037.5 800 1300 4 MANAGER 8275 2758.33333 2450 2975 3 PRESIDENT 5000 5000 5000 5000 1 SALESMAN 5600 1400 1250 1600 4
112
INPUT
SQL> SELECT JOB,SUM(DECODE(DEPTNO,10,SAL)) DEPT10, SUM(DECODE(DEPTNO,20,SAL)) DEPT20, SUM(DECODE(DEPTNO,30,SAL)) DEPT30, SUM(SAL) TOTAL FROM EMP GROUP BY JOB; OUTPUT JOB DEPT10 DEPT20 DEPT30 TOTAL --------- ---------- ---------- ---------- ---------ANALYST 6000 6000 CLERK 1300 1900 950 4150 MANAGER 2450 2975 2850 8275 PRESIDENT 5000 5000 SALESMAN 5600 5600
ANALYSIS When we apply group by, initially all the designations are placed in ascending order of designations. Then group by clause groups similar designations, then DECODE function (Single row function) applies on each and every row of that group and checks the DEPTNO. If DEPTNO=10, it passes corresponding salary as an argument to SUM() . INPUT SQL> SELECT DEPTNO,JOB,COUNT(*) FROM EMP GROUP BY DEPTNO,JOB; OUTPUT
DEPTNO ---------10 10 10 20 20 20 30 30 30 ANALYSIS JOB COUNT(*) --------- ---------CLERK 1 MANAGER 1 PRESIDENT 1 CLERK 2 ANALYST 2 MANAGER 1 CLERK 1 MANAGER 1 SALESMAN 4
113
114
Use Rollup or CUBE with Group by to produce super aggregate rows by cross-referencing columns. ROLLUP grouping produces a result set containing the regular grouped rows and the subtotal values. CUBE grouping produces a result set containing the rows from ROLLUP and cross-tabulation rows
The ROLLUP and CUBE operators are available only in Oracle8i and later releases.
Syntax SELECT [column,] group_function(column)... FROM table [WHERE condition] [GROUP BY [CUBE] group_by_expression] [HAVING having_expression] [ORDER BY column];
115
Cube displays the out with all the permutation and combination of all the columns given a CUBE function.
116
117
To Display only those designations, whose total salary is more than 5000
INPUT SQL> SELECT JOB,SUM(SAL) FROM EMP WHERE SUM(SAL) > 5000 GROUP BY JOB; OUTPUT
SELECT JOB,SUM(SAL) FROM EMP WHERE SUM(SAL) > 5000 GROUP BY JOB * ERROR at line 1: ORA-00934: group function is not allowed here
ANALYSIS
Where clause doesnt allow using group function in the condition. When we are using group function in the condition, we have to use having clause.
118
Siva Kumar HVK INPUT SQL> SELECT JOB,SUM(SAL) FROM EMP GROUP BY JOB HAVING SUM(SAL) > 5000; OUTPUT
JOB SUM(SAL) --------- ---------ANALYST 6000 MANAGER 8275 SALESMAN 5600
ANALYSIS
Displays all the designations whose total salary is more than 5000.
INPUT SQL> SELECT JOB,COUNT(*) FROM EMP GROUP BY JOB HAVING COUNT(*) BETWEEN 3 AND 5; OUTPUT
JOB COUNT(*) --------- ---------CLERK 4 MANAGER 3 SALESMAN 4
ANALYSIS
Displays all the designations whose number where employees between 3 and 5
119
OUTPUT
SAL ---------1250 3000
ANALYSIS
Displays all the salaries, which are appearing more than one time in the table.
POINTS TO REMEMBER WHERE clause can be used to check for conditions based on values of columns and expressions but not the result of GROUP functions. HAVING clause is specially designed to evaluate the conditions that are based on group functions such as SUM , COUNT etc. HAVING clause can be used only when GROUP BY clause is used.
120
Siva Kumar HVK ORDER OF EXECUTION Here are the rules ORCALE uses to execute different clauses given in SELECT command Selects rows based on Where clause Groups rows based on GROUP BY clause Calculates results for each group Eliminate groups based on HAVING clause Then ORDER BY is used to order the results
Example INPUT SQL> SELECT JOB,SUM (SAL) FROM EMP WHERE JOB != CLERK GROUP BY JOB HAVING SUM(SAL) > 5000 ORDER BY JOB DESC;
121
122
Topics Nested Sub Queries Single row Sub queries Multi Row Sub query Multi column Sub query Co-related Sub query Scalar Sub Queries ANY ALL and EXISTS Exercise
123
Whenever particular information is not accessible through a single query, then we have to write different queries one included in another. Sub queries can be nested as deeply as your implementation of SQL allows. We can write different types sub queries Single row sub queries Multi row sub queries Multi column sub queries Correlated sub queries.
124
For example,
To get the employee, who is drawing maximum salary?
INPUT SQL> SELECT ENAME,SAL FROM EMP WHERE SAL = ( SELECT MAX(SAL) FROM EMP); OUTPUT ENAME -----------KING
SAL ---------5000
ANALYSIS Right side query is called as child query and left side query is called parent query. In nested queries, child query executes first before executing parent query.
INPUT SQL> SELECT ENAME, HIREDATE FROM EMP WHERE HIREDATE = ( SELECT MAX(HIREDATE) FROM EMP); OUTPUT ENAME HIREDATE ---------- --------ADAMS 12-JAN-83 ANALYSIS Display the least experienced employee
125
INPUT SQL> SELECT ENAME,SAL FROM EMP WHERE SAL < (SELECT MAX(SAL) FROM EMP); OUTPUT
ENAME SAL ---------- ---------SMITH 800 ALLEN 1600 WARD 1250 JONES 2975 MARTIN 1250 BLAKE 2850 CLARK 2450 SCOTT 3000 TURNER 1500 ADAMS 1100 JAMES 950 FORD 3000 MILLER 1300 ANALYSIS Display all the employees whose salary is less than the maximum salary of all the employees.
Query
To display all the employees whose salary lines between minimum and maximum salaries
INPUT SQL> SELECT * FROM EMP WHERE SAL BETWEEN (SELECT MIN(SAL) FROM EMP) AND (SELECT MAX(SAL) FROM EMP);
126
SQL> SELECT * FROM EMP WHERE COMM = (SELECT MAX(COMM) FROM EMP); Query
Display all the employees from department 30 whose salary is less than maximum salary of department 20.
SQL> SELECT EMPNO,ENAME,SAL FROM EMP WHERE DEPTNO=30 AND SAL < (SELECT MAX (SAL) FROM EMP WHERE DEPTNO = 20);
INPUT SQL>SELECT ENAME,SAL FROM EMP WHERE SAL IN(SELECT SAL FROM EMP GROUP BY SAL HAVING COUNT(*)> 1); OUTPUT ENAME ---------- WARD MARTIN SCOTT FORD
ANALYSIS Displays all the employees who are drawing similar salaries When child query returns more than one value, we have to use IN operator for comparison.
127
SQL> SELECT EMPNO,ENAME,DEPTNO,SAL FROM EMP WHERE (DEPTNO,SAL)IN (SELECT DEPTNO,MAX(SAL) FROM EMP GROUP BY DEPTNO);
OUTPUT EMPNO ---------7839 7788 7902 7698 ENAME DEPTNO SAL ---------- ---------- ---------KING 10 5000 SCOTT 20 3000 FORD 20 3000 BLAKE 30 2850
ANALYSIS Display all the employees who are drawing maximum salaries in each department
INPUT SQL> UPDATE EMP SET SAL = (SELECT MAX(SAL) FROM EMP) WHERE EMPNO = (SELECT EMPNO FROM EMP WHERE SAL = (SELECT MIN (SAL) FROM EMP)); ANALYSIS Identify the employee who is drawing minimum salary and update with the maximum salary of all the employees.
128
INPUT SQL> INSERT INTO EMP1 SELECT * FROM EMP ; ANALYSIS EMP1 is an existing table. Inserts all the selected rows into EMP1 table.
129
ANALYSIS Find department wise maximum salaries and display the employees whose salary is less than that value for each department
130
ANALYSIS It selects each row from emp table from parent query and finds the distinct count for each salary whose salary >= the salary returned by main query.
A Few More Examples on Correlated Subqueries: 1. Display the employees who are not getting max sal in each dept? A. select e.ename, e.deptno, e.sal from emp e where e.sal<(select max(sal) from emp where deptno = e.deptno); 2. Display the details of employee who is drawing nth max sal from emp table? A. select ename, sal, deptno from emp e where &n = (select count(*) from emp where sal > x.sal); 3. Display the employees who are earning more than the avg salary in thier respective depts? A. select ename, sal, deptno from emp e where sal > (select avg(sal) from emp where deptno = e.deptno); 4. Display the employees who have atleast one person reportig to them? A. select empno, ename, job, deptno from emp e where exists (select 1 from emp where mgr = e.empno); 5. Display the employees who have no one reporting to? A. select empno, ename, job, deptno from emp e where exists (select 1 from emp where mgr = e.empno); 6. Find the deptnos which doesnt have any emps in it? A. select deptno, dname from dept d where not exists (select 1 from emp where deptno = d.deptno); 7. Display all the employee details under the deptnos which have less than N number of employees in it? A. select distinct deptno,empno,sal from emp e where &n >= (select count(*) from emp where deptno = e.deptno); OR select deptno,ename,empno,sal from emp e
131
Table joins should be written first before any condition of WHERE clause. And the conditions which filter out the maximum records should be placed at the end after the joins as the parsing is done from BOTTOM to TOP.
132
INPUT SQL> SELECT EMPNO,ENAME,SAL FROM EMP WHERE SAL > ANY(SELECT SAL FROM EMP); OUTPUT EMPNO ---------7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934 ENAME SAL ---------- ---------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
133
INPUT SQL> SELECT EMPNO,ENAME,SAL FROM EMP WHERE SAL < ANY (SELECT SAL FROM EMP); OUTPUT EMPNO ---------7369 7499 7521 7566 7654 7698 7782 7788 7844 7876 7900 7902 7934 ENAME SAL ---------- ---------SMITH 800 ALLEN 1600 WARD 1250 JONES 2975 MARTIN 1250 BLAKE 2850 CLARK 2450 SCOTT 3000 TURNER 1500 ADAMS 1100 JAMES 950 FORD 3000 MILLER 1300
INPUT SQL> SELECT EMPNO,ENAME,SAL FROM EMP WHERE SAL >ALL(SELECT SAL FROM EMP); OUTPUT no rows selected
134
INPUT SQL> SELECT EMPNO,ENAME,SAL FROM EMP WHERE SAL >ALL(3000,2000,4000); OUTPUT EMPNO ENAME SAL ---------- ---------- ---------7839 KING 5000
INPUT SQL> SELECT EMPNO,ENAME,SAL FROM EMP WHERE SAL <ALL(3000,2000,4000); OUTPUT EMPNO ---------7369 7499 7521 7654 7844 7876 7900 7934 ENAME SAL ---------- ---------SMITH 800 ALLEN 1600 WARD 1250 MARTIN 1250 TURNER 1500 ADAMS 1100 JAMES 950 MILLER 1300
135
EXISTS is different from other operators like IN , ANY etc, because it doesnt compare values of columns, instead. It checks any row is retrieved from sub query or not. If any row is retrieved from sub query the EXISTS returns true otherwise it returns False.
INPUT SQL> SELECT EMPNO,ENAME,SAL,MGR FROM EMP X WHERE EXISTS(SELECT MGR FROM EMP WHERE X.MGR = EMPNO); OUTPUT EMPNO ---------7369 7499 7521 7566 7654 7698 7782 7788 7844 7876 7900 7902 7934
ENAME SAL MGR ---------- ---------- ---------SMITH 800 7902 ALLEN 1600 7698 WARD 1250 7698 JONES 2975 7839 MARTIN 1250 7698 BLAKE 2850 7839 CLARK 2450 7839 SCOTT 3000 7566 TURNER 1500 7698 ADAMS 1100 7788 JAMES 950 7698 FORD 3000 7566 MILLER 1300 7782
Note :Use EXISTS in place of IN for Base Tables to improve the performance.
Remember
The following important points to be remembered while dealing with sub queries Sub query can not use ORDER BY clause. Because ORDER BY clause must be the last clause of SELECT BETWEEN AND operator can not be used with Sub queries
136
137
Exercise Annexure
Query III
138
Revision / Doubts
139
Siva Kumar HVK Course Day Session Duration : : : : Oracle 4 1&2 5 Hrs
Topics Integrity Constraints DDL and DML commands Transactional Control statements Referential Integrity constraints Exercise
140
INTEGRITY CONSTRAINTS
Constraints are used to implement standard rules such as uniqueness in the key filed and business rule such as AGE column should contain a value between 15 and 60 etc. Oracle server makes sure that the constraints are not violated whenever a row is inserted, deleted or updated. If constraint is not satisfied the operation will fail. Constraints are normally defined at the time of creating table. But it is also possible to define constraints after the table is created.
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
141
Table Constraint A constraint given at the table level is called as Table Constraint. It may refer to more than one column of the table.
A typical example is PRIMARY KEY constraint that is used to define composite primary key.
Various types of Integrity constraints PRIMARY KEY UNIQUE NOT NULL CHECK
142
Example : EmailID
A UNIQUE key integrity constraint requires that every value in a column or set of columns (key) be unique- that is, no two rows of table can have duplicate values in a specified column or set of columns. The column (or set of columns) included in the definition of the UNIQUE key constraint is called the unique key. If the UNIQUE constraint comprises more than one column, the group of columns is called a composite unique key. NOT NULL Uniqueness not maintained and null values are
not acceptable. Note: The NOT NULL constraint can be specified only at the column level, not at the table level.
CHECK
Defines the condition that should be satisfied before insertion and updating is done. Defines a condition that each row must satisfy The following expressions are not allowed - References to CURRVAL, NEXTVAL and ROWNUM pseudocolumns - Calls to SYSDATE,UID,USER functions - Queries that refer to other values in other rows
Note: - Pseudocolumns are not actual columns in a table but they behave like columns. For example, you can select clause from pseudo columns. However, you cannot insert into, update, or delete from a pseudocolumn.
143
Create Table CREATE TABLE <TABLE-NAME> (COLUMN DEFINITION1, COLUMN DEFINITION2); Syntax :Column Def : <Name> Data type [Default Value] [constraint <name> constraint type] Note: = Min. Column in a table = 1 Max. Columns in a table = 1000
Rules: 1. A table or a column name must never start a number but they can contain numbers in them 2. They cant consist of any special characters other than $, #, - i.e. $,# are used mainly for system tables.
Example :
SQL>CREATE TABLE EMPL47473 (EMPNO NUMBER(3)CONSTRAINT PK_EMPL47473_EMPNO PRIMARY KEY, ENAME VARCHAR2 (10) NOT NULL, GENDER CHAR(1) CONSTRAINT CHK_EMPL47473_GENDER CHECK(UPPER (GENDER) IN (M,F)), EMAIL_ID VARCHAR2 (30) UNIQUE, DESIGNATION VARCHAR2 (15), SALARY NUMBER (7,2) CHECK (SALARY BETWEEN 10000 AND 70000));
144
SQL> DESCRIBE USER_CONSTRAINTS SQL> SELECT CONSTRAINT_NAME, CONSTRAINT_TYPE, SEARCH_CONDITION FROM USER_CONSTRAINTS WHERE TABLE_NAME = 'EMPL47473'; OUTPUT
CONSTRAINT_NAME CONSTRAINTTYPE SEARCH_CONDITION
---------------------------- ------------------------------------------------------SYS_C003018 C "ENAME" IS NOT NULL CHK_EMPL47473_GENDER SYS_C003020 PK_EMPL47473_EMPNO ANALYSIS C C P UPPER (GENDER) IN ('M','F') SALARY BETWEEN 10000 AND 70000 SYS_C003022
Describe displays structure of the data dictionary table. Select statement is used to view the constraints defined on the table
145
OUTPUT
CONSTRAINT_NAME --------------------------------CHK_EMPL47473_GENDER PK_EMPL47473_EMPNO SYS_C003018 SYS_C003020 SYS_C003022 COLUMN_NAME - ---------------------------GENDER EMPNO ENAME SALARY EMAIL_ID
ANALYSIS Describe displays structure of the data dictionary table. Select statement is used to view the constraints defined on the column
146
SYNTAX ALTER TABLE <TABLENAME> [ ADD | MODIFY | DROP | RENAME] ( COLUMN(S)); ADD MODIFY DROP RENAME - for adding new columns into the table - for modifying the structure of columns - for removing a column in the table ( 8i) - for renaming the column name ( Only from 9i)
SQL> ALTER TABLE EMPL47473 ADD (ADDRESS VARCHAR2 (30), DOJ DATE,PINCODE VARCHAR2(7)); SQL> ALTER TABLE EMPL47473 MODIFY (ENAME CHAR (15), SALARY NUMBER (8,2)); SQL> ALTER TABLE EMPL47473 DROP COLUMN PINCODE; SQL> ALTER TABLE EMPL47473 DROP (DESIGNATION,ADDRESS); SQL> ALTER TABLE EMPL47473 RENAME COLUMN ENAME TO EMPNAME
Note: This command is also useful for manipulating constraints INPUT SQL> ALTER TABLE EMPL47473 DROP PRIMARY KEY; ANALYSIS
To remove the primary key from table. Other constraints are removed only by referring constraint name.
INPUT SQL>ALTER TABLE EMPL47473 ADD PRIMARY KEY(EMPNO); ANALYSIS To add primary key in the table without constraint name. It creates constraint name with SYS_Cn.
147
INPUT SQL>ALTER TABLE EMPL47473 ADD CONSTRAINT PK_EMPL47473_EMPNO PRIMARY KEY(EMPNO); ANALYSIS To add primary key in the table with constraint name DATA MANIPULATION INSERTING ROWS SYNTAX INSERT INTO TABLENAME [ COLUMNNAME,COLUMNNAME,.] VALUES(VALUE1 VALUE2 VALUE3
SQL> INSERT INTO EMPL47473 VALUES(101,RAVI,M, RAMESH_B@YAHOO.COM,5000,10-JAN-2001); OR SQL> INSERT INTO EMPL47473 VALUES(&EMPNO , &EMPNAME,&GENDER,&EMAIL_ID,&SALARY,&DOJ);
TO INSERT SPECIFIED COLUMNS IN THE TABLE SQL> INSERT INTO EMPL47473(EMPNO,EMPNAME,SALARY) VALUES(101,RAVI, 5000); OR SQL> INSERT INTO EMPL47473(EMPNO,EMPNAME,SALARY) VALUES(&EMPNO,7EMPNAME,&SALARY); ANALYSIS We cant skip primary key and NOT NULL columns
148
Siva Kumar HVK Note :- Changes made on the database are recorded only in the shadow page. For saving the information we have to use a command COMMIT, ROLLBACK.SAVEPOINT ( Called as Transactional processing statements) SQL>COMMIT; ANALYSIS Information from shadow page flushed back to the table and shadow page gets destroyed automatically.
SQL>ROLLBACK; ANALYSIS Shadow page destroys automatically without transferring the information back to the table. SAVEPOINT
We can use save points to roll back portions of your current set of transactions For example
149
The output shows the three new records weve added . Now roll back just the last insert:
SQL> ROLLBACK TO B;
IMPLICIT COMMIT The actions that will force a commit to occur, even without your instructing it to, or quit, exit (the equivalent to exit), any DDL command forces a commit.
AUTO ROLLBACK
If youve completed a series of inserts, updates or deletes, but not yet explicitly or implicitly committed them, and you experience serious difficulties, such as a computer failure, Oracle automatically roll back any uncommitted work. If the machine or database goes down, it does this as cleanup work the next time the database is brought back up.
Note :
Rollback works only on uncommitted data A DDL transaction after a DML transaction, automatically commits. We can use an Environment command SET VERIFY OFF to remove the old and new messages while inserting data.
150
151
Siva Kumar HVK CREATING A TABLE FROM ANOTHER TABLE SYNTAX CREATE TABLE <TABLENAME> AS SELECT <COLUMNS> FROM <EXISTING TABLE> [WHERE <CONDITION>];
To add a new column in the table SQL> ALTER TABLE EMP47473 ADD(SEX CHAR(1)); SQL> SELECT * FROM EMP47473;
UPDATING ROWS
This command is used to change the data of the table
SYNTAX UPDATE <TABLENAME> SET column1 = expression, column2 = expression WHERE <condition>; SQL> UPDATE EMP47473 SET SAL = SAL*1.1; SQL> COMMIT / ROLLBACK; ANALYSIS To give uniform increments to all the employees
152
SQL> UPDATE EMP47473 SET SEX = M WHERE ENAME IN (KING,MILLER,BLAKE); SQL> COMMIT / ROLLBACK; SQL> SELECT * FROM EMP47473;
SQL> UPDATE EMP47473 SET SEX = F WHERE SEX IS NULL; SQL> COMMIT / ROLLBACK; SQL> SELECT * FROM EMP47473 ;
SQL> UPDATE EMP47473 SET ENAME = DECODE(SEX,M,Mr.||ENAME,Ms.||ENAME); SQL> COMMIT / ROLLBACK; ANALYSIS ADD Mr. or Ms. Before the existing name as per the SEX value
153
TRUNCATING A TABLE SYNTAX TRUNCATE TABLE <TABLENAME> Note : Removes all the rows from table. Deleting specified rows is Not possible. Once the table is truncated, it automatically commits. It is a DDL statement
Droping a table
SYNTAX
DROP TABLE <TABLENAME> Note : Table is dropped permanently. It is a DDL statement. It removes the data along with table definitions and the table.
154
Siva Kumar HVK Adding comments to a table You can add comments up to 2000 bytes about a column, table, view by using the COMMENT statement. The comment is stored in the data dictionary and can be viewed in one of the following data dictionary views in the COMMENTS column: ALL_COL_COMMENTS USER_COL_COMMENTS ALL_TAB_COMMENTS USER_TAB_COMMENTS
155
References
table
Example
Department47473 (Deptno , dname) Employee47473 (Empno, ename, salary, dno) Deptno of Department47473 is a primary key Empno of Employee47473 is a primary key Dno of Employee47473 is a reference key
156
SQL>Create table department47473 (deptno number(3) primary key, dname varchar2(20) Not null); SQL>Create table employee47473(empno number(3) primary key, ename varchar2(10) Not null, salary number(7,2) check(salary > 0), dno number(3) references department47473(deptno) on delete cascade);
Assume the case where supermarket selling various items and customers order the items.
SQL>Create table itemmaster (itemno number (3) primary key, itemname varchar2 (10), stock number (3) check (stock > 0)); SQL>Create table itemtran (trnno number (3), itemno number (3) references itemmaster (itemno), trndate date, trntype char (1) check (upper (trntype) in (R,I)), quantity number (3) check (quantity > 0), primary key (trnno, itemno));
Itemno Trnno
quantity
Assume the case where with each transaction customer orders more than one item.
157
DROP TABLE <TABLENAME> CASCADE CONSTRAINTS ANALYSIS Dropping the table along with constraints
ALTER TABLE <tablename> DROP PRIMARY KEY CASCADE; ANALYSIS Removing the primary key along with Reference key
ALTER TABLE <TABLENAME> DISABLE PRIMARY KEY ALTER TABLE <tablename> DISABLE PRIMARY KEY CASCADE; Note : It is not possible to enable using cascade
158
159
Topics Joins
160
JOINS Objectives
Join will enable you to gather and manipulate data across several tables. By One of the most powerful features of SQL is its capability to gather and manipulate data from across several tables. Without this feature you would have to store all the data elements necessary for each application in one table. Without common tables you would need to store the same data in several tables.
Objectives After completing this lesion, you should be able to do the following. Write SELECT statements to access data from more than one table using equality and nonequality join. View Data that generally does not meet condition by using outer joins Join a table itself by using self join a join
161
Siva Kumar HVK TYPES OF JOINS Oracle Proprietary Joins(8i and prior) EquiJoin Non-equi join Outer join SelfJoin SQL:1999 Compliant Joins: Cross Joins Natural Joins Using caluse Full or two sided outer join Arbitrary join conditions For Outer joins
Types of Joins
The Oracle 9i database offers join syntax that is SQL: 1999 compliant. Prior to 9i release, the join syntax was different from the ANSI standards. The new SQL: 1999 compliant join syntax does not offer any performance benefits over the Oracle proprietary join syntax that existed in prior releases.
162
Guidelines When writing a SELECT statement that joins tables, precede the common column name with the table name for clarify 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. This rule many not apply if your table has a concatenated primary key, in which case more than one column is required to uniquely identify each row.
163
Departments
Employees
164
ANALYSIS Efficiency is more when we compare the information from lower data table(master table) to Higher data table( child table). When Oracle processes multiple tables, it uses an internal sort/merge procedure to join those tables. First, it scans & sorts the first table (the one specified last in FROM clause). Next, it scans the second table (the one prior to the last in the FROM clause) and merges all of the retrieved from the second table with those retrieved from the first table. It takes around 0.96 seconds
165
Non-Equi joins
Getting the information from more than one table without using comparison (=) operator.
INPUT SQL> select empno,ename,sal,grade,losal,hisal from salgrade g,emp e where e.sal between g.losal and g.hisal / ANALYSIS Displays all the employees whose salary lies between any pair of low and high salary ranges.
INPUT SQL> SELECT * FROM DEPT WHERE DEPTNO NOT IN (SELECT DISTINCT DEPTNO FROM EMP); OUTPUT DEPTNO DNAME LOC ---------- -------------------------40 OPERATIONS BOSTON ANALYSIS Displays the details of the department where there are no employees
166
SQL> SELECT DEPTNO FROM DEPT MINUS SELECT DEOTNO FROM EMP;
SQL> SELECT DEPTNO FROM DEPT UNION SELECT DEOTNO FROM EMP; SQL> SELECT DEPTNO FROM DEPT UNION ALL SELECT DEOTNO FROM EMP;
167
OUTPUT
EMPNO ---------7782 7839 7934 7369 7876 7902 7788 7566 7499 7698 7654 7900 7844 7521 ENAME JOB SAL DNAME ---------- --------- ---------- ------------CLARK KING MILLER SMITH ADAMS FORD SCOTT JONES ALLEN BLAKE MARTIN JAMES TURNER WARD MANAGER PRESIDENT CLERK CLERK CLERK ANALYST ANALYST MANAGER SALESMAN MANAGER SALESMAN CLERK SALESMAN SALESMAN 2450 5000 1300 800 1100 3000 3000 2975 1600 2850 1250 950 1500 1250 ACCOUNTING ACCOUNTING ACCOUNTING RESEARCH RESEARCH RESEARCH RESEARCH RESEARCH SALES SALES SALES SALES SALES SALES OPERATIONS
168
ANALYSIS Gets the common information, and forcibly joins from left side table to right side table.
169
ANALYSIS Gets the common information from both tables, then forcibly joins from dept table to emp table.
ANALYSIS Gets the common information from both tables, and then forcibly joins from dept table to emp table.
170
ANALYSIS Gets the common information from both tables, then forcibly joins from dept table to emp table.
171
SQL> SELECT WORKER.ENAME || ' IS WORKING UNDER ' || MANAGER.ENAME FROM EMP WORKER, EMP MANAGER WHERE WORKER.MGR = MANAGER.EMPNO;
OUTPUT WORKER.ENAME||'ISWORKINGUNDER'||MANAGE -------------------------------------SCOTT IS WORKING UNDER JONES FORD IS WORKING UNDER JONES ALLEN IS WORKING UNDER BLAKE WARD IS WORKING UNDER BLAKE JAMES IS WORKING UNDER BLAKE TURNER IS WORKING UNDER BLAKE MARTIN IS WORKING UNDER BLAKE MILLER IS WORKING UNDER CLARK ADAMS IS WORKING UNDER SCOTT JONES IS WORKING UNDER KING CLARK IS WORKING UNDER KING BLAKE IS WORKING UNDER KING SMITH IS WORKING UNDER FORD ANALYSIS It displays who is working under whom. MGR number appearing against employee is the employee number of manager
172
Creating Natural Joins The Natural join clause is based on all columns in the two tables that have the same name, It selects rows from the two tables that have equal values in all matched columns. If the columns having the same names have different data types, an error is returned.
For example, To get the common information from two tables,
INPUT SQL> SELECT EMPNO,ENAME,JOB,DEPTNO,DNAME FROM DEPT 2 NATURAL JOIN EMP; OUTPUT EMPNO ---------7782 7839 7934 7369 7876 7902 7788 7566 7499 7698 7654 7900 7844 7521 ENAME ---------CLARK KING MILLER SMITH ADAMS FORD SCOTT JONES ALLEN BLAKE MARTIN JAMES TURNER WARD JOB DEPTNO DNAME --------- ---------- -------------MANAGER 10 ACCOUNTING PRESIDENT 10 ACCOUNTING CLERK 10 ACCOUNTING CLERK 20 RESEARCH CLERK 20 RESEARCH ANALYST 20 RESEARCH ANALYST 20 RESEARCH MANAGER 20 RESEARCH SALESMAN 30 SALES MANAGER 30 SALES SALESMAN 30 SALES CLERK 30 SALES SALESMAN 30 SALES SALESMAN 30 SALES
173
174
INNER JOIN
Support for INNER join syntax was introduced in Oracle9i, inner joins are the default they return the rows the two tables have in common, and are the alternative to outer joins. Note that they support ON clause, so that you can specify join criteria.
SQL>SELECT EMPNO, ENAME, JOB, DEPT.DEPTNO, DNAME FROM EMP INNER JOIN DEPT ON EMP.DEPTNO = DEPT.DEPTNO;
INPUT SQL> SELECT * FROM DEPT,EMP; OR SQL> SELECT * FROM EMP CROSS JOIN DEPT; ANALYSIS It multiplies the rows from both tables and displays the output i.e. 14 rows (emp table) X 4 rows(dept table) = 56 rows.
175
EXERCISE
ANNEXURE
QUERY III
176
177
SYNTAX CREATE SEQUENCE sequence [INCREMENT BY n] [START WITH n] [{MAXVALUE n | NOMAXVALUE}] [{MINVALUE n | NOMINVALUE}] [{CYCLE | NOCYCLE}] [{CACHE n | NOCACHE}];
Sequence is the name of the sequence generator INCREMENT BY n specifies the interval between sequence numbers where n is an integer (If this clause is omitted, the sequence increments by 1.) START WITH n specifies the first sequence number to be generated (If this clause is omitted, the sequence starts with 1.) MAXVALUE n specifies the maximum value the sequence can generate NOMAXVALUE specifies a maximum value of 10^27 for an ascending sequence and 1 for a descending sequence (This is the default option.) MINVALUE n specifies the minimum sequence value NOMINVALUE specifies a minimum value of 1 for an ascending sequence and (10^26) for a descending sequence (This is the default option.)
CYCLE | NOCYCLE specifies whether the sequence continues to generate values after reaching its maximum or minimum value (NOCYCLE is the default Option.) CACHE n | NOCACHE specifies how many values the Oracle server preallocates and keep in memory (By default, the Oracle server caches 20 values.) The value set must be less than MAXVALUE minus
178
Example
CREATE SEQUENCE SQNO47473 START WITH 1 INCREMENT BY 1 MAXVALUE 10;
Note: - These sequences are stored in a data dictionary table USER_SEQUENCES. This sequence object provides two public member functions NEXTVAL and CURRVAL NEXTVAL is a function which generate next value from sequence object CURRVAL is a function, which gives the current value of the sequence object
179
TO MODIFY THE SEQUNECE OBJECT SQL> ALTER SEQUENCE SQNO47473 INCREMENT BY 2 MAXVALUE 40; Note : We cant change starting value
VIEWS 180
SIMPLE view is a view, which is created using only one base table. COMPLEX view is a view, which is created using more than one table or using group functions INLINE view is a view, which is created using sub query (it is not a schema object. It is a named sub query in the FROM clause of the main query. Generally used in TOP N Analysis.
SYNTAX CREATE OR REPLACE [FORCE] VIEW <VIEWNAME> AS SELECT <COLUMNS> FROM <TABLE > [ WITH READ ONLY];
The table on which a view is based is called as base table FORCE option allows view to be created even if the base table doesnt exist. However, the base table should exist before the view is used.
Example
SQL> CREATE OR REPLACE VIEW TESTVIEW47473 AS SELECT EMPNO,ENAME,SAL FROM EMP47473;
182
SQL> CREATE OR REPLACE VIEW TESTVIEW47473 AS SELECT EMPNO, ENAME,SAL FROM EMP47473 WITH READ ONLY;
ANALYSIS View becomes a read only view
It doesnt allow you to update the condition column as well as it doesnt allow you to insert the details of employees with DEPTNO other than 20.
We can also create a view using group functions. Such views are called as INLINE views. They are by default read only.
INDEX 183
SELECT doesnt contain WHERE clause When the data size is less SELECT contains WHERE clause, but WHERE clause doesnt refer to indexed column.
184
FUNCTIONAL INDEX
As of Oracle8i, we can create functional-based indexes. When we are storing alpha-numeric information, we may store the information in any case. When we create index on such columns, information is placed in different ranges of indexes. So, before creating index, we can convert them in to single case.
SQL> CREATE INDEX IDX_NAME ON EMP(UPPER(ENAME)); Dropping an Index SYNTAX DROP INDEX <INDEXNAME>;
Removing an index doesnt invalidate existing applications, because applications are not directly dependent on index, but at the same time not having an index may effects performance.
185
TO DISPLAY 3 HIGHEST PAID EMPLOYEES SQL> SELECT ROWNUM,EMPNO,ENAME,SAL FROM (SELECT EMPNO, ENAME,SAL FROM EMP ORDER BY SAL DESC) WHERE ROWNUM <= 3;
Materialized Views:
Materialized views are schema objects that can be used to summarize, compute, replicate, and distribute data. A materialized view provides access to table data by storing the results of a query in a separate schema object. Unlike an ordinary view, which does not take up any storage space or contain any data, a materialized view contains the rows resulting from a query against one or more base tables or views. When you create a materialized view, Oracle Database creates one internal table and at least one index, and may create one view, all in the schema of the materialized view. Oracle Database uses these objects to maintain the materialized view data. You must have the privileges necessary to create these objects.
186
CREATE MATERIALIZED VIEW <[schema.]name> [LOGGING] [CACHE] [TABLESPACE <tablespace_name>] BUILD IMMEDIATE [REFRESH <FAST | FORCE | COMPLETE>] [ON <COMMIT | DEMAND>] [<USING INDEX | USING NO INDEX>] [START WITH <date> NEXT <date_calculation>] [FOR UPDATE] [STORAGE CLAUSE] AS (<SQL statement>);
BUILD: Specifies when to populate the materialized view. Specify IMMEDIATE to indicate that the materialized view is to be populated immediately. CACHE: For data that will be accessed frequently, CACHE specifies that the blocks retrieved for this table are placed at the most recently used end of the least recently used (LRU) list in the buffer cache when a full table scan is performed. This attribute is useful for small lookup tables. NOCACHE specifies that the blocks are placed at the least recently used end of the LRU list.
Syntax: <CACHE | NOCACHE>
REFRESH MODES FAST Clause The FAST refreshes use the materialized view logs (as seen above) to send the rows that have changed from master tables to the materialized view. You should create a materialized view log for the master tables if you specify the REFRESH FAST clause. Complete Clause The complete refresh re-creates the entire materialized view. If you request a complete refresh, Oracle performs a complete refresh even if a fast refresh is possible. Force Clause When you specify a FORCE clause, Oracle performs a fast refresh if possible, otherwise complete refresh. If you do not specify a refresh method (FAST, COMPLETE, or FORCE), FORCE is the default. USING INDEX If USING INDEX is not specified, then default tablespace values are used. The default index is used to speed up incremental (FAST) refresh of the materialized view.
Syntax: <USING INDEX | USING NO INDEX>
187
188
189
Exercise
1) Display the string SATYAM in the format S A T Y A M 2) Display only even rows from the table 3) Display one year calendar 4) Display how many as are there in the given string 5) Remove duplicate rows from the given table Empno ename 1 x 2 y 3 z 1 x 3 z 6) Find out how many columns are there in a given table(Use the data dictionary table USER_TAB_COLUMNS)
Course
Oracle 190
Topics
Advanced Queries Analytical Queries
Presentation
191
ANALYSIS When different employees salary is same, they get the same rank. There is a gap between ranks. In the example, see the ranks between 1 and 4.
DENSE_RANK
192
SQL> SELECT DENSE_RANK() OVER(ORDER BY SAL DESC) DEFAULT_RANK, SAL FROM EMP; DEFAULT_RANK SAL ------------ ---------1 855945.6 1 855945.6 1 855945.6 2 641959.2 3 196867.32 4 184563.24 5 153802.68 5 153802.68 6 129461.88 7 111807.6 8 66870.77 9 10000 10 6810.91
ROW_NUMBER 193
194
ANALYSIS It is just opposite to NVL(). NVL() substitute value, if its is NULL. Where as NULLIF produces NULL, if value matches.
Syntax
NVL2(expr1,expr2,expr3) In NVL2, expr1 can never be returned; either expr2 or expr3 will be returned.
If expr1 is not NULL, NVL2 returns expr2, If expr1 is NULL , NVL2 returns expr3. The expr1 can have any data type. The arguments expr2 and expr3 can have any datatype except LONG.
INPUT SQL> SELECT COMM,NVL2(COMM,COMM,0) FROM EMP; OUTPUT COMM NVL2(COMM,COMM,0) ---------- ----------------0 300 300 500 500 0 1400 1400 0 0 0 0 0 0 0 0 0 0
Coalesce Function
This function takes n arguments and produces first argument, which is having the first NOT NULL value.
196
We can load the data conditionally into three tables by using following statement SQL> insert all When deptno = 10 then Insert into table1 values(empno,ename,job,sal,deptno); When deptno = 20 then Insert into table2 values(empno,ename,job,sal,deptno); When deptno = 30 then Insert into table3 values(empno,ename,job,sal,deptno); Select empno,ename,sal,deptno from emp
198
The difference between Insert First and Insert All is that in the formar at the most one row is inserted into the table while latter rows may be inserted into multiple tables.
199
200
Locks are held until either a transaction is committed / rolled back. Locking using SELECT for UPDATE SELECT * FROM EMP WHERE EMPNO = 7521 FOR UPDATE OF SAL NOWAIT; With this SELECT we lock all the rows in the result set for later update. The FOR UPDATE tells Oracle to lock each row as it processes it. The OF keyword prefixes the column identification area which specifies which columns are going to be updated by us at a later date. The NOWAIT keyword specifies that we dont want the statement to wait until, and current locks on the table are removed. Assume that there are two users SCOTT AND X In the Scott user there is one table with the name EMP. Scott has given some privileges on EMP table to X user.
If X wants to lock the EMP table, then he has to issue a command LOCK TABLE SCOTT.EMP IN EXCLUSIVE MODE NOWAIT; Now from SCOTT user , if he tries to the lock the table, which is already locked by X LOCK TABLE EMP IN EXCLUSIVE MODE; It results an error LOCK TABLE EMP IN EXCLUSIVE MODE NOWAIT * ERROR at line 1: ORA-00054: resource busy and acquire with NOWAIT specified
201
Object privilege
An object privilege is a right to perform a particular operation on an object. An object is a table, view, sequence, procedure, function or package.
System privilege
A system privilege is a right to perform certain operation in the system. For example, the privilege to create a table is a system privilege.
Object Privileges
User owns the object that he/she creates. Unless otherwise specified, only the owner and DBA can access the object. But, if user wants to share his object with other users, he has to grant privileges on the object to other users.
These privileges are given on various objects, such as TABLE, VIEW, SEQUENCE, PROCEDURE,FUNCTION, PACKAGE AND OBJECT TYPE
202
-- any object privileges -- to grant all privileges -- to grant privilege to all the users of the
Now from X user, he can select as well as update the information in EMP table. SELECT * FROM SCOTT.EMP; UPDATE SCOTT.EMP EMPNO = 7521; SET SAL = 11000 WHERE
So, X user can modify only sal value in the EMP table.
203
Public Synonym
Public synonym is available for all the users.
SQL>CREATE SCOTT.EMP;
PUBLIC
SYNONYM
EMPL
FOR
204
Topic
SQL*Loader
Presentation
What is SQL*Loader? SQL*Loader is Oracles utility program for loading data into an Oracle table. Most often, SQL*Loader takes two input files a control file and a data file and loads the data into a single Oracle table. The data file contains data, and the control file contains information about the data -- where to load it, what to do if something goes wrong, etc. SQL*Loader has lots and lots of options which can be used to handle various types of data and levels of complexity. SQL*Loader is fully described in the Oracle Server Utilities Users Guide. This document is just about getting started. SQL*Loader runs on Unix, mainframes, and PCs. This document is just about running it from a Windows PC.
Why Use SQL*Loader From Your PC? If you need to transfer quite a lot of data from your machine to an Oracle database table, you might want to use SQL*Loader. If you already have the data in some other format, it may be worthwhile to use SQL*Loader. If you need to transfer local data to a remote database on some recurring basis, it may be preferable to use SQL*Loader rather than something like FTP. At the end of this document, there is a brief comparison of FTP versus SQL*Loader.
Getting Started, an Example Say, for example, that youve got an Excel spreadsheet with State data already in it. Youve got 50 rows of data each containing the State Abbreviation, State Name, an [optional] unofficial State Slogan, and the number of State Residents Who Drink Bottled Water.
205
Heres what you do: 1) Create your data file. This is easy. Save your Excel spreadsheet data AS a Comma-Separated-Variable (*.csv) file. This will automatically put commas between each of the four data elements. In addition, if any of the data elements already contain a comma, the Save AS *.csv step will optionally and automatically enclose that data in double quotes. So, after your Save AS command, you might have a file named C:\MyStates.csv that contains data like this:
AR,Arkansas,We are sure CO,Colorado,,3000 WI,Wisconsin,Rose Bowl CA,California,"Dude? You want, Oxygen?",90203049
proud
of
2) Create your control file. Using any text editor, create a file (say, C:\mystates.ctl) containing these lines: LOADDATA INFILE 'C:\EMPLOYEE.csv' REPLACE INTO TABLE EMPL FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' TRAILING NULLCOLS (EMPNO, ENAME INTEGER EXTERNAL) The REPLACE keyword says, "remove any existing rows before starting the load." There's also an INSERT [into empty table] and APPEND [to existing rows] option. State_Abbrev, State_Name, State_Slogan, and Nbr_Residents_WDBW are the actual column names defined in the sp.mystates table. Because the first three items are of character datatype, it was not necessary to further describe them character is the default. The fourth column is numeric data it totals the number of state residents who drink bottled water. The INTEGER EXTERNAL describes the datatype in the C:\mystates.csv input file. Notice there is some missing data in the data file -- Colorado has no state slogan. The TRAILING NULLCOLS statement handles the missing data; it tells SQL*Loader to load any missing data as NULL values. There are, as we said earlier, lots of available options described in the Utilities Users Guide.
206
4)Run Prerequisites:
SQL*Loader
You must have SQL*Loader and SQL*Net installed on your machine. The SQL*Loader program may have a version number included as part of its name, something like sqlldr73.exe or sqlldr80.exe. Or maybe it will be just sqlldr.exe. You can look for it in your ORAWIN95 or ORANT \BIN directory. If it's not installed, you can get the Oracle Client Software installation CD and install "UTILITIES". You must have the target database (say, its called ELTP) configured as SQL*Net service in your local tnsnames.ora file. This is pretty standard stuff; its probably already there. You must have authorization to modify the sp.mystates table (INSERT, or DELETE and INSERT if you're using the REPLACE option in the control file. In the example below we assume that user SCOTT with password TIGER has appropriate authorization.
At an MS-DOS prompt (or the Start, Run menu) , execute SQL*Loader as follows: sqlldr scott/tiger@ELTP control=C:\mystates.ctl When the load completes, look in the file C:\mystates.log. This log file will contain information about how many rows were loaded, how many rows -- if any -- were NOT loaded, and other information that may be useful to reassure or debug.
207
Siva Kumar HVK How to convert Excel Sheet into CSV(Comma separated variable) file
This article describes how to convert a single column of addresses in a Microsoft Excel worksheet into a comma-separated value (CSV) file that you can import into another program (for example, Microsoft Word). Note For the address example in this article, the Excel worksheet contains the following address information: A B 1 2 3 ravi kris babu
1. On the File menu, click Save As. Note In Excel 2007, click the Microsoft Office Button, and then click Save As. 2. In the Save As dialog box: a. In the Save as type box, click CSV (Comma delimited) (*.csv). b. In the File name box, type a name for your CSV file (for example, Address.csv), and then click Save. c. Click OK when you receive the following message: The selected file type does not support workbooks that contain multiple sheets. To save only the active sheet, click OK. To save all sheets, save them individually using a different file name for each, or select a file type that supports multiple sheets. d. Click Yes when you receive the following message: Address.csv may contain features that are incompatible with CSV (comma delimited). Do you want to keep the workbook in this format? To keep this format, which leaves out any incompatible features, click Yes. To preserve the features, click No. Then save a copy in the latest Excel format. To see what might be lost, click Help. 3. On the File menu, click Close, and then exit Microsoft Excel. Note In Excel 2007, click the Microsoft Office Button, click Close, and then click Exit Excel. Note You may be prompted to save the file again. When you are prompted, you can click Yes, repeat steps c and d, and then exit Excel.
208
a. Click the Microsoft Office Button, and then click Word Options. b. Click Display. c. Click Paragraph marks under the Always show these formatting marks on the screen.
209
Sample data For our sample data we will create a test table and copy a few rows and columns of ALL_TABLES as follows. SQL> CREATE TABLE temp 2 AS 3 SELECT owner, table_name, tablespace_name 4 FROM all_tables 5 WHERE ROWNUM <= 5; Table created. SQL> SELECT * FROM t; OWNER TABLE_NAME TABLESPACE_NAME --------------- --------------- -------------------SYS SEG$ SYSTEM SYS CLU$ SYSTEM SYS OBJ$ SYSTEM SYS FILE$ SYSTEM
210
DBMS_FLASHBACK can be used within logon triggers to enable Flashback without changing the application code. You may want to use DBMS_FLASHBACK for the following reasons: Self-service repair. If you accidentally delete rows from a table, you can recover the deleted rows. Packaged applications such as e-mail and voicemail. You can use Flashback to restore deleted e-mail by re-inserting the deleted message into the current message box. Decision support system (DSS) and online analytical processing (OLAP) applications. You can perform data analysis or data modeling to track seasonal demand.
211
212
213
SQL> SELECT * FROM temp; OWNER TABLE_NAME TABLESPACE_NAME --------------- --------------- -------------------SYS seg$ system SYS clu$ system SYS obj$ system SYS file$ system SYS col$ system 5 rows selected. Now we can invoke flashback query as of the timestamp prior to our update. SQL> SELECT * 2 FROM temp AS OF TIMESTAMP TO_TIMESTAMP('22-NOV-2002 21:31:01.750'); OWNER TABLE_NAME TABLESPACE_NAME --------------- --------------- -------------------SYS SEG$ SYSTEM SYS CLU$ SYSTEM SYS OBJ$ SYSTEM SYS FILE$ SYSTEM SYS COL$ SYSTEM 5 rows selected. This is much easier! The extended FROM clause is simple and intuitive to use and is more likely to encourage developers to use flashback query. A particularly good use for this is for resetting test data during development and unit-testing. It is also a good short-term recovery tool for rectifying minor mistakes. A note on flashback precision As noted earlier, flashback query timestamps are mapped to SCNs, but only once every five minutes. This makes flashback queries with timestamps subject to precision errors. We can see the effect of this in our 9.2 flashback query results above. Our flashback query correctly returns the original upper-case TABLE_NAME data but it also returns the original upper-case TABLESPACE_NAME data also. This tells us that the SCN that Oracle mapped to our timestamp is from a time before we ran the 9.0 example. Using an SCN, however, we can be more precise with our flashback query. We will take a guess that the SCN after our 9.0 example update will be a few greater than before we began (there is no other activity on
214
Siva Kumar HVK this test system). Using this, we will try a 9.2 flashback query AS OF SCN.
SQL> SELECT * FROM t AS OF SCN 592969; OWNER TABLE_NAME TABLESPACE_NAME --------------- --------------- -------------------SYS SEG$ system SYS CLU$ system SYS OBJ$ system SYS FILE$ system SYS COL$ system 5 rows selected. We can now see the data as it existed after the first update (9.0 example) but before the second update (9.2). Using the SCN enabled us to be far more precise with our flashback query. Recovering data Using the AS OF syntax, we can either update the table from the flashback query source or we can delete the current data and insert the flashback data in much easier way. In the example below, we'll remove the current data and replace it with the data as it existed after our 9.0 examples (i.e. lower-case TABLESPACE_NAME). SQL> DELETE FROM temp; 5 rows deleted. SQL> INSERT INTO temp 2 SELECT * FROM temp AS OF SCN 592969; 5 rows created. SQL> COMMIT; Commit complete. SQL> SELECT * FROM t; OWNER TABLE_NAME TABLESPACE_NAME --------------- --------------- -------------------SYS SEG$ system SYS CLU$ system SYS OBJ$ system SYS FILE$ system SYS COL$ system
5 rows selected.
215
DBMS_FLASHBACK Error Messages Error 8182 8184 8183 8185 Description In Flashback mode, user cannot perform DML or DDL operations. User cannot enable Flashback within another Flashback session. User cannot enable Flashback within an uncommitted transaction. SYS cannot enable Flashback mode. User cannot begin read only or serializable transactions in Flashback mode. Time specified is too old. Invalid system change number specified.
8180 8181
DBMS_FLASHBACK Example The following example illustrates how Flashback can be used when the deletion of a senior employee triggers the deletion of all the personnel reporting to him. Using the Flashback feature, you can recover and re-insert the missing employees. /* keep_scn is a temporary table to store scns that we are interested in. */ create table keep_scn (scn number); execute dbms_flashback.disable; set echo on create table employee (employee_no number(5) primary key, employee_name varchar2(20), employee_mgr number(5)constraint mgr_fkey references employee on delete cascade, salary number, hiredate date); /* Populate the company with employees */ insert into employee values (1, 'John Doe', null, 1000000, '5-jul-81'); insert into employee values (10, 'Joe Johnson', 1, 500000, '12-aug84');
insert into employee values (20, 'Susie Tiger', 10, 250000, '13-dec90');
216
end; / /* Show Scott's org */ select lpad(' ', 2*(level-1)) || employee_name Name from employee connect by prior employee_no = employee_mgr 217
Siva Kumar HVK start with employee_no = (select employee_no from employee where employee_name = 'Scott Tiger') order by level; declare scotts_emp number; scotts_mgr number; cursor c1 is select employee_no, employee_name, employee_mgr, salary, hiredate from employee connect by prior employee_no = employee_mgr start with employee_no =
(select employee_no from employee where employee_name = 'Scott Tiger'); c1_rec is c1 % ROWTYPE; begin select employee_no, employee_mgr into scotts_emp, scotts_mgr from employee where employee_name = 'Scott Tiger'; /* Open c1 with Flashback enabled. */ open c1; /* Disable Flashback. */ dbms_flashback.disable; loop /* Note that all the DML operations inside the loop are performed with Flashback disabled. */ fetch c1 into c1_rec; exit when c1%NOTFOUND; for c1_rec in c1 loop
if (c1_rec.employee_mgr = scotts_emp) then insert into employee values (c1_rec.employee_no, c1_rec.employee_name,
218
219
220
DISABLE Procedure This procedure disables the Flashback mode for the entire session. Syntax DBMS_FLASHBACK.DISABLE; Example The following example queries the salary of an employee, Joe, on August 30, 2000: EXECUTE dbms_flashback.enable_at_time('30-AUG-2000'); SELECT salary from emp where name = 'Joe' EXECUTE dbms_flashback.disable;
221
ANNEXURE
Table : Studies NAME (PNAME) SPLACE COURSE NULL NOT NULL NOT NULL NOT NULL TYPE VARCHAR2(20) VARCHAR2(20) VARCHAR2(20)
TABLE : SOFTWARE NAME (PNAME) TITLE DEV_IN SCOST DCOST SOLD NULL ? NOT NULL NOT NULL NOT NULL TYPE VARCHAR2(20) VARCHAR2(20) VARCHAR2(10) NUMBER(7,2) NUMBER(7,2) NUMBER(4)
NAME DEVELOPED PROJECT NAME LANGUAGE DEVELOPED SOFTWARE COST DEVELOPMENT COST NO OF SOFTWARE SOLD
Data in Table : STUDIES PNAME ANAND ALTAF JULIANA KAMALA MARY NELSON PATRICK QADIR RAMESH REBECCA REMITHA REVATHI VIJAYA SPLACE SABHARI COIT BITS PRAGATHI SABHARI PRAGATHI SABHARI APPLE SABHARI BPILLANI BDPS SABHARI BDPS COURSE PGDCA DCA MCA DCP PGDCA DAP DCA HDCP PGDCA DCA DCS DAP DCA COST 45000 7200 22000 5000 4600 6200 5200 14000 4500 11000 6000 5000 48000
222
DEV_IN BASIC PASCAL COBOL DBASE ORACLE COBOL C++ ASSEMBLY C DBASE PASCAL C ASSEMBLY PASCAL BASIC C
SCOST
DCOST
SOLD
399 7500 3000 9000 18000 4500 300 750 1900 12000 599 725 2500 1100 3200 900
6000 16000 3500 20000 85000 20000 1200 5000 3400 3500 4500 5000 6000 75000 2100 700
43 9 0 7 4 23 84 11 21 4 73 51 6 2 15 6
ANAND ALTAF JULIANA KAMALA MARY NELSON PATRICK QADIR RAMESH REBECCA REMITHA REVATHI VIJAYA
21-APR-66 02-JUL-64 31-JAN-68 30-OCT-68 24-JUN-70 11-SEP-85 10-NOV-65 31-AUG-65 03-MAY-67 01-JAN-67 19-APR-70 02-DEC-69 14-DEC-65
21-APR-92 13-NOV-90 21-APR-90 02-JAN-92 01-FEB-91 11-OCT-89 21-APR-90 21-APR-91 28-FEB-91 01-DEC-90 20-APR-93 02-JAN-92 02-MAY-92
PASCAL CLIPPER COBOL C C++ COBOL PASCAL ASSEMBLY PASCAL BASIC C PASCAL FOXPRO
BASIC COBOL DBASE DBASE ORACLE DBASE CLIPPER C DBASE COBOL ASSEMBLY BASIC C
3200 2800 3000 2900 4500 2500 2800 3000 3200 2500 3600 3700 3500
223
224
QUERY II
Display the cost of the package developed by each programmer Display the sales values of the packages developed by the each programmer Display the number of packages sold by each programmer Display the sales cost of the packages developed by each programmer Display each language name with average development cost, average selling cost and average price per copy Display each programmers name, costliest package and cheapest packages developed by him / her. Display each institute name with number of courses , average cost per course Display each Institute name with number of students Display the names of male and female programmers Display the programmers name and their packages Display the number of packages in each language except C and C++ Display the number of packages in each language for which development cost is less than 1000 Display the average difference between SCOST and DCOST for each language Display the total SCOST, DCOST and amount to be recovered for each programmer for those whose dcost has not yet been recovered Display the highest, lowest and average salaries for those earning more than 2000
225
226
Write a query to display the last name, department number, and salary of any employee whose department number and salary both match the department number and salary of any employee who earns a commission. Display the last name, department name, and salary of any employee whose salary and commission match the salary and commission of any employee located in location ID 1700. Create a query to display the last name, hire date, and salary for all employees who have the same salary and commission as Kochhar. Note: Do not display Kochhar in the result set. Create a query to display the employees who earn a salary that is higher than the salary of all of the sales managers (JOB_ID = 'SA_MAN'). Sort the results on salary from highest to lowest.
Find all employees who are not supervisors. a. First do this using the NOT EXISTS operator b. Can this be done by using the NOT IN operator? How, or why not?
Write a query to display the last names of the employees who earn less than the average salary in their departments. Write a query to display the last names of the employees who have one or more coworkers in their departments with later hire dates but higher salaries. Write a query to display the department names of those departments whose total salary cost is above one eighth (1/8) of the total salary cost of the whole company Write a query to display the last name, department number, and department name for all employees Create a unique listing of all jobs that are in department 80. Include the location of the department in the output. Write a query to display the employee last name, department name, location ID, and city of all employees who earn a commission. Display the employee last name and department name for all employees who have an a (lowercase) in their last names Write a query to display the last name, job, department number, and department name for all employees who work in Toronto.
227
Show the structure of the JOB_GRADES table. Create a query that displays the name, job, department name, salary, and grade for all employees. Create a query to display the name and hire date of any employee hired after employee Davies.
Write a query to display the following for those employees whose manager ID is less than 120: Manager ID Job ID and total salary for every job ID for employees who report to the same manager Total salary of those managers Total salary of those managers, irrespective of the job IDs
228
Question: 2
You need to produce a report for mailing labels for all customers. The mailing label must have only the customer name and address. The CUSTOMERS table has these columns: CUST_ID CUST_NAME CUST_ADDRESS CUST_PHONE NUMBER(4) NOT NULL VARCHAR2(100) VARCHAR2(150) VARCHAR2(20)
Which SELECT statement accomplishes this task? 1. SELECT* FROM customers; 2. SELECT name, address FROM customers; 3. SELECT id, name, address, phone FROM customers; 4. SELECT cust_name, cust_address FROM customers; 5. SELECT cust_id, cust_name, cust_address, cust_phone FROM customers;.
Question: 3
Evaluate this SQL statement: SELECT e.EMPLOYEE_ID,e.LAST_NAME,e.DEPARTMENT_ID, d.DEPARTMENT_NAME. FROM EMP e, DEPARTMENT d WHERE e.DEPARTMENT_ID = d.DEPARTMENT_ID; In the statement, which capabilities of a SELECT statement are performed? 1. 2. 3. 4. 5. Selection, projection, join Difference, projection, join Selection, intersection, join Intersection, projection, join Difference, projection, product
229
Question: 5
From SQL*Plus, you issue this SELECT statement: SELECT * From orders; You use this statement to retrieve data from a data table for __________. 1. Updating 2. Viewing 3. Deleting 4. Inserting 5. Truncating
Question: 6
Which SQL SELECT statement performs a projection, a selection, and join when executed? 1. SELECT p.id_number, m.manufacturer_id, m.city FROM product p, manufacturer m WHERE p.manufacturer_id = m.manufacturer_id AND m.manufacturer_id = 'NF10032'; 2. SELECT id_number, manufacturer_id FROM product ORDER BY manufacturer_id, id_number; 3. SELECT id_number, manufacturer_id FROM product WHERE manufacturer_id = 'NF10032'; 4. SELECT manufacturer_id, city FROM manufacturer AND manufacturer_id = 'NF10032' ORDER BY city;
230
Question: 8
Evaluate these two SQL statements: SELECT last_name, salary , hire_date FROM EMPLOYEES ORDER BY salary DESC; SELECT last_name, salary, hire_date FROM EMPLOYEES ORDER BY 2 DESC; What is true about them? 1. The two statements produce identical results.
231
Question: 9
Evaluate the set of SQL statements: CREATE TABLE dept (deptno NUMBER(2), dname VARCNAR2(14), loc VARCNAR2(13)); ROLLBACK; DESCRIBE DEPT What is true about the set? 1. The DESCRIBE DEPT statement displays the structure of the DEPT table. 2. The ROLLBACK statement frees the storage space occupies by the DEPT table. 3. The DESCRIBE DEPT statement returns an error ORA-04043: object DEPT does not exist. 4. The DESCRIBE DEPT statement displays the structure of the DEPT table only if the COMMIT statement introduced before the ROLLBACK statement..
Question: 10
Examine the data of the EMPLOYEES table. EMPLOYEES (EMPLOYEE_ID is the primary key. MGR_ID is the ID of managers and refers to the EMPLOYEE_ID)
EMPLOYEE_ID EMP_NAME 101 Smith 102 Martin 103 Chris 104 John 105 Diana 106 Bryan 108 Jennifer 110 Bob 120 Ravi DEPT_ID 20 10 20 30 30 40 30 40 20 MGR_ID 120 105 120 108 108 110 110 110 JOB_ID SA_REP CLERK IT_ADMIN HR_CLERK HR_MGR AD_ASST HR_DIR EX_DIR SA_DIR SALARY 4000 2500 4200 2500 5000 3000 6500 8000 6500
Evaluate this SQL statement: SELECT e.employee_id "Emp_id", e.emp_name "Employee", e.salary, m.employee_id "Mgr_id", m.emp_name "Manager"
232
2. EMP_id EMPLOYEE SALARY Mgr_id ------- ---------- --------- ------------- -------------120 Ravi 6500 110 Bob 108 Jennifer 6500 110 Bob 103 Chris 4200 120 Ravi 105 Diana 500 108 Jennifer
Manager
3. EMP_id EMPLOYEE SALARY Mgr_id ------- ---------- --------- ------------- -------------110 Bob 800 120 Ravi 6500 110 Bob 108 Jennifer 6500 110 Bob 103 Chris 4200 120 Ravi 105 Diana 5000 108 Jennifer D EMP_id EMPLOYEE SALARY Mgr_id ------- ---------- --------- ------------- -------------110 Bob 8000 110 Bob 120 Ravi 6500 120 Ravi 108 Jennifer 6500 108 Jennifer 103 Chris 4200 103 Chris 105 Diana 5000 105 Dina 5. The SQL statement produces an error.
Manager
Manager
233
Question: 12
You are formulating queries in a SQL*Plus. Which of the following statement correctly describes how to specify a column alias? 1. Place the alias at the beginning of the statement to describe the table. 2. Place the alias after each column separated by a space to describe the column. 3. Place the alias after each column separated by a comma to describe the column. 4. Place the alias at the end of the statement to describe the table.
Question: 13
You want to use a function in you column clause of a SQL statement. The NVL function accomplishes which of the following tasks? 1. 2. 3. 4. Assists in the distribution of output across multiple columns. Enables you to specify alternate output for non-NULL column values. Enables you to specify alternated out for NULL column values. Nullifies the value of the column out put.
Question: 14
You want to use SQL*Plus to connect to the oracle database. Which of the following choices does not indicate a component you must specify when logging into the oracle? 1. 2. 3. 4. The The The The SQL*Plus Keyword. username password. database name.
234
1. SELECT employee_id||' - '||last_name AS Former Employee, hire_date||' / '||depart_date AS Term of Employment FROM employee_history WHERE hire_date > '31-DEC-95'; 2. SELECT employee_id||' - '||last_name "AS Former Employee", hire_date||' / '||depart_date "AS Term of Employment" FROM employee_history WHERE hire_date > '31-DEC-95'; 3. SELECT employee_id||' - '||last_name 'Former Employee', hire_date||' / '||depart_date 'Term of Employment' FROM employee_history WHERE hire_date > '31-DEC-95' AND depart_date > NULL; 4. SELECT employee_id||' - '||last_name "Former Employee", hire_date||' / '||depart_date "Term of Employment" FROM employee_history WHERE hire_date > '31-DEC-95' AND depart_date <> NULL; 5. SELECT employee_id||' - '||last_name "Former Employee", hire_date||' / '||depart_date "Term of Employment" FROM employee_history WHERE hire_date > '31-DEC-95' AND depart_date IS NOT NULL;
235
Question: 17
Examine the data of the EMPLOYEES table. EMPLOYEES (EMPLOYEE_ID is the primary key. MGR_ID is the ID of managers and refers to the EMPLOYEE_ID)
EMPLOYEE_ID 101 102 103 104 105 106 108 110 120 EMP_NAME Smith Martin Chris John Diana Bryan Jennifer Bob Ravi DEPT_ID 20 10 20 30 30 40 30 40 20 MGR_ID 120 105 120 108 108 110 110 110 JOB_ID SA_REP CLERK IT_ADMIN HR_CLERK HR_MGR AD_ASST HR_DIR EX_DIR SA_DIR SALARY 4000 2500 4200 2500 5000 3000 6500 8000 6500
Which statement lists the ID, name, and salary of the employee, and the ID and name of the employee's manager, for all the employees who have a manager and earn more than 4000? 1. SELECT employee_id "Emp_id", emp_name "Employee", salary, employee_id "Mgr_id", emp_name "Manager" FROM employees WHERE salary > 4000; 2. SELECT e.employee_id "Emp_id", e.emp_name "Employee", e.salary, m.employee_id "Mgr_id", m.emp_name "Manager" FROM employees e, employees m WHERE e.mgr_id = m.mgr_id AND e.salary > 4000; 3. SELECT e.employee_id "Emp_id", e.emp_name "Employee", e.salary, m.employee_id "Mgr_id", m.emp_name "Manager" FROM employees e, employees m WHERE e.mgr_id = m.employee_id AND e.salary > 4000;
236
Question: 18
You need to display the last names of those employees who have the letter A as the second character in their names. Which SQL statement displays the required results? 1. SELECT last_name FROM EMP WHERE last_name LIKE _A%; 2. SELECT last_name FROM EMP WHERE last name =*A% 3. SELECT last_name FROM EMP WHERE last name =_A%; 4. SELECT last_name FROM EMP WHERE last name LIKE *A%
Question: 19
In which scenario would TOP N analysis be the best solution? 1. You want to identify the most senior employee in the company. 2. You want to find the manager supervising the largest number of employees. 3. You want to identify the person who makes the highest salary for all employees. 4. You want to rank the top three sales representatives who have sold the maximum number of products.
Question: 20
Evaluate this SQL statement: SELECT c.customer_id, o.order_id, o.order_date, p.product_name FROM customer c, curr_order o, product p WHERE customer.customer_id = curr_order.customer_id AND o.product_id = p.product_id ORDER BY o.order_amount; This statement fails when executed. Which change will correct the problem? 1. Include the ORDER_AMOUNT column in the SELECT list. 2. Use the table name in the ORDER BY clause. 3. Remove the table aliases from the WHERE clause. 4. Use the table aliases instead of the table names in the WHERE clause. 5. Remove the table alias from the ORDER BY clause and use only the column name.
237
Question: 22
For which task would you use the WHERE clause in a SELECT statement? 1. to designate the ORDER table location 2. to compare PRODUCT_ID values to 7382 3. to display only unique PRODUCT_ID values 4. to restrict the rows returned by a GROUP BY clause
Question: 23
The STUDENT_GRADES table has these columns: STUDENT_ID NUMBER(12) SEMESTER_END DATE GPA NUMBER(4,3) The registrar has requested a report listing the students' grade point averages (GPA), sorted from highest grade point average to lowest within each semester, starting from the earliest date. Which statement accomplishes this? 1. SELECT student_id, semester_end, gpa
238
Question: 24
The ORDERS table has these columns: ORDER_ID NUMBER(4) NOT NULL CUSTOMER_ID NUMBER(12) NOT NULL ORDER_TOTAL NUMBER(10,2) The ORDERS table tracks the Order nnmher, the order total, and the customer to whom the Order belongs. Which two statements retrieve orders with an inclusive total that ranges between 100.00 and 2000.00 dollars? 1. SELECT customer_id, order_id, order_total FROM orders RANGE ON order_total (100 AND 2000) INCLUSIVE; 2. SELECT customer_id, order_id, order_total FROM orders HAVING order_total BETWEEN 100 and 2000; 3. SELECT customer_id, order_id, order_total FROM orders WHERE order_total BETWEEN 100 and 2000; 4. SELECT customer_id, order_id, order_total FROM orders WHERE order_total >= 100 and <= 2000; 5. SELECT customer_id, order_id, order_total FROM orders WHERE order_total >= 100 and order_total <= 2000;
Question: 25
Examine the structure of the PRODUCT table. PRODUCT Table PRODUCT _ID NUMBER Primary Key PRODUCT_NAME VARCHAR2(25)
239
LIST_RRICE NUMBER (5,2) COST NUMBER (5,2) You want to display all product identification numbers of products for which there are 500 or more available for immediate sale. You want the product numbers displayed alphabetically by supplier, then by product number from lowest to highest. Which statement should you use to achieve the required results? 1. SELECT product_id FROM product WHERE qty_per_unit >= 500 ORDER BY supplier_id, product_id; 2. SELECT product_id FROM product WHERE qty_per_unit >= 500 SORT BY supplier_id, product_id; 3. SELECT product_id FROM product WHERE qty_per_unit >= 500 ORDER BY supplier_id, product_id DESC; 4. SELECT product_id FROM product WHERE qty_per_unit > 500 SORT BY supplier_id, product_id;
Question: 26
Examine the data in TEACHER table. ID LAST_NAME FIRST_NAME SUBJECT_ID 88 Tsu Ming HST_AMER 70 Smith Ellen HST_INDIA 56 Jones Karen HST_REVOL 58 Hann Jeff HST_CURR 63 Hopewell Mary Elizabetn HST_RELIG Which query should you use to return the following values from the TEACHER table? Name Subject ------------------------------------- ------------------Jones, Karen HST_REVOL Hopewell, Mary Elizabeth HST_RELIG
240
Question: 27
You query the database with this SQL statement: SELECT bonus FROM salary WHERE bonus BETWEEN 1 AND 250 OR (bonus IN(190, 500, 600) AND bonus BETWEEN 250 AND 500); Which value could the statement return? 1. 2. 3. 4. 100 260 400 600
Question: 28
Examine the structure of the STUDENTS table: STUDENT_ID NUMBER Primary Key STUDENT_NAME VARCHAR2(30) COURSE_ID VARCHAR2(10) NOT NULL MARKS NUMBER START_DATE DATE FINISH_DATE DATE You need to create a report of the 10 students who achieved the highest ranking in the course INT SQL and who completed the course in the year 1999. Which SQL statement accomplishes this task? 1. SELECT student_ id, marks, ROWNUM "Rank" FROM students WHERE ROWNUM <= 10 AND finish_date BETWEEN '01-JAN-99' AND '31-DEC-99' AND course_id = 'INT_SQL' ORDER BY marks DESC;
241
Question: 29
Examine the structure of the LINE_ITEM table. LINE_ITEM_ID NUMBER(9), ORDER_ID NUMBER(9) NOT NULL, PRODUCT_ID NUMBER(9) NOT_NULL, QUANTITY NUMBER(9), Constraint primary key (LINE_ITEM_ID, ORDER_ID), Constraint foreign key ORDER_ID REFERENCES CURR_ORDER(ORDER_ID), Constraint foreign key PRODUCT_ID REFERENCES PRODUCT(PRODUCT_ID)); You must display the order number, line item number, product identification number, and quantity of each item where the quantity ranges from 10 through 100. The order numbers must be in the range of 1500 through 1575. The results must be sorted by order number from lowest to highest and then further sorted by quantity from highest to lowest. Which statement should you use to display the desired result? 1. SELECT order_id, line_item_id, product_id, quantity FROM line_item WHERE quantity BETWEEN 9 AND 101 AND order_id BETWEEN 1500 AND 1575 ORDER BY order_id DESC, quantity DESC;
242
Question: 30
The ITEM table contains these columns: ITEM_ID NUMBER(9) COST NUMBER(7,2) RETAIL NUMBER(7,2) You need to create a report that displays the cost, the retail price, and the profit for item number 783920. To calculate the profit, subtract the cost of the item from its retail price, and then deduct an administrative fee of 25 percent of this derived value. Which SELECT statement produces the desired results? 1. SELECT cost, retail, (retail - cost) - ((retail - cost) * .25) "Profit" FROM item WHERE item_id = 783920; 2. SELECT cost, retail, (retail - cost) - retail - (cost * .25) "Profit" FROM item WHERE item_id = 783920; 3. SELECT cost, retail, (retail - cost - retail - cost) * .25 "Profit" FROM item WHERE item_id = 783920; 4. SELECT cost, retail, retail - cost - retail - cost * .25 "Profit" FROM item WHERE item_id = 783920;
243
Question: 32
The EMP table contains these columns: LAST NAME VARCHAR2(25) SALARY NUMBER(6,2) DEPARTMENT_ID NUMBER(6) You need to display the employees who have not been assigned to any department. You write the SELECT statement: SELECT LAST_NAME, SALARY, DEPARTMENT_ID FROM EMP WHERE DEPARTMENT_ID = NULL; What is true about this SQL statement? 1. The SQL statement displays the desired results. 2. The column in the WHERE clause should be changed to display the desired results. 3. The operator in the WHERE clause should be changed to display the desired results. 4. The WHERE clause should be changed to use an outer join to display the desired results.
244
Question: 34
You are sorting data in a table in you SELECT statement in descending order. The column you are sorting on contains NULL records, where will the NULL record appears? 1. At the beginning of the list. 2. At the end of the list. 3. In the middle of the list. 4. At the same location they are listed in the unordered table.
Question: 35
The ACCOUNT table contains these columns: ACCOUNT_ID NUMBER(12) PREVIOUS_BALANCE NUMBER(7,2) PAYMENTS NUMBER(7,2) NEW_PURCHASES NUMBER(7,2) CREDIT_LIMIT NUMBER(7) You need to display the account number, finance charge, and current balance for accounts 1500 through 2000 with a current balance greater than the account's credit limit. The finance charge is .9 percent (.009) of the previous balance. Adding the previous balance value, new purchases value, and finance charge value, and then subtracting the payments value yields the current balance value. Evaluate this statement: SELECT account_id, NVL(previous_balance, 0) * .009 finance_charge, NVL(new_purchases, 0) + (NVL(previous_balance, 0) * 1.009) NVL(payments, 0) current balance FROM account WHERE (new_purchases + (previous_balance * 1.009)) - payments > credit_limit AND account_id BETWEEN 1500 AND 2000; Which statement about this SELECT statement is true? 1. The statement calculates the finance charge incorrectly. 2. The statement calculates the current balance incorrectly. 3. The statement returns only accounts that have NO previous balance.
245
Question: 36
Examine the description of the EMPLOYEES table: EMP_ID NUMBER(4) NOT NULL LAST_NAME VARCHAR2(30) NOT NULL FIRST_NAME VARCHAR2(30) DEPT_ID NUMBER(2) JOB_CAT VARCHARD2(30) SALARY NUMBER(8,2) Which statement shows the maximum salary paid in each job category of each department? 1. SELECT dept_id, job_cat, MAX(salary) FROM employees WHERE salary > MAX(salary); 2. SELECT dept_id, job_cat, MAX(salary) FROM employees GROUP BY dept_id, job_cat; 3. SELECT dept_id, job_cat, MAX(salary) FROM employees; 4. SELECT dept_id, job_cat, MAX(salary) FROM employees GROUP BY dept_id; 5. SELECT dept_id, job_cat, MAX(salary) FROM employees GROUP BY dept_id, job_cat, salary;
Question: 37
Management has asked you to calculate the value 12*salary* comossion_pct for all the employees in the EMP table. The EMP table contains these columns: LAST NAME VARCNAR2(35) NOT NULL SALARY NUMBER(9,2) NOT NULL COMMISION_PCT NUMBER(4,2) Which statement ensures that a value is displayed in the calculated columns for all employees? 1. SELECT last_name, 12*salary*commison_pct FROM emp; 2. SELECT last_name, 12*salary* (commission_pct,0) FROM emp; 3. SELECT last_name, 12*salary*(nvl(commission_pct,0)) FROM emp; 4. SELECT last_name, 12*salary*(decode(commission_pct,0)) FROM emp;
246
Question: 39
The EMPLOYEE tables has these columns: LAST_NAME VARCNAR2(35) SALARY NUMBER(8,2) COMMISSION_PCT NUMBER(5,2) You want to display the name and annual salary multiplied by the commission_pct for all employees. For records that have a NULL commission_pct, a zero must be displayed against the calculated column. Which SQL statement displays the desired results?
1. SELECT last_name, 2. SELECT last_name, EMPLOYEES; 3. SELECT last_name, EMPLOYEES; 4. SELECT last_name, EMPLOYEES;
(salary * 12) * commission_pct FROM EMPLOYEES; (salary * 12) * IFNULL(commission_pct,0) FROM (salary * 12) * NVL2(commission_pct, 0) FROM (salary * 12) * NVL(commission_pct, 0) FROM
Question: 40
You would like to display the system date in the format "Monday, 01 June, 2001". Which SELECT statement should you use? 1. 2. 3. 4. 5. SELECT SELECT SELECT SELECT SELECT TO_DATE(SYSDATE, 'FMDAY, DD Month, YYYY') FROM dual; TO_CHAR(SYSDATE, 'FMDD, DY Month, 'YYY') FROM dual; TO_CHAR(SYSDATE, 'FMDay, DD Month, YYYY') FROM dual; TO_CHAR(SYSDATE, 'FMDY, DDD Month, YYYY') TO_DATE(SYSDATE, 'FMDY, DDD Month, YYYY') FROM dual;
Question: 41
Evaluate the SQL statement:
247
Question: 42
Examine the description of the MARKS table: STD_ID NUMBER(4) STUDENT_NAME VARCHAR2(30) SUBJ1 NUMBER(3) SUBJ2 NUMBER(3) SUBJ1 and SUBJ2 indicate the marks obtained by a student in two subjects. Examine this SELECT statement based on the MARKS table: SELECT subj1+subj2 total_marks, std_id FROM marks WHERE subj1 > AVG(subj1) AND subj2 > AVG(subj2) ORDER BY total marks; What is the result of the SELECT statement? 1. The statement executes successfully and returns the student ID and sum of all marks for each student who obtained more than the average mark in each subject. 2. The statement returns an error at the SELECT clause. 3. The statement returns an error at the WHERE clause. 4. The statement returns an error at the ORDER BY clause.
Question: 43
Which three SELECT statements displays 2000 in the format $2,000.00? 1. SELECT TO_CHAR (2000, $#,###.##) FROM dual; 2. SELECT TO_CHAR (2000, $0,000.00) FROM dual; 3. SELECT TO_CHAR (2000, $9,999.00) FROM dual; 4. SELECT TO_CHAR (2000, $9,999.99) FROM dual; 5. SELECT TO_CHAR (2000, $2,000.00) FROM dual; 6. SELECT TO_CHAR (2000, $N,NNN.NN ) FROM dual;
248
249
Question: 46
Which four statements correctly describe functions that are available in SQL? 1. INSTR returns the numeric position of a named character. 2. NVL2 returns the first non-null expression in the expression list. 3. TRUNCATE rounds the column, expression, or value to n decimal places. 4. DECODE translates an expression after comparing it to each search value. 5. TRIM trims the heading of trailing characters (or both) from a character string. 6. NVL compares two expressions and returns null if they are equal, or the first expression of they are not equal. 7. NULLIF compares two expressions and returns null if they are equal, or the first expression if they are not equal.
250
NUMBER Primary Key VARCHAR2 (30) NOT NULL VARCHAR2 (25) NOT NULL NUMBER (7) NOT NULL DATE
ADMISSION Table PATIENT_ID NUMBER NOT NULL, Primary Key, References PATIENT_ID column of the PATIENT table PHYSICIAN_ID NUMBER NOT NULL, Primary Key, References PHYSICIAN_ID column of the PHYSICIA table ADMIT_DATE DATE DISCHG_DATE DATE ROOM_ID NUMBER Foreign key to ROOM_ID of the ROOM table Which SQL statement will produce a list of all patients who have more than one physician? 1. SELECT p.patient_id FROM patient p WHERE p.patient_id IN (SELECT patient_id FROM admission GROUP BY patient_id HAVING COUNT(*) > 1); 2. SELECT DISTINCT a.patient_id FROM admission a, admission a2 WHERE a.patient_id = a2.patient_id AND a.physician_id <> a2.physician_id; 3. SELECT patient_id FROM admission WHERE COUNT(physician_id) > 1; 4. SELECT patient_id FROM patient FULL OUTER JOIN physician;
251
Question: 49
In a SELECT statement that includes a WHERE clause, where is the GROUP BY clause placed in the SELECT statement? 1. Immediately after the SELECT clause 2. Before the WHERE clause 3. Before the FROM clause 4. After the ORDER BY clause 5. After the WHERE clause
Question: 50
Which two are character manipulation functions? 1. TRIM 2. REPLACE 3. TRUNC 4. TO_DATE 5. MOD 6. CASE
252