SQL for Queries
early every data retrieval process creates an SQL query and sends it to the Oracle8 engine. Your process may be direct, as in the case of an ad hoc query you create in SQL Worksheet. On the other hand, a third-party software package, such as NetDynamics, may hide the query inside a Java script. This chapter describes how to create simple and complex SQL queries. A good query enables you to create useful reports quickly and easily. This chapter describes how to construct basic SQL queries for getting data out of a Table and also illustrates how to use the more interesting SQL functions when writing queries. When you finish this chapter, you’ll know the proper syntax of SQL queries.

3 3 3 3




In This Chapter
Selecting your tool Building basic queries Joining Tables Using SQL functions in queries



Selecting Your Tool
SQL*Plus and SQL Worksheet are the two standard Oracle8 primary tools for developing your queries. Table 9-1 illustrates the pros and cons of each tool. All methods discussed in this chapter work equally well in either tool. As a developer and DBA, I prefer developing SQL in the SQL Worksheet because of its superior capabilities in editing and cycling through previous commands. Once I have the query working, I move over to SQL*Plus to complete the report (if the report is my final product).

Chapter 14 shows you how to take queries and turn them into full-fledged reports. You learn how to add headers and titles as well as how to sort, group, summarize, and adjust Column formats.


Chapter 9 3 SQL for Queries

Table 9-1 SQL*Plus and SQL Worksheet Compared
Feature Windows-like Browse tool for retrieving and saving files Editor Editing in tool Format numbers Format headings Retrieve prior commands Behavior on exit SQL Worksheet Good Yes Use any editor you want Mouse-capable, cut/paste No No Yes Rolls back transaction by default on exit SQL*Plus Poor No Use any editor you want Line-mode only, no mouse, limited cut/paste Yes, using SET command Yes, using COLUMN command Only most recent command Commits transaction by default on exit

The following two sections show you basic techniques for getting around in SQL Worksheet and SQL*Plus.

How to use SQL Worksheet for queries
To start SQL Worksheet, follow these steps: 1. Start the Enterprise Manager toolbar. If you are running Windows NT, choose Start Á Programs Á Oracle Enterprise Manager Á Administrator Toolbar. The toolbar appears across the top of your desktop. 2. Start the SQL Worksheet. Click the SQL Worksheet icon (which looks like a paper and pencil) in the Enterprise Manager toolbar. SQL Worksheet prompts you to log in to the database.
On the CD-ROM

3. Log in as the owner of the Table you are changing. Log in with a valid Oracle8 User name and password. If you installed the sample schema included on the CD-ROM, log in as AMY with password AMY123. Leave the Service box empty if you are running your own personal Oracle8; otherwise, fill in the name of the Oracle8 database (instance) on your network. Leave the Connect As box set to Normal.

Chapter 9 3 Selecting Your Tool


Figure 9-1 illustrates the SQL Worksheet window. A column of buttons along the lower-left window helps you work with files.

Figure 9-1: Enter a valid User name and password here.

These buttons are: 3 New. Starts a new worksheet. If you have anything in your current worksheet, the SQL Worksheet asks you whether to save the worksheet before wiping the slate clean for your new worksheet. 3 Open. Opens a previously saved worksheet. 3 Save. Saves current worksheet in a file. 3 Execute. Executes current worksheet. 3 Command History. Opens a window showing recent worksheets. Choosing one worksheet will replace your current worksheet. 3 Previous Command. Replaces the current worksheet with the preceding worksheet. 3 Next Command. Replaces the current worksheet with the following worksheet. Use in combination with the Previous Command button to move back and forth among commands you executed.


Chapter 9 3 SQL for Queries

How to use SQL*Plus for queries
SQL*Plus runs on both the client and the server side for Oracle8. To start up SQL*Plus on the client, add SQL*Plus to the Enterprise Manager Administrator’s toolbar and select the icon. The next two sections show how to start SQL*Plus on the client and the server.

Client-side — adding SQL*Plus to your toolbar
Follow these steps to add a SQL*Plus start button to the Enterprise Manager toolbar: 1. Start the Oracle Administrator toolbar. If you are running Windows NT, click Start Á Programs Á Oracle Enterprise Manager Á Administrator Toolbar. Your toolbar appears as a small set of buttons on your desktop as shown in Figure 9-2.

Figure 9-2: The Enterprise Manager toolbar sits on your desktop.

2. Right-click anywhere on the bar and select Customize. Right-click brings up a pop-up menu. Select Customize… from the menu. The Customize window pops up as shown in Figure 9-3.

Figure 9-3: Customize the Enterprise Manager toolbar using this window.

Chapter 9 3 Selecting Your Tool


3. Click the Applications tab. Figure 9-4 shows the applications window. By default, most of the tools you need are already selected and ready on the toolbar. Complete the following steps to add a program (SQL*Plus, in this example) to your toolbar and enable your important programs to be at your fingertips. You can add other programs to your toolbar in a similar manner.

Figure 9-4: You already have five applications on the toolbar.

4. Click the Add button. A window pops up to define a new button. 5. Click the Browse button and select executable. This action brings you to the BIN directory where you can choose executable programs to add into your toolbar. Scroll across and click Plus80w.exe, which has an icon that looks like a small yellow plus sign. 6. Click Open. After clicking Open, you proceed to the Add Application Wizard. Figure 9-5 shows the Add Application in ToolBar window after selecting Plus80w.exe. 7. Click Next and fill in information. After clicking the Next button, another window (shown in Figure 9-6) enables you to select a toolbar title for your program. Type SQL*Plus in the Name box. Because SQL*Plus is a database application, select the Yes radio button. 8. Click the Finish button. This action returns you to the Customize window. SQL*Plus appears at the bottom of the list.


Chapter 9 3 SQL for Queries

Figure 9-5: Here’s the first step to adding SQL*Plus to the Enterprise Manager toolbar.

Figure 9-6: Name the new application on on the toolbar.

9. Click OK to apply this change and exit the Customize window. After returning to your desktop, Enterprise Manager takes a moment to think and then refreshes your toolbar. The toolbar with the additional SQL*Plus icon appears on your desktop as shown in Figure 9-7.

Figure 9-7: Your customized toolbar contains an SQL*Plus icon.

Whenever you need to use SQL*Plus, just call up your Enterprise Manager toolbar and click the big yellow plus sign.

Chapter 9 3 Selecting Your Tool


Server-side — starting SQL*Plus
Server-side SQL*Plus provides a line-mode tool. When you cannot use a GUI interface, this tool gives you the ability to query your database directly. Results are delivered, line by line, back to your terminal. Follow these steps to start SQL*Plus from the server: 1. Open a command line prompt on the server. 2. Start SQL*Plus. On the command line, type:

Press Enter. SQL*Plus starts and prompts you for a User name. 3. Type a valid Oracle8 User name and press Enter. SQL*Plus prompts you for your password. 4. Type the password and press Enter. The password does not appear on the terminal. 5. SQL*Plus initiates your SQL session. The command prompt changes to:

This prompt indicates you are using SQL*Plus. 6. To exit, type:

Press Enter. The prompt returns to the normal operating system prompt. Now you are ready to work through this chapter’s examples to learn how to create queries. Because no one is a perfect typist, the following section shows you useful tips on how to edit your code during your SQL*Plus session.

Editing your work in SQL*Plus
You can call an editor to save, edit, and start files from within SQL*Plus. The editing commands follow: 3 EDIT: opens a temporary file and starts the local text editor for the current SQL query. 3 SAVE filename: saves the current SQL query in a file. Replace filename with the actual filename — you can also include the path and suffix. 3 GET filename: retrieves an SQL query from the file you name.


Chapter 9 3 SQL for Queries

3 START filename: retrieves and runs a file in the current SQL Worksheet session. The file can include both SQL and formatting commands, such as TTITLE, COLUMN, and SPOOL. 3 LIST: lists your current SQL command in the SQL buffer. In addition, the following line-edit commands within SQL*Plus enable simple changes to your commands without calling an external editor. 3 C/x/y. Change x into y. The command works once on the current line. For example, to correct a spelling error, you might type:

3 L. List current command. 3 Ln. Make line number n current. This command enables you to use the other line-edit commands on the current line. 3 DEL. Delete the current line. 3 I. Insert a new line below the current line. This command enables you to add onto the current SQL query. Choose either SQL*Plus or SQL Worksheet and follow along through the ensuing sections to learn how to create effective and efficient queries. To execute a query, you have two choices: 3 Type a slash (/) on a line by itself following your query. Then press Enter. 3 Type a semicolon (;) on the last line or on a line following your query. Then press Enter.

After executing a query, type a slash (/) and press Enter to execute it again.

The Basic SQL Query
See Reference Section


A SQL query has five main parts (or clauses): 3 SELECT. Put the list of Columns you want to view in this clause. List all the Columns, even if they are from several Tables, and separate them with commas. 3 FROM. Put the Table name in this clause. If you have more than one Table, separate Table names with commas.

Chapter 9 3 The Basic SQL Query


3 WHERE (optional). Put comparisons, limits, and connections between Tables in this clause and list them with either AND or OR between each set. When the WHERE clause is left out, all rows are chosen. 3 GROUP BY (optional). Describe how you want data summarized in this clause. You only need this clause for a query that summarizes data. 3 ORDER BY (optional). List Columns to use for sorting in this clause. When there is no ORDER BY clause, rows are returned in the order they were inserted into the database. Although other clauses can go into a query, the preceding list details are the primary clauses. Here’s how the five parts fit together in a single SQL query:
select column, column , ... from table where clause group by clause order by clause

Sampling some queries

An art dealer represents ten artists around the country. He asks you to prepare a list of all the artists showing their first names, cities of residence, and creative specialties. The query looks like this:

Three Columns are chosen from one Table. The results may look like this:
FIRST_NAME CITY SPECIALTY ----------------------------------------------Lina Lone Rock OTHER Nikki Makawao ACRYLIC Lorri Madison WATERCOLOR Robert Salt Lake City MIXED MEDIA Thomas Madison OIL Stephen Makawao MIXED ON PAPER Ken Marin County DIGITAL Sherry San Francisco WATERCOLOR Terence DIGITAL Sharron San Francisco DIGITAL 10 rows selected.


Chapter 9 3 SQL for Queries

The art dealer wants the list in alphabetical order. Add an ORDER BY clause:

The results appear sorted in ascending alphabetical order by first name:
FIRST_NAME CITY SPECIALTY ----------------------------------------------Ken Marin County DIGITAL Lina Lone Rock OTHER Lorri Madison WATERCOLOR Nikki Makawao ACRYLIC Robert Salt Lake City MIXED MEDIA Sharron San Francisco DIGITAL Sherry San Francisco WATERCOLOR Stephen Makawao MIXED ON PAPER Terence DIGITAL Thomas Madison OIL

Suppose the art dealer says he only wants to see the watercolor artists. Add the WHERE clause to narrow down your selection. The WHERE clause comes between the FROM and the ORDER BY clause. When using a literal in the WHERE clause, enclose it in single quotes (except numbers, which need no quotes).
select FIRST_NAME, city, specialty from artist where specialty = ‘WATERCOLOR’ order by FIRST_NAME;

Oracle8 looks for rows that have WATERCOLOR in the SPECIALTY Column and then sorts the rows in proper order.
FIRST_NAME CITY SPECIALTY ------------------------------------Lorri Madison WATERCOLOR Sherry San Francisco WATERCOLOR

Oracle8 is always case-sensitive. In the preceding example, a row containing ‘Watercolor’ in the SPECIALTY Column would not be selected.
See Reference Section


The character function UPPER helps simplify queries by converting mixed-case text into uppercase.

Chapter 9 3 The Basic SQL Query


Some tips to help you write good queries

Some of these tips are guidelines or hints for good form; others are simply possibilities — available options of which you may not be aware. 3 List Columns in the sequence they appear in your report. The SELECT clause is your only chance to specify which Column comes first, second, and so forth. 3 Use the asterisk to select all Columns in a Table. This tip saves typing time when you need all Columns (in the sequence they appear in your Table) in your query.

3 List Columns in the order you sort them. Although not required, this tip is recommended for logical results — for example, listing people’s names in the phone book with their last name first to facilitate quick visual searching.

3 Add words or phrases in your SELECT statement to make your report clearer. For example:
select 'My name is', NAME from ARTIST;

3 Sort by multiple Columns. List the Columns in the ORDER BY clause as in this example:

3 Oracle8 is sensitive to uppercase and lowercase in the words or phrases that you place inside single quotes.
... where SPECIALTY = 'Watercolor'

3 The preceding phrase is different from the following one:

3 Oracle8 does not differentiate between uppercase and lowercase for Column names, Table names, and the SELECT statement clauses, except when the Table or Column name was created with the name enclosed in double quotes. In these cases, use double quotes around the Table name or Column name and match the case.


Chapter 9 3 SQL for Queries

3 The preceding query is identical to the following one:
select city from artist;

3 You can mix and match case in your SQL. Oracle8 sees the following query as the same as the preceding two:
select CITY from ARTIST;

3 Oracle8 does not care how you arrange blank spaces and line breaks in the query.
select CITY, SPECIALTY from ARTIST order by CITY;

3 To Oracle8, the preceding query is identical to the following one:
select CITY, SPECIALTY from ARTIST order by CITY;

3 This tip is purely for aesthetics: I prefer to start each clause (SELECT, FROM, WHERE, and ORDER BY) on a new line.

Joining Tables
When a query combines data from two Tables, it is called a join (or joining Tables). The key to joining Tables is — the key! Know your Tables, their keys, and how they connect. I’ve created examples with simple and complex joins.

Basic join
See Reference Section


The basic structure of a join matches the standard query structure. A join differs from a query in the following ways: you list Columns from several Tables in the SELECT clause, list several Tables in the WHERE clause, and tell SQL how they fit together in the WHERE clause. Here’s the basic layout:

Chapter 9 3 Joining Tables


A Table alias (indicated in the preceding query as alias1 and alias2) assigns a shorthand nickname to each Table in the FROM clause. Use the alias (followed by a period) as an identifier to show which Table is the source of each Column in the other parts of the query (the SELECT, WHERE, GROUP BY, and ORDER BY clauses). Although a Table alias is not technically required, I find it important for creating clear and easy-to-follow join queries. The next section shows several examples of join queries in action. As a general rule of thumb, the complexity of the WHERE clause increases with the addition of Tables to a query.

Examples of join queries

You have two Tables: TYPE_OF_SALAD for types of salads and SALAD_TRAY for each salad in a restaurant cooler. You want a simple report to list the seaweed samples and show whether they are organic. The SQL code:

The results:
TRAY_ID SELLING_PRICE SALAD_DESC ORGANIC_FLAG ----------------------------------------------------------1 100 Leafy green NO 2 30 Purple delicate YES 3 110 Green delight YES 4 100 Leafy green NO 5 30 Purple delicate YES 6 110 Green delight YES

To keep track of your customers, in case you want to send them a flyer next year, add a Table called CLIENT to your database. Now you have three Tables as shown in Figure 9-8. Add a new Column to the SALAD_TRAY Table, which is a Foreign Key to the CLIENT Table.


Chapter 9 3 SQL for Queries



is a type of salad in



Figure 9-8: The entrepreneur tracks clients who buy her salad trays.

This query combines all three Tables:

The results:
TRAY_ID ORGANIC_FLAG NAME -----------------------------1 NO Jane 4 NO Jane 3 YES Joe 6 YES Joe 2 YES Harry 5 YES Amy

The results show: a list of the salad trays, which types of salad trays are organic, which are not organic, and which of your customers bought the tray. Now you have completed several exercises in which you used SQL commands to get a basic report out of the database. The following section describes the outer join, a way to query on more complex relationships.

Outer join
Normally, when you join two Tables, you are only interested in rows that contain a match between the two Tables. Sometimes, you need to include mismatched rows from one of the Tables. An outer join allows these mismatches. One of the Tables is chosen as the primary Table. Any row in this Table without matches in the other Table stays in the results. For these rows, Oracle substitutes null values for any Column from the second Table.

Chapter 9 3 Joining Tables


The syntax for an outer join is nearly the same as a normal join (sometimes called an inner join). A special symbol, (+), tells Oracle8 your query contains an outer join. These special rules apply when creating outer join queries: 3 Every Column in a Table designated as an outer join Table must have (+) (the outer join symbol) after the Column name. 3 If there are multiple outer join Tables, each must be joined to a non-outer join Table. No two outer join Tables can be joined to each other.

Assume you have two Tables: CUSTOMER_ACCOUNT and ACCOUNTS_RECEIVABLE. If a customer has no accounts receivable this month, the ACCOUNTS_RECEIVABLE Table contains no row for that customer. You want a list of all your customers and their current accounts receivable balance for November. Any customer without accounts receivable should be listed with a zero in the Accounts Receivable Column. Using an inner join fails to select all your customers. Your list only includes the customers that actually have a row in your ACCOUNTS_RECEIVABLE Table. Using an outer join gets the desired results because your list includes all customers whether or not they have a row in the ACCOUNTS_RECEIVABLE Table. To create an outer join, add (+) at the end of each Column of the outer join Table (the ACCOUNTS_RECEIVABLE Table) in the WHERE clause. The query looks like this:

The results:
NAME NVL(A.AMOUNT_OWED,0) --------------------------------------------------Jane 600 Joe 0 Harry 0 Amy 480

In the preceding example, two customers (Joe and Harry) have no rows related to the month of November.


Chapter 9 3 SQL for Queries

Using subqueries
The second variation on the SELECT command has a great amount of flexibility because it uses a subquery — a query within the query. A sample of the format:
SELECT columnname3, columnname4, ... FROM tablename1 WHERE (columnname5, columnname6, ...) IN (SELECT columnname7, columnname8,... FROM tablename2 WHERE clause);

The subquery constitutes everything inside the parenthesis after the word IN. You can place any query inside the subquery as long as the Columns in the subquery (columnname7, columname8, ...) match the Columns in the outside query (columnname5, columname6, ...). Notice the two WHERE clauses. The last clause corresponds to the subquery SELECT statement. The first clause in the statement corresponds to the primary query. The subquery format has many variations — listing all variations is impossible. Using a subquery helps when you do not have a predefined list of values to query against. For example, a look-up Table might have new values inserted into the Table. If you use a predefined list, you have to edit your query to add the new values. If you use a subquery, the new values are included with no changes to the query.

This example shows how you can use a subquery to compare rows of a Table to other rows of the same Table. You run an art gallery. You have a Table called MONTHLY_SALES. You want to list all the days in February where sales matched or exceeded the highest sales day in January.

Oracle8 shows two rows in the sample data fit this query criteria:
SALES_DAT SALES_AMOUNT ---------------------01-FEB-98 1230 05-FEB-98 1440

Chapter 9 3 SQL Functions in Queries


Exists clause
Often, the IN operator is used with a subquery. Another useful operator, EXISTS, replaces IN. You gain performance speed using EXISTS because Oracle8 evaluates the main query first and runs the subquery only until it finds a match. With IN, Oracle8 suspends processing of the main query while executing the subquery to make a list. Oracle8 stores that list in an indexed temporary Table and then resumes processing of the main query. Although exceptions exist, Oracle8 usually performs queries that use EXISTS faster than those that use IN. Therefore, examine your WHERE clause for the IN condition. In most cases, you can replace the IN condition of a subquery with EXISTS.

Here’s an example of a subquery using EXISTS:

Here’s the same query using IN for the subquery:

The first example gets the same results (the same rows retrieved) as the second example but runs faster because it uses EXISTS rather than IN.

SQL Functions in Queries
This section describes some of the interesting functions available in Oracle8 SQL. These functions add power to a query and give you more flexibility in your code.

The DECODE function
See Reference Section


You use the DECODE function to work as a filter and transformer inside a query. Apply DECODE to any character-datatype Column. Your FISH Table, for example, has a Column for DEATH_DATE. This Column contains the fish’s death date or null in every row. You want to run a query that translates the Column into either DEAD or ALIVE instead of the actual value of the DEATH_DATE Column. DECODE can help. Here’s the query:


Chapter 9 3 SQL for Queries

The DECODE function acts like an “IF-THEN-ELSE” logical structure. In the preceding code, if the value in DEATH_DATE is null, the DECODE returns the value ‘ALIVE.’ Otherwise, the DECODE returns the value ‘DEAD.’ The resulting report looks like Figure 9-9.

Figure 9-9: The DECODE function has lots of potential.

You can use the DECODE function anywhere you use a Column. DECODE is a powerful tool worth considering to help simplify queries.

The INSTR function
See Reference Section

INSTR INSTR (short for INSTRING) is a function that you apply to a character-datatype Column. INSTR hunts down a phrase or letter and tells you exactly where it starts.

For example, the letter a holds the second position in my name (Carol). If the Column does not contain the phrase or letter, INSTR returns zero. Here’s an example:

In this example, you look for the letter b in the COMMENT_TEXT Column. The report, shown in Figure 9-10, states two of the rows have a letter b in the seventh position and one has the letter b in position 34.

Chapter 9 3 SQL Functions in Queries


Figure 9-10: Locating a word, letter, or phrase can be done using INSTR.

The SUBSTR function
See Reference Section

SUBSTR SUBSTR, also called SUBSTRING, cuts off a portion of a Column’s data.

Here’s an example that combines two functions: INSTR and SUBSTR. You want to grab the first word in the COMMENT_TEXT Column and use it in your report. Use INSTR to find a blank character inside the COMMENT_TEXT Column; then use SUBSTR to cut off the Column at that point. The INSTR function acts as a parameter (the starting point) for the SUBSTR function.

In this example, I add the complete COMMENT_TEXT so you can verify the results easily. Figure 9-11 shows these results.

Figure 9-11: You can easily remove sections of data using SUBSTR.


Chapter 9 3 SQL for Queries

See Reference Section


The CONCATENATE symbol combines two Columns or a Column and a literal phrase. If you want to insert the words The Honorable in front of your fish’s names, for example, use the CONCATENATE symbol as follows:

Figure 9-12 shows the report. One small detail: I add a blank space at the end of the phrase, because the concatenation leaves no space between the two Columns or combined phrases.

Figure 9-12: A literal and Column data are concatenated.

The CONCATENATE symbol consists of two vertical bars on nearly all platforms. On rare occasions, the CONCATENATE symbol gets mistranslated when you port between some platforms. To accommodate this problem, Oracle8 provides a function called CONCAT you can use as a substitute. Use concatenation between two Columns, literals and Columns, or a series of literals and Columns.

The NVL function
See Reference Section


The NVL function enables you to substitute a phrase, number, or date for a null value in a row’s Column. Here’s an easy example:

In this example, when a fish has a null value in its SEX Column, the word Unknown appears in its place but does not change the underlying data. The NVL function changes only the report. Figure 9-13 shows the report.

Chapter 9 3 Summary


Figure 9-13: Replace null values in a report with a literal or another Column’s data. NVL helps when you are calculating numbers and you need to replace nulls. Nulls,

as you may have seen, gum up calculations. Any math executed on a null results in a null. To remedy this problem, change null values to zeros by using the NVL function.

When creating and testing SQL queries, you can use either SQL Worksheet or SQL*Plus. Each tool has specific advantages and disadvantages for particular uses. When using SQL Worksheet, get familiar with the windows-like interface. You can save files, save output, edit files, execute commands, view and recall previous commands, and even record your activity into a transaction log. When using SQL*Plus on a client machine, you can add the tool to your Administrator Toolbar for convenience. SQL*Plus can also be used on the server side. Start the server-side SQL*Plus with the sqlplus command. SQL*Plus has its own built-in line editor. You can also save, recall, and execute files containing SQL, PL/SQL, and SQL*Plus commands. Learning to write queries is a basic skill in SQL. The same queries are used in other commands, such as INSERT and UPDATE. The SQL SELECT command is the mechanism for queries. The SELECT command has five basic components: the SELECT, FROM, WHERE, GROUP BY, and ORDER BY clauses.


Chapter 9 3 SQL for Queries

This chapter illustrates basic single Table queries and discusses tips to writing good queries, and then constructs several different kinds of more complex queries. A join query brings out data from two or more related Tables. An outer join also selects data from two or more related Tables; it allows rows from one Table to be returned in the results even if the rows are not related to rows in the other joined Tables, however. Subqueries add flexibility by allowing you to construct a query inside a query used in the WHERE clause of the initial query. Correlated subqueries, a more complex variation on the subquery, allow you to constrain the results of the subquery based on the current row of the outer query. The EXISTS clause also adds speed and efficiency to your code with a subquery. Functions are ways to modify Column contents within the context of the query. When used in a query, the underlying data does not change. Functions can be used anywhere a Column can be used. The DECODE function is like a miniature IF-THENELSE command built into a Column. The INSTR function looks for matching text portions in a Column. The SUBSTR function truncates contents of a Column at a specified point. The CONCATENATE function combines the value of two Columns (or a Column and a literal) into a single Column. The NVL function replaces null values within a Column with a specified value such as a zero.




Sign up to vote on this title
UsefulNot useful