Oracle Database 11G SQL and PL/SQL: a Brief Primer
Total Page:16
File Type:pdf, Size:1020Kb
APPENDIX ■ ■ ■ Oracle Database 11g SQL and PL/SQL: A Brief Primer I’m sure most of you are already familiar with SQL to some extent. However, I present in this appendix a quick introduction to Oracle Database 11g SQL and its programmatic cousin, PL/SQL, as a starting point for those new to programming Oracle databases. My goal here is simply to present a short summary of the classic DML and DDL commands and to discuss the newer SQL and PL/SQL concepts in greater detail. Your need to know SQL or PL/SQL depends somewhat on the type of DBA you are—a production support DBA won’t need to know as much about Oracle programming as a DBA assisting in develop- mental efforts. It’s becoming increasingly important, however, for DBAs to learn a number of advanced SQL and PL/SQL concepts, including the new Java and XML-based technologies. The reason is simple: even when you aren’t developing applications yourself, you’re going to be assisting people who are doing so, and it helps to know what they’re doing. This appendix aims to summarize some of the most important Oracle Database 11g SQL and PL/SQL features so you and the developers you work with can take advantage of them. Oracle SQL and PL/SQL represent an enormously broad topic, so this appendix lightly covers several important topics without attempting any detailed explanation due to space considerations. Please refer to the Oracle manuals Application Developer’s Guide—Fundamentals and PL/SQL User’s Guide and Reference for a comprehensive introduction to SQL and PL/SQL. The Oracle Database 11g Sample Schemas The examples in this appendix use the demo schemas provided by Oracle as part of the Oracle Data- base 11g server software. The demo data is for a fictitious company and contains the following five schemas: • HR is the human resources division, which contains information on employees. It is the most commonly used schema, with its familiar employees and dept tables. The schema uses scalar data types and simple tables with basic constraints. • OE is the order entry department, which contains inventory and sales data. This schema covers a simple order-entry system and includes regular relational objects as well as object- relational objects. Because the OE schema contains synonyms for HR tables, you can query HR’s objects from the OE schema. • PM is the product media department, which covers content management. You can use this schema if you’re exploring Oracle’s Multimedia option. The tables in the PM schema contain audio and video tracks, images, and documents. 1221 1222 APPENDIX ■ ORACLE DATABASE 11G SQL AND PL/SQL: A BRIEF PRIMER • IX is the information exchange department in charge of shipping using various B2B applications. • SH is the sales history department in charge of sales data. It is the largest sample schema, and you can use it for testing examples with large amounts of data. The schema contains parti- tioned tables, an external table, and Online Analytical Processing (OLAP) features. The SALES and COSTS tables contain 750,000 rows and 250,000 rows, respectively, as compared to 107 rows in the employees table from the HR schema. In order to install the SH schema, you must have the partitioning option installed in your Oracle database; this option lets you use table and index partitioning in your database. Ideally, you should install the Oracle demo schemas in a test database where you can safely practice the parts of SQL you aren’t familiar with. The Oracle Sample Schemas documentation manual provides detailed informa- tion about the sample schemas. If you’ve created a starter database using the Database Configuration Assistant (DBCA) as part of your Oracle software installation (the Basic Installation option), it will have automatically created the sample schemas in the new starter database. If you’ve chosen to not create the starter database (by selecting a Software Only installation option), you can run the DBCA to install the sample schemas. Choose the Sample Schemas option when you use the DBCA to create the sample schemas in an existing database. By default, all the sample schema accounts are locked, and you must use the ALTER USER . ACCOUNT UNLOCK state- ment to unlock them. If you want to create the sample schemas in a database without using the DBCA, you can run Oracle-provided scripts to install the sample schemas. Oracle Data Types Data in an Oracle database is organized in rows and columns inside tables. The individual columns are defined with properties that limit the values and format of the column contents. Let’s review the most important Oracle built-in data types before we look at Oracle SQL statements. Character Data Types The CHAR data type is used for fixed-length character literals: SEX CHAR(1) The VARCHAR2 data type is used to represent variable-length character literals: CITY VARCHAR2 (20) The CLOB data type is used to hold large character strings and the BLOB and BFILE data types are used to store large amounts of binary data. Numeric Data Types There are two important SQL data types used to store numeric data: •The NUMBER data type is used to store real numbers, either in a fixed-point or floating-point format. •The BINARY FLOAT and BINARY DOUBLE data types store data in a floating-point format. APPENDIX ■ ORACLE DATABASE 11G SQL AND PL/SQL: A BRIEF PRIMER 1223 Date and Time Data Types There are a couple of special data types that let you handle date and time values: •The DATE data type stores the date and time (such as year, month, day, hours, minutes, and seconds). •The TIMESTAMP data type stores time values that are precise to fractional seconds. Conversion Functions Oracle offers several conversion functions that let you convert data from one format to another. The most common of these functions are the TO_CHAR, TO_NUMBER, TO_DATE, and TO_TIMESTAMP functions. The TO_CHAR function converts a floating number to a string, and the TO_NUMBER function converts a floating number or a string to a number. The TO_DATE function converts character data to a DATE data type. Here are some examples: SQL> SELECT TO_CHAR(TO_DATE('20-JUL-08', 'DD-MON-RR') ,'YYYY') "Year" FROM DUAL; Year ------------------------------------------------------------------------------- 2008 SQL> SQL> SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY') FROM DUAL; TO_CHAR(SYSDATE -------------- 20-JUL-2008 SQL> SQL In Chapter 7 you saw how Oracle SQL statements include DDL, DML, and other types of statements. Let’s begin with a review of the basic SQL statements. The SELECT Statement The SELECT statement is the most common SQL statement (it is also called a projection). A SELECT statement retrieves all or some of the data in a table, based on the criteria that you specify. The most basic SELECT statement is one that retrieves all the data in the table: SQL> SELECT * FROM employees; To retrieve only certain columns from a table, you specify the column names after the SELECT keyword, as shown in the following example: SQL> SELECT first_name, last_name, hiredate FROM employees; If you want only the first ten rows of a table, you can use the following statement: SQL> SELECT * FROM employees WHERE rownum <11; 1224 APPENDIX ■ ORACLE DATABASE 11G SQL AND PL/SQL: A BRIEF PRIMER If you want just a count of all the rows in the table, you can use the following statement: SQL> SELECT COUNT(*) FROM employees; If a table has duplicate data, you can use the DISTINCT clause to eliminate the duplicate values, as shown here: SQL> SELECT DISTINCT username FROM V$SESSION; The optional WHERE clause in a SELECT statement uses conditions to help you specify that only certain rows be returned. Table A-1 lists some of the common conditions you can use in a WHERE clause. Table A-1. Common Conditions Used in WHERE Clauses Symbol Condition = Equal > Greater than < Less than <+ Less than or equal to >= Greater than or equal to <> or ! Not equal to Here are some examples of using the WHERE clause: SQL> SELECT employee_id WHERE salary = 50000; SQL> SELECT employee_id WHERE salary < 50000; SQL> SELECT employee_id WHERE salary > 50000; SQL> SELECT employee_id WHERE salary <= 50000; SQL> SELECT employee_id WHERE salary >= 50000; SQL> SELECT employee_id WHERE salary ! 50000; The LIKE Condition The LIKE condition uses pattern matching to restrict rows in a SELECT statement. Here’s an example: SQL> SELECT employee_id, last_name FROM employees 2* WHERE last_name LIKE 'Fa%'; EMPLOYEE_ID LAST_NAME ----------- ---------- 109 Faviet 202 Fay SQL> The pattern that you want the WHERE clause to match should be enclosed in single quotes (' '). In the preceding example, the percent sign (%) indicates that the letters Fa can be followed by any character string. Thus, the percent sign acts as a wildcard for one or more characters, performing the same job as the asterisk (*) in many operating systems. Note that a single underscore character (_) acts as a wildcard for one and only one character. APPENDIX ■ ORACLE DATABASE 11G SQL AND PL/SQL: A BRIEF PRIMER 1225 The INSERT Statement The INSERT statement enables you to add new data to a table, including duplicate data if there are no unique requirements enforced by a primary key or an index. The general form of the INSERT state- ment is as follows: INSERT INTO <table> [(<column i, . , column j>)] VALUES (<value i, . ,value j>); Here is an example of the insert command: SQL> INSERT INTO employees( 2 employee_id,last_name,email,hire_date,job_id) 3 VALUES 4* (56789,'alapati','[email protected]', sysdate,98765); 1 row created. SQL> In the preceding list, the column names were specified because only some columns were being populated in the row being inserted.