- Lab 2.1 The SQL Execution Environment
- Lab 2.2 The Anatomy of a SELECT Statement
- Lab 2.3 An Introduction to SQL*Plus
Lab 2.2 The Anatomy of a SELECT Statement
When you write a SQL query, it is usually to find an answer to 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 find answers to 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 or tables from which you want to display data. The FROM clause states on what table or tables this column or columns are found. Later, you will learn some of the other clauses that can be used in a SELECT statement.
How to Write a SQL Query
Before formulating the SELECT statement, you must first determine in which table the information is located. A study of the schema diagram for the STUDENT database reveals that the COURSE table provides descriptions related to courses. (You can also refer to Appendix E, "Table and Column Descriptions.")
The following SELECT statement provides a list of course descriptions. SQL does not require a new line for each clause, but using this formatting convention makes for easy readability.
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.
DESCRIPTION ------------------------- Technology Concepts Intro to Information Systems ... Java Developer III DB Programming with Java 30 rows selected.
Many of the result sets displayed throughout this book show both the SQL statement and the resulting data in a fixed-width font. At times, you may also find screenshots of the output in SQL Developer. However, typically the result is shown in a fixed-width font for easy readability.
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 ----------------------------- ---- Technology Concepts 1195 Intro to Information Systems 1195 ... Java Developer III 1195 DB Programming with 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 determines the order in which the columns are displayed in the output.
SELECTING ALL COLUMNS
You can select all columns in a table with the asterisk (*) wildcard character. This is handy because it means 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 click the Columns tab in SQL Developer or issue the DESCRIBE command.
SELECT * FROM course
Constructing the SQL Statement in SQL Developer
You can drag tables listed in the Connections navigator into the SQL Worksheet. When you do this, you construct a SELECT statement with all columns in the table. If desired, you can then edit the statement further. Figure 2.16 shows an example.
Figure 2.16 Result of dragging a table into the SQL Worksheet
The SQL Worksheet Icons
Figure 2.17 shows the SQL Worksheet toolbar. You are already familiar with the Execute Statement icon.
Figure 2.17 The SQL Worksheet icons toolbar
RUN SCRIPT
The Run Script icon allows you to execute multiple statements and emulates SQL*Plus as much as possible; the result is displayed in the Script Output tab instead of the Results tab.
COMMIT
The Commit icon looks like a database icon with the check mark. Any modifications to the data become permanent and visible to all users.
ROLLBACK
The Rollback icon looks like a database icon with an undo arrow. It undoes database changes, provided that they have not yet been committed. The COMMIT and ROLLBACK commands are discussed in Chapter 11.
CANCEL, EXECUTE EXPLAIN PLAN, AND AUTOTRACE
The Cancel icon stops a running statement that is currently executing. The Execute Explain Plan icon and the Autotrace icons are useful for optimizing SQL statements. You will learn about them in Chapter 18.
CLEAR
The eraser icon (Ctrl-D) at the end of the toolbar clears any statements in the SQL Worksheet.
Eliminating Duplicates with DISTINCT or UNIQUE
The use of the DISTINCT or UNIQUE keyword 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 instructor LAST_NAME ZIP ------------------------- ----- Hanks 10015 Wojick 10025 Schorin 10025 Pertez 10035 Morris 10015 Smythe 10025 Chow 10015 Lowry 10025 Frantzen 10005 Willig 10 rows selected.
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 in the table, you write the following SELECT statement. In this example, the last row shows the NULL value.
SELECT DISTINCT zip FROM instructor ZIP ----- 10005 10015 10025 10035 5 rows selected.
The output in SQL Developer shows the existence of the null much more obviously with a "(null)" display in the column (see Figure 2.18). Furthermore, the numbers to the left of the ZIP column display how many rows are returned.
Figure 2.18 Display of a null value in SQL Developer
From Chapter 1, "SQL and Data," you already know that a primary key is always unique or distinct. Therefore, the use of the DISTINCT or UNIQUE keyword 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 or null values.
Formatting a SQL Statement in SQL Developer
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 in SQL statements, which appear in 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 this book.
SYNTAX FORMATTING
SQL Developer provides many ways to help you achieve consistency. When you right-click within the SQL Worksheet, the menu shows a Refactoring, To Upper/Lower/Initcap menu option that lets you toggle between the different cases. The shortcut to remember is Ctrl-Quote. Another useful feature is the Format menu (Ctrl-F7); it automatically reformats your SQL statement to fit a given standard. You highlight the statement, right-click, and choose Format (see Figure 2.19) from the context menu.
Figure 2.19 Format feature
Figure 2.20 shows the result of this selection. The Oracle keywords are in uppercase and right aligned, and the name of the COURSE table is in lowercase.
Figure 2.20 Format results
The Tools, Preference, SQL Formatter menu option allows you to customize the formatting to your standards (see Figure 2.21).
Figure 2.21 Preferences window
CODE COMPLETION
Another useful feature of Oracle Developer is code completion, which helps you complete your SQL statements easily. When you pause on your statement, the program prompts you for appropriate commands, column names, or table names, which you can then select from the list. Figure 2.22 shows an example. When you remove the asterisk from the statement and enter a space, you see a list of possible choices. You can then choose the DESCRIPTION column and then enter a comma to get the list of relevant columns.
Figure 2.22 Code completion feature in SQL Developer
If you find the code completion feature confusing, you can turn it off by unchecking both of the Enable Auto-Popup check boxes in the Tools, Preference menu (see Figure 2.23).
Figure 2.23 Code Insight preferences
SYNTAX HIGHLIGHTING
SQL Developer offers syntax highlighting, which helps distinguish the SQL language keywords with a different color. This way, you can easily identify and distinguish between the SQL language commands and any table or column names. The column and table names appear in black; SQL language commands appear in blue. This color-coding improves the readability of a statement and helps you spot syntax errors easily.
Notice that the COST column in Figure 2.24 is not colored black. Even though this is the name of the column in the table, COST also happens to be an Oracle keyword.
Figure 2.24 Syntax highlighting
Writing Multiple Statements in the SQL Worksheet
You can enter multiple statements in the SQL Worksheet and execute them individually by placing the cursor on the line of the statement (see Figure 2.25). You need to end each SQL statement with a semicolon (;) or type a forward slash (/) on a new line; otherwise, SQL Developer displays an error.
Figure 2.25 Executing multiple SQL statements in SQL Developer
If you want to run both statements at once, you need to run the statements as a script by clicking the Run Script icon (F5). The output is then displayed in the Script Output tab in a matter much like the SQL*Plus command-line version.
SQL Developer's Statement History
SQL Developer keeps track of your most recently executed commands in the SQL History window (see Figure 2.26) below the Results pane. If the SQL History tab is not visible, you can click View, SQL History or press F8. The SQL commands are saved even after you exit SQL Developer.
Figure 2.26 SQL History window
To place a command from the History window back into the SQL Worksheet, you can simply double-click the statement. If you choose the up/down arrows icon on the left, the statement is appended to any existing statements in the SQL Worksheet window. The left/right arrows icon replaces any existing SQL statement(s) in the Worksheet.
You are able to search for text within the historical SQL statements by entering the information in the box and clicking the Filter button on the right. The eraser icon clears all the statements from the SQL history. If you do not choose a statement, you can exit the SQL History window by pressing the Esc key.
Lab 2.2 Exercises
-
Write a SELECT statement that lists the first and last names of all students.
-
Write a SELECT statement that lists all cities, states, and zip codes.
-
Why are the results of the following two SQL statements the same?
SELECT letter_grade FROM grade_conversion SELECT UNIQUE letter_grade FROM grade_conversion
-
Explain what happens, and why, when you execute the following SQL statement.
SELECT DISTINCT course_no FROM class
-
Execute the following SQL statement. Then, in the Results window, right-click and choose the menu option Single Record View. Describe your observation.
SELECT * FROM student
Lab 2.2 Exercise Answers
-
Write a SELECT statement that lists 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. You can examine the rows by scrolling up and down. The rows are not returned in any particular order; you will learn about ordering the result set in Chapter 3, "The WHERE and ORDER BY Clauses."
SELECT first_name, last_name FROM student FIRST_NAME LAST_NAME ------------------------- ---------- George Eakheit Leonard Millstein ... Kathleen Mastandora Angela Torres 268 rows selected.
-
Write a SELECT statement that list all cities, states, and zip codes.
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.
-
Why are the results of the following two SQL statements the same?
SELECT letter_grade FROM grade_conversion SELECT UNIQUE letter_grade FROM grade_conversion
ANSWER: The result sets are the same because the data values in the LETTER_GRADE column of the GRADE_CONVERSION table are not repeated; the LETTER_GRADE column is the primary key of the table, so by definition its values are unique. The UNIQUE and DISTINCT keywords can be used interchangeably.
-
Explain what happens, and why, when you execute the following SQL statement.
SELECT DISTINCT course_no FROM class
ANSWER: Oracle returns an error because a table named CLASS does not exist.
The error message indicates the error in the query. In SQL Developer, you see a message box similar to Figure 2.27, which indicates the line and column number where the error occurs.
Figure 2.27 Error message in SQL Developer
You can review your cursor's exact position by referring to the bottom of the screen (see Figure 2.28).
Figure 2.28 Line and column indicator
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 the database returns to you so you can learn from and correct your mistakes. For example, the Oracle error message in Figure 2.27 informs you that you referenced a nonexistent table or view within the database schema. (Views are discussed in Chapter 13. You can correct your SQL statement and execute it again.
-
Execute the following SQL statement. Then, in the Results window, right-click and choose the menu option Single Record View. Describe your observation.
SELECT * FROM student
ANSWER: The Single Record View window allows you to examine one record at a time and scroll through the records using the arrows at the top (see Figure 2.29). If there are many columns in a table, you can expand the window by dragging its sides.
Figure 2.29 Single Record View window
As you can see, there are many menu options available when you right-click the Results window. The Auto-fit menu options (see Figure 2.30) are very useful for formatting the Results window according to the length of the data cells or the length of the column name.
Figure 2.30 The Results window menu options
The Count Rows menu option returns the number of rows in the table. Not all the rows may be displayed at a given time in SQL Developer, as indicated in the Fetched Rows message on the status bar (see Figure 2.31). SQL Developer fetches additional rows, as needed, when you scroll down.
Figure 2.31 Row Count and Fetched Rows comparison
Lab 2.2 Quiz
In order to test your progress, you should be able to answer the following questions.
-
The SELECT clause specifies the columns you want to display, and the FROM clause specifies the table that contains these columns.
_______
a) True
_______
b) False
-
The column names listed in the SELECT list must be separated by commas.
_______
a) True
_______
b) False
-
The asterisk can be used as a wildcard in the FROM clause.
_______
a) True
_______
b) False
-
The following statement contains an error:
SELECT courseno FROM course
_______
a) True
_______
b) False
-
The Cancel icon stops a long-running SQL statement.
_______
a) True
_______
b) False
-
The Ctrl-Quote keystroke allows you to toggle the case of text entered in the SQL Worksheet.
_______
a) True
_______
b) False
-
Syntax highlighting in SQL Developer helps you distinguish between Oracle keywords and table/column names.
_______
a) True
_______
b) False
-
All SQL commands must be entered in uppercase only.
_______
a) True
_______
b) False
-
When you click on the Execute Statement icon, the output always displays in the Results tab.
_______
a) True
_______
b) False
ANSWERS APPEAR IN APPENDIX A.