- Lab 2.1: The SQL*Plus Environment
- Lab 2.2: The Anatomy of a SELECT Statement
- LAB 2.3: Editing a SQL Statement
- LAB 2.4: The WHERE Clause: Comparison and Logical Operators
- LAB 2.5: The ORDER BY Clause
- Chapter 2: Test Your Thinking
Lab 2.2: The Anatomy of a SELECT Statement
Lab Objectives
After this lab, you will be able to:
-
Write a SQL SELECT Statement
-
Use DISTINCT in a SQL Statement
The Select Statement
When you write a SQL query, it is usually to answer a question such as "How many students live in New York?" or "Where, and at what time, does the Unix class meet?" A SQL SELECT statement, or SQL query, is used to answer these questions. A SELECT statement can be broken down into a minimum of two parts: the SELECT list and the FROM clause. The SELECT list usually consists of the column or columns of a table(s) from which you want to display data. The FROM clause states on what table or tables this column or columns are found. Later in this chapter, you will learn some of the other clauses that can be used in a SELECT statement.
How Do You Write a SQL Query?
Before formulating the SELECT statement, you must first determine the table where the information is located. A study of the schema diagram reveals that the course table provides descriptions of courses. (You can also refer to Appendix E, "Table and Column Descriptions.")
The following SELECT statement provides a list of course descriptions:
SELECT description FROM course
The SELECT list shows the single column called DESCRIPTION, which contains this information. The DESCRIPTION column is found on the COURSE table as specified in the FROM clause. When the statement is executed, the result set is a list of all the values found in the DESCRIPTION column of the COURSE table:
------------------------- DP Overview Intro to Computers ... JDeveloper Techniques DB Programming in Java 30 rows selected.
Many of the result sets displayed throughout this book do not list all the rows. This is denoted with a line of "..." in the middle of the output. Typically, you will see the beginning and the ending rows of the result set and the number of rows returned. The resulting output of the SQL command is displayed in a bold font to easily distinguish the output from the commands you enter.
EXECUTING THE SQL STATEMENT
SQL*Plus does not require a new line for each clause, but it requires the use of a semicolon (;) at the end of each SQL statement to execute it. (Figure 2.11 shows the result of the execution of the previously mentioned SQL query in SQL*Plus.) Alternatively, the forward slash (/) may be used on a separate line to accomplish the same. In iSQL*Plus a semicolon or forward slash is not required, you only need to press the Execute button:
SQL> SELECT description 2 FROM course;or:
SQL> SELECT description 2 FROM course 3 /
The SQL*Plus commands such as DESC or SHOW USER discussed in the previous lab are not SQL commands and therefore do not require a semicolon or forward slash.
Figure 2.11 Executing the SELECT statement in SQL*Plus.
Retrieving Multiple Columns
To retrieve a list of course descriptions and the cost of each course, include the cost column in the SELECT list:
SELECT description, cost FROM course DESCRIPTION COST ------------------------ ---- DP Overview 1195 Intro to Computers 1195 ... JDeveloper Techniques 1195 DB Programming in Java 30 rows selected.
When you want to display more than one column in the SELECT list, separate the columns with commas. It is good practice to include a space after the comma for readability. The order of columns in a SELECT list will determine the order in which the columns are displayed in the output.
SELECTING ALL COLUMNS
You can also select all columns in a table with the asterisk (*) wildcard character. This is handy so you don't have to type all columns in the SELECT list. The columns are displayed in the order in which they are defined in the table. This is the same order you see when you use the SQL*Plus DESCRIBE command. If you execute this command you will notice that the columns wrap in SQL*Plus (not iSQL*Plus) as there is not sufficient room to display them in one line. You will learn how to format the output shortly.
SELECT * FROM course
Eliminating Duplicates with Distinct
The use of DISTINCT in the SELECT list eliminates duplicate data in the result set. The following SELECT statement retrieves the last name and the corresponding zip code for all rows of the INSTRUCTOR table.
SELECT last_name, zip FROM instructorLAST_NAME ZIP ------------------------- ----- Hanks 10015 Wojick 10025 Schorin 10025 Pertez 10035 Morris 10015 Smythe 10025 Chow 10015 Lowry 10025 Frantzen 10005 Willig 10 rows selected.
Notice that there are 10 rows, yet only nine instructors have zip codes. Instructor Willig has a NULL value in the ZIP column. If you want to show only the distinct zip codes of the table, you write the following SELECT statement. The last row shows the NULL value.
SELECT DISTINCT zip FROM instructor ZIP --- 10005 10015 10025 10035 5 rows selected.
By definition, a NULL is an unknown value, and a NULL does not equal another NULL. However, there are exceptions: If you write a SQL query using DISTINCT, SQL will consider a NULL value equal to another NULL value.
From Chapter 1, "SQL and Data," you already know that a primary key is always unique or distinct. Therefore, the use of DISTINCT in a SELECT list containing the primary key column(s) is unnecessary. The ZIP column in the INSTRUCTOR table is not the primary key and can therefore contain duplicate values.
DISPLAYING the Number of Rows Returned
You may notice that SQL*Plus sometimes does not show the number of rows returned by the query, but rather depends on the feedback settings for your SQL*Plus session. Typically, the feedback is set to 6 or more rows. In the previous example the feedback was set to 1, which displays the feedback line even when there is only one row returned. You will find this setting useful if your result set returns less than the default six rows and if any of the rows return nulls, which display as a blank. Otherwise, you may think it is not a row or value. To display the exact number of rows returned until you exit SQL*Plus, enter the SQL*Plus command:
To display your current settings use the SHOW ALL command or simply SHOW FEEDBACK. (If you want to retain certain SQL*Plus settings, you can create a login.sql file for your individual computer in a clientserver setup. You can also create a glogin.sql file for all users if you want all to have the identical settings or if you use iSQL*Plus. See the companion Web site for more information.)
SQL STATEMENT FORMATTING CONVENTIONS
You will notice that the SQL statements presented in this and all other books in this series follow a common format. The use of uppercase for SELECT, FROM, and other Oracle keywords is for emphasis only, and distinguishes them from table and column names, which you see in the SQL statement as lowercase letters. A standard format enhances the clarity and readability of your SQL statements and helps you detect errors more easily. Refer to Appendix B, "SQL Formatting Guide," for the formatting guidelines used throughout.
Cancelling a Command and Pausing the Output
If you want to stop a command while the statement is still executing, you can press CTRL+C in SQL*Plus for Windows or the Cancel button in iSQL*Plus.
If your result in SQL*Plus is fairly large, you can examine the output by scrolling up and down. If you wish to look at the rows one screen at a time, use the SQL*Plus SET PAUSE ON command. This commands displays one screen at a time and to change the number of lines displayed per screen to use the SET PAGESIZE n command where n is the number of rows per page. To continue to the next screen, press the Enter key in SQL*Plus. If you want to stop scrolling through the screens and return to the SQL> prompt, press CTRL + C. Remember to issue the SET PAUSE OFF command to stop the feature when you are done!
In iSQL*Plus you can choose to display only a specific number of rows per page by clicking on Preferences, Interface Configuration, Output Page Setup, and then Multiple Pages. If the output has more than the specified number of rows, you will see a Next Page button that lets you move to the next page of rows.
Lab 2.2 Exercises
2.2.1 Write a SQL SELECT Statement
-
Write a SELECT statement to list the first and last names of all students.
-
Write a SELECT statement to list all cities, states, and zip codes.
-
Describe the result set of the following SQL statement:
SELECT * FROM grade_type
2.2.2 Use DISTINCT in a SQL Statement
-
Why are the result sets of each of the following SQL statements the same?
-
Explain the result set of the following SQL statement:
-
Explain what happens, and why, when you execute the following SQL statement:
SELECT letter_grade FROM grade_conversion SELECT DISTINCT letter_grade FROM grade_conversion
SELECT DISTINCT cost FROM course
SELECT DISTINCT course_no FROM class
Lab 2.2 Exercise Answers
2.2.1 Answers
-
Write a SELECT statement to list the first and last names of all students.
Answer: The SELECT list contains the two columns that provide the first and last names of students; the FROM clause lists the STUDENT table where these columns are found.
SELECT first_name, last_name FROM student FIRST_NAME LAST_NAME ------------------------- ---------- George Eakheit Leonard Millstein ... Kathleen Mastandora Angela Torres 268 rows selected.
You will also notice many rows are returned; you can examine each of the rows by scrolling up and down. There are many SET options in SQL*Plus that allow you to change the headings and the overall display of the data. As you work your way through this book, you will examine and learn about the most important SQL*Plus settings.
-
Write a SELECT statement to list all cities, states, and zip codes.
-
Describe the result set of the following SQL statement:
Answer: The SELECT list contains the three columns that provide the city, state, and zip code; the FROM clause contains the ZIPCODE table where these columns are found.
SELECT city, state, zip FROM zipcode CITY ST ZIP ------------------------- -------- Santurce PR 00914 North Adams MA 01247 ... New York NY 10005 New York NY 10035 227 rows selected.
SELECT * FROM grade_type
Answer: All columns and rows of the GRADE_TYPE table are returned in the result set. If you use iSQL*Plus, your result will look similar to Figure 2.12. If you use SQL*Plus, your result may resemble the first listing of SQL output in Figure 2.13.
Figure 2.12 SELECT statement against the GRADE_TYPE table issued in iSQL*Plus.
Formatting Your Result: The SQl*PLus COLUMN and Format Commands
If you are using SQL*Plus, not iSQL*Plus, you will notice that the result set is difficult to read when data "wraps" itself onto the next line. The result may look similar to the screen you see in Figure 2.13. This will often occur when your SELECT statement contains multiple columns. To help you view the output more easily, SQL*Plus offers a number of formatting commands.
Figure 2.13 SELECT issued in SQL*Plus for Windows.
The SQL*Plus COLUMN command allows you to specify format attributes for specific columns. Because the SQL statement contains three alphanumeric columns, format each using these SQL*Plus commands:
COCOL description FORMAT A13 COL created_by FORMAT A8 COL modified_by FORMAT A8
When you re-execute the SQL statement, the result is more readable, as you see in the last result set shown in Figure 2.13.
The DESCRIPTION column is formatted to display a maximum of 13 characters; the CREATED_BY and MODIFIED_BY columns are formatted to display 8 characters. If the values in the columns do not fit into the space allotted, the data will wrap within the column. The column headings get truncated to the specified length.
The format for the column stays in place until you either respecify the format for the columns, specifically clear the format for the column, or exit SQL*Plus. To clear all the column formatting, execute the CLEAR COLUMNS command in SQL*Plus.
The two DATE datatype columns of this statement, CREATED_DATE and MODIFIED_DATE, are not formatted by the COL command. By default, Oracle displays all DATE datatype columns with a 9-character width. You will learn about formatting columns with the DATE datatype in Chapter 4, "Date and Conversion Functions."
Formatting Numbers
If the column is of a NUMBER datatype column, you can change the format with a format model in the COLUMN command. For example, the 9 in the format model 999.99 represents the numeric digits, so the number 100 is displayed as 100.00. You can add dollar signs, leading zeros, angle brackets for negative numbers, and round values to format the display to your desire.
COL cost FORMAT $9,999.99 SELECT DISTINCT cost FROM courseCOST ---------- $1,095.00 $1,195.00 $1,595.00 4 rows selected.
If you did not allot sufficient room for the number to fit in the column, SQL*Plus will show a # symbol instead.
COL cost FORMAT 999.99 COST ------- ####### ####### ####### 4 rows selected.
For more SQL*Plus COLUMN FORMAT commands, see Appendix C, "SQL*Plus Command Reference."
Throughout this book you notice that the output is displayed in SQL*Plus rather than iSQL*Plus format. The reason for this is simply that it takes up less space in the book.
2.2.2 Answers
-
Why are the result sets of each of the following SQL statements the same?
SELECT letter_grade FROM grade_conversion SELECT DISTINCT letter_grade FROM grade_conversion
Answer: The result sets are the same because the data values in the LETTER_GRADE column in the GRADE_CONVERSION table are not repeated; the LETTER_GRADE column is the primary key of the table, so by definition its values are already distinct.
-
Explain the result set of the following SQL statement:
-
Explain what happens, and why, when you execute the following SQL statement:
SELECT DISTINCT cost FROM course
Answer: The result set contains four rows of distinct costs in the COURSE table, including the NULL value.
SET FEEDBACK 1 SELECT DISTINCT cost FROM courseCOST ----------- 1095 1195 1595 4 rows selected.
Note that if you changed the feedback SQL*Plus environment variable to 1, using the SQL*Plus command SET FEEDBACK 1, the result will include the "4 rows selected." statement. There is one row in the course table containing a null value in the COST column. Even though null is an unknown value, DISTINCT recognizes one or more null values in a column as one distinct value when returning a result set.
SELECT DISTINCT course_no FROM class
Answer: Oracle returns an error because a table named CLASS does not exist.
FROM class * ERROR at line 2: ORA-00942: table or view does not exist
The asterisk in the error message indicates the error in the query. SQL is an exacting language. As you learn to write SQL, you will inevitably make mistakes. It is important to pay attention to the error messages returned to you from the database to learn from and correct your mistakes. This Oracle error message tells you that you referenced a table or a view does not exist in this database schema. (Views are discussed in Chapter 12, "Views, Indexes, and Sequences.") Correct your SQL statement and execute it again.
Lab 2.2 Self-Review Questions
In order to test your progress, you should be able to answer the following questions.
-
The column names listed in the SELECT list must be separated by commas.
-
True
-
False
-
A SELECT list may contain all the columns in a table.
-
True
-
False
-
The asterisk may be used as a wildcard in the FROM clause.
-
True
-
False
- The following statement contains an error:
-
True
-
False
FROM course
Answers appear in Appendix A, Section 2.2.