CHAPTER 1 • ELEMENTS OF ORACLE DATABASE MANAGEMENT 28 3 where hiredate < sysdate 4* SQL> 2 2* form emp SQL> c/form/from 2* from emp To add additional text to the SQL statement, use the A command and then specify the additional text. For example: A from dba_data_files, as shown here: SQL> select empno, ename 2 from emp 3 where hiredate < sysdate 4 SQL> 1 1* select empno, ename SQL> a , hiredate 1* select empno, ename, hiredate To insert a line, use the I command. SQL*Plus will prompt you to insert additional test at the location of the current pointer. A SQL*Plus command must be on one line only (this is not true for a SQL state- ment). If you explicitly want to use two or more lines to express the command, you must end each line with a space and then a dash ( - ). Then you can continue the command on the next line (which starts with a > symbol). Here’s an example: Column bytes - > format 999,999,999 SQL*Plus also provides other features for the DBA. You can • Format the output, including page breaks and totals summation on columns. • Control the format of specific columns, including length of the output dis- played in the column, and whether the output wraps or not. • Supply title, header, and footer output for your SQL statements. • Clear the screen. • Calculate and print summary totals of columns. All SQL*Plus commands are documented in Appendix C. Copyright ©2002 SYBEX, Inc., Alameda, CA www.sybex.com Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 29 NOTE Several database management commands have been added to SQL*Plus since Oracle7, to facilitate the removal of Server Manager at some point in the future. These commands include starting up, shutting down, and recovering the database. Starting and stopping the database is discussed in Chapter 7. Setting up the database (including starting it without using CONNECT INTERNAL) is covered in Chapter 3. Database security relating to CONNECT INTERNAL is discussed in Chapter 21. TNSPING The Oracle utility called TNSPING helps you determine if your Oracle networking is set up properly. Here is the syntax for the command to run TNSPING: TNSPING (network_service_name) [count] The network_service_name is the name of the database you wish to check on. The COUNT parameter is the number of “pings” you wish to send to the database. NOTE The TNSPING command does not help you determine if your database is up and running. It only tells you whether the listener for that database is up and running. If the TNSPING command is successful, Oracle responds with a display showing how long it took the ping to be returned by the Oracle listener. Following is an example: C:\>tnsping ora816 TNS Ping Utility for 32-bit Windows: Version 8.1.6.0.0 - Production on 07-JAN-20 01 13:10:43 (c) Copyright 1997 Oracle Corporation. All rights reserved. Attempting to contact (ADDRESS=(PROTOCOL=TCP) (HOST=ws-jax-w2820)(PORT=1521)) OK (650 msec) Using Oracle SQL SQL is the language of Oracle databases and the DBA’s path into the database. You use SQL to store, remove, and retrieve information at will. This section provides a basic introduction to SQL, the fundamental precepts of SQL that you will see used throughout the rest of the book. USING ORACLE SQL Oracle Essentials PART I Copyright ©2002 SYBEX, Inc., Alameda, CA www.sybex.com Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. CHAPTER 1 • ELEMENTS OF ORACLE DATABASE MANAGEMENT 30 NOTE Don’t forget to check the reading list at the end of this chapter if you need addi- tional help working with SQL. You will have the opportunity to study the many SQL com- mands used throughout this book, and when you need more information about a command, you can look in Oracle’s SQL Reference Guide. Also, there’s a SQL quick refer- ence guide in Appendix E of this book. Datatypes in Oracle8i When you query a table with a SQL statement, you access one or more columns in that table. The types of data stored in these columns are defined when the table is created. Each column is defined to be a particular datatype. This might be a scalar (native) datatype such as VARCHAR2, which stores characters. Or it might be a user- defined datatype. We will explore the Oracle datatypes throughout this book; Table 1.3 is a summarized list. TABLE 1.3: NATIVE ORACLE DATATYPES Datatype Description CHAR Stores up to 2000 characters of data in a fixed-length format. VARCHAR2 Stores up to 4000 variable characters of data. (Though it’s not often used, Oracle still offers the VARCHAR datatype, which is the same as a VARCHAR2.) NCHAR and NVARCHAR2 These datatypes store National Language Support (NLS) character data. They store data similarly to the CHAR and VARCHAR2 datatypes. LOB and NCLOB Can store up to 4GB of character data. These are part of the fam- ily of LOB data types. BLOB Stores up to 4GB of binary, unformatted data. BFILE Pointer to an outside operating system file. LONG and LONGRAW Stores up to 2GB of raw, unformatted data. Support for these data types will be dropped at some point in favor of LOBs. DATE Stores dates in Oracle. Stores both the date and time, up to hun- dredths of seconds. NUMBER Number datatype. ROWID and UROWID Stores Oracle ROWIDs. UROWID supports a wider variety of ROWIDs. Copyright ©2002 SYBEX, Inc., Alameda, CA www.sybex.com Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 31 The DML and DDL Languages In this section we’ll look at Oracle’s Data Manipulation Language (DML) and Data Definition Language (DDL), starting with the common syntax conventions. First, all commands begin with a keyword. These are words that imply the action to be performed—for example, INSERT, UPDATE, and DELETE. In SQL, certain characters have a special meaning, as follows: ; End of SQL statement / End of SQL statement -- Comment /* */ Comment So, for example, when you complete a DML or DDL statement, you end it with a semicolon to indicate that the statement is completed. DML DML statements are designed to display or modify database data. Following is a list of DML statements that you will be using in Oracle: Statement Purpose Example SELECT SELECT * FROM emp WHERE empno < 2000; INSERT INSERT INTO emp (empno, name) VALUES (1,'Robert'); UPDATE UPDATE emp SET ename='Davis' WHERE empno=12345; DELETE DELETE FROM emp WHERE empno=12345; NOTE SELECT queries are sometimes considered a distinct type of statement, but in this book we will consider them DML. DDL Oracle’s Data Definition Language (DDL) comprises every remaining SQL command that is not DML. In general, these are the statements that manipulate the database itself. DDL statements include CREATE TABLE, CREATE INDEX, and CREATE DATABASE. Removes one or more rows from a database table Updates rows in the database table Adds new rows into a database table The most common SQL state- ment; used to query the data in the database USING ORACLE SQL Oracle Essentials PART I Copyright ©2002 SYBEX, Inc., Alameda, CA www.sybex.com Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. CHAPTER 1 • ELEMENTS OF ORACLE DATABASE MANAGEMENT 32 Set Processing Oracle SQL statements work with one group of records at a time. Unlike most stan- dard programming languages that require you to loop through a set of records and process them one record at a time, Oracle facilitates what is called set processing. Many new developers who come from a background of COBOL or C have difficulty grasping this paradigm change, and at first tend to write inefficient code. For example, con- sider the following pseudocode: For loop until EOF Do Get record If column_to_change=’2’ then Change record so column_to_change=’1’ End if Write changed record End of loop This code works fine, of course, but in Oracle a simple SQL statement will generally work much faster: UPDATE my_table SET column_to_change=1 WHERE column_to_change=2; Not only will it work much faster, but it’s more compact as well. Set processing allows Oracle to perform one or more operations collectively. The result from one operation can interact with previous operations, and all of this is done via one SQL statement. Let’s look at a specific example. You need to collect a set of employee records for all employees of Department 7, sort them by hire date, and then remove from the result set all employees who happen to be retired. This type of logic would take several lines of other code but is done quickly in SQL by issuing a statement such as this: SELECT employee_name, address, hire_date FROM employee_data WHERE status != ‘Retired’ AND dept_no=7 SORT BY hire_date; WARNING SQL statements and set processing are more direct but can get compli- cated fast. The Oracle database engine is designed around set operations. As DBA, when reviewing programmers’ code, be on the lookout for code that interacts with the database in a way that does not fully take advantage of set processing. Copyright ©2002 SYBEX, Inc., Alameda, CA www.sybex.com Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 33 The SQL Query A SQL query has several parts to it, some required and some optional. Its basic com- ponents are described in the following paragraphs. The SQL Quick Reference in Appendix F can be of assistance to you in crafting the perfect SQL statement. The SELECT Clause This clause starts with the SELECT keyword, followed by a comma-separated list of columns to display as a part of the query results. If you wish to bring back all columns of the table, use an asterisk (*). You can also include functions (your own or one of the many supplied by Oracle) to manipulate the columns appearing in the SELECT clause. For example, to display only a part of a character column, you might use the SUBSTR function in the SELECT query to limit the number of characters returned. Throughout this book we will look at and use many of the native Oracle functions. In addition, a quick reference to functions can be found in Appendix F. The FROM Clause The FROM clause contains one or more of the following: • A list of tables to be accessed as a part of the query • An inline view that is to be accessed as part of the query The WHERE Clause This clause consists of several predicates, separated by AND keywords, that control the results of the SQL statement. The WHERE clause serves several purposes, including • Making the query selective. Instead of bringing back all rows from the tables queried, the criteria in the WHERE clause’s predicates serve to restrict the num- bers of rows. • Joining rows together. If several tables appear in the FROM clause, it is the WHERE clause that defines the related columns of the tables. In the following example of a basic SQL statement: SELECT empno, ename FROM emp WHERE empno=1; the following is true: • The SELECT clause will cause Oracle to return two columns, EMPNO and ENAME. • The FROM clause identifies what table (EMP) we wish to bring back from the EMPNO and ENAME columns. USING ORACLE SQL Oracle Essentials PART I Copyright ©2002 SYBEX, Inc., Alameda, CA www.sybex.com Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. CHAPTER 1 • ELEMENTS OF ORACLE DATABASE MANAGEMENT 34 • The WHERE clause, with one predicate (empno=1), restricts the rows returned to just the row(s) where empno=1. These are just the basic parts of a SQL statement, of course. There are other clauses, such as GROUP BY and HAVING, that format grouped results—for instance, a summa- tion of values in the columns of a table. The ORDER BY clause sorts the result set. All of these commands and others are documented in the SQL Quick Reference in Appen- dix E, and you will find plenty of examples in this book. SQL Operations Several different kinds of operations are possible when issuing SQL statements. Subqueries A subquery is a SQL statement within a SQL statement. This allows nesting of queries in your SQL statement. The following example of a subquery returns a count of all employees who are paid less than the average salary: SELECT count(*) FROM employee WHERE salary<(select AVG(salary) FROM employee); Correlated Subqueries These are subqueries that depend on the values of the parent query. Correlated sub- queries return the same values as a join, but you use a subquery where you cannot use a join—in UPDATE and DELETE statements, for example. Consider the following cor- related subquery that updates zip codes in the employee records, based on zip code changes in a ZIP_CHANGE table. What makes this a correlated subquery is that the subquery issuing the SELECT against the ZIP_CHANGE table is referencing the EMPLOYEE table, which we are updating. UPDATE employee SET zip_code=(SELECT new_zip FROM zip_change WHERE employee.zip_code=old_zip) WHERE zip_code IN (SELECT old_zip FROM zip_change); Joins Joins allow two or more tables to be included in the same query, based on common key columns that relate the tables. There are several different kinds of joins. Copyright ©2002 SYBEX, Inc., Alameda, CA www.sybex.com Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 35 Equijoin and Inner Join An equijoin is a join involving a direct equivalence between the key columns of the tables involved in the join. In this example: SELECT a.ename, a.deptno, b.dname FROM emp a, dept b WHERE a.deptno=b.deptno the equijoin is between the EMP table and the DEPT table. The join is on the like or equivalent (hence the word equijoin) DEPTNO keys in both tables. From this join, we get the department number from the EMP table, and the name of the department is derived from the DEPT table. An inner join is probably the most common join operation. It is the join of the rows from one table to those of others based on common key values. If a row in one table has a key that does not have a match in another table, then that row will not be dis- played. For example, if an employee is assigned to a department that does not exist in the department table, then that employee will not appear in the results displayed by the following (a good example of referential integrity’s importance in a database): SELECT a.ename, a.deptno, b.dname FROM employee a, dept b WHERE a.deptno=b.deptno Theta Joins A theta join (also called a non-equijoin) is a join using an operator that involves equiv- alence along a range of values. SQL statement operators include < and >, BETWEEN, and others. Here is an example of a theta join: SELECT a.ename, b. grade FROM employee a, salgrade b WHERE a.sal BETWEEN b.losal AND b.hisal Outer Joins An outer join causes rows in one table to be included in the resulting join, even if there is no matching row in the other joined table. Oracle uses a non-ANSI standard (+) operator to designate an outer join. The (+) operator goes in the WHERE clause, by the column/table combination that might not have the associated rows in it. Let’s say you are looking for employees and what they were paid last week, but you also want to see employees who were not paid anything last week. The PAY_TABLE table (which contains pay records) might not have rows for all the employees, since they might not all have been paid. To list all employees, then, including those not paid, we put the (+) in the WHERE clause next to the EMPNO column for the USING ORACLE SQL Oracle Essentials PART I Copyright ©2002 SYBEX, Inc., Alameda, CA www.sybex.com Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. CHAPTER 1 • ELEMENTS OF ORACLE DATABASE MANAGEMENT 36 PAY_TABLE table. So the query would look something like this (the outer join is in the last line): SELECT a.empno, a.ename, b.pay_day, b.pay_total FROM employee a, pay_table b WHERE a.empno = b.empno (+) Anti-Joins An anti-join makes possible the selection of all rows in one table that do not have rows that match in another table. Specifically, you might want to find all the rows in one table that do not have the selected column values of those rows in another table. Anti-joins are typically performed using the NOT IN and NOT EXIST clauses. Let’s say you want a list of employees who have not been assigned a department. You can do that using an anti-join with a query such as this one: SELECT a.empno, a.ename, a.deptno FROM emp a WHERE a.deptno NOT IN (SELECT deptno FROM dept); Self Joins When you join a table to itself, it’s called a self join. In a self join, the same table will appear twice (or more) in the FROM clause. Here’s an example: SELECT a.empno, a.ename, a.mgr, b.ename “Manager Name” FROM employee a, employee b WHERE b.empno=a.mgr; Cartesian Joins Cartesian joins are the result of a join between two tables when no join condition is defined the query’s WHERE clause. Oracle will occasionally decide to do a Cartesian join when executing a SQL statement if it thinks that the join will provide the required row sources faster than other access methods. The Effects of NULL Columns on Joins The presence of NULLs in relational databases means we have a third logical value to deal with. Instead of just TRUE and FALSE, for instance, you now also have to con- sider NULL, which simply means that the data is missing or undefined. This causes some additional complications. The impact of NULL values on queries is fairly easy to demonstrate. Here is an example: SQL> SELECT COUNT(*) FROM emp WHERE job=’CLERK’ 2 union Copyright ©2002 SYBEX, Inc., Alameda, CA www.sybex.com Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 37 3 SELECT COUNT(*) FROM emp WHERE job!=’CLERK’; COUNT(*) ---------- 4 11 SQL> SELECT COUNT(*) FROM emp; COUNT(*) ---------- 16 This example perfectly demonstrates three-valued logic. In the first query, we have 15 total rows reported; yet when we issue a statement to count all rows, we get a total of 16 rows. What’s up? The issue is that in one row the job column is set to NULL. The NULL is essentially a third value and will not evaluate to TRUE or FALSE. Thus, it fails both the test of being equal to ‘CLERK’ and the test of being unequal to ‘CLERK’. The NULL is an unknown, and a special test must be done to check for that logical condition. In other words, neither the = nor the != test will find NULL values! The presence of NULL values in data can have some interesting impact on join results, and you’ll need to consider this when developing your queries. For example, take another look at our anti-join query: SELECT a.empno, a.ename, a.deptno FROM emp a WHERE a.deptno NOT IN (SELECT deptno FROM dept); This gives the following output: EMPNO ENAME DEPTNO ----- ------------- ------------- 1 Freeman 99 What we want here is a listing of all employees who are assigned a department number that is not in the DEPT department. Only problem is, if an employee has NULL assigned to the DEPTNO column of the EMP table, that employee record will not appear—because the NULL is not considered a value at all. Thus, when a NULL column appears, it doesn’t satisfy the NOT IN check and does not appear as part of the result set. USING ORACLE SQL Oracle Essentials PART I Copyright ©2002 SYBEX, Inc., Alameda, CA www.sybex.com Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... Oracle’s aggregation functions In the following example of aggregation, we determine the total size of the SYSTEM tablespace in bytes: SELECT SUM(bytes) FROM dba_data_files Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark www.sybex.com Copyright ©2002 SYBEX, Inc., Alameda, CA ORACLE PL/SQL WHERE tablespace_name = ‘SYSTEM’ GROUP BY tablespace_name; 39 PA R T I SQL has little... procedural constructs, including these: • Looping constructs • IF/THEN/ELSE structures • Handling of statement results a row at a time, rather than relying on set processing Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark www.sybex.com Copyright ©2002 SYBEX, Inc., Alameda, CA Oracle Essentials Oracle PL/SQL 40 CHAPTER 1 • ELEMENTS OF ORACLE DATABASE MANAGEMENT • Error checking... type number V_Num_rows number; The BEGIN section is next The body of the PL/SQL code begins after the BEGIN keyword BEGIN SELECT count(*) INTO v_num_rows FROM dba_tables; Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark www.sybex.com Copyright ©2002 SYBEX, Inc., Alameda, CA ORACLE PL/SQL The Dbms_output.put_line package will output a message to the screen Dbms_output.put_line(‘The... V_Num_rows as a variable of type number V_Num_rows number; The BEGIN section starts next The body of the PL/SQL code begins after the BEGIN keyword BEGIN SELECT count(*) Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark www.sybex.com Copyright ©2002 SYBEX, Inc., Alameda, CA Oracle Essentials The END declaration ends the body of the PL/SQL program 42 CHAPTER 1 • ELEMENTS... number V_Num_rows number; The BEGIN section starts next The body of the PL/SQL code begins after the BEGIN keyword BEGIN SELECT count(*) INTO v_num_rows FROM dba_tables; Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark www.sybex.com Copyright ©2002 SYBEX, Inc., Alameda, CA MOVING ON The dbms_output.put_line package will output a message to the screen Dbms_output.put_line(‘The... outlined in this first chapter We trust this book will provide you with lots of help in managing your database Now, let’s move on to the topic of installing the Oracle software Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark www.sybex.com Copyright ©2002 SYBEX, Inc., Alameda, CA Oracle Essentials The END declaration ends the body of the PL/SQL program You would run this procedure... Universal Installer 47 Preinstall steps 48 Installing the database software 50 Patching the Oracle software 64 Removing the Oracle software 66 Migrating/updating to Oracle8i 70 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark www.sybex.com Copyright ©2002 SYBEX, Inc., Alameda, CA I f you are installing Oracle for the first time, congratulations! You are implementing one of the... your Oracle platform-specific documentation, so you can refer to that if something doesn’t work or doesn’t translate into the vernacular of your particular operating system Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark www.sybex.com Copyright ©2002 SYBEX, Inc., Alameda, CA Introducing the Universal Installer The Oracle Universal Installer (UI) was introduced in Oracle8i... Universal Installer does provide a number of benefits These include • An easy-to-use common install/upgrade interface to Oracle products • Support for Oracle patch-set installs Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark www.sybex.com Copyright ©2002 SYBEX, Inc., Alameda, CA 47 PA R T I Oracle Essentials INTRODUCING THE UNIVERSAL INSTALLER 48 CHAPTER 2 • INSTALLING, UPGRADING,... server and the expected user process loads • Make sure the operating system level, with all required patch sets, is supported by the Oracle version you are going to install Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark www.sybex.com Copyright ©2002 SYBEX, Inc., Alameda, CA • For any optional Oracle software that you are installing, find out about any specific preinstall . Copyright ©2002 SYBEX, Inc., Alameda, CA www.sybex.com Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 29 NOTE Several database management. Copyright ©2002 SYBEX, Inc., Alameda, CA www.sybex.com Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. CHAPTER 1 • ELEMENTS OF ORACLE