Home > Articles

This chapter is from the book

This chapter is from the book

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.11Figure 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 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.

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 client–server 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

  1. Write a SELECT statement to list the first and last names of all students.

  2. Write a SELECT statement to list all cities, states, and zip codes.

  3. Describe the result set of the following SQL statement:

  4. SELECT *
     FROM grade_type

2.2.2 Use DISTINCT in a SQL Statement

  1. Why are the result sets of each of the following SQL statements the same?

  2. SELECT letter_grade
     FROM grade_conversion
    
    
    SELECT DISTINCT letter_grade
     FROM grade_conversion
  3. Explain the result set of the following SQL statement:

  4. SELECT DISTINCT cost
     FROM course
  5. Explain what happens, and why, when you execute the following SQL statement:

  6. SELECT DISTINCT course_no
     FROM class

Lab 2.2 Exercise Answers

2.2.1 Answers

  1. Write a SELECT statement to list the first and last names of all students.

  2. 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.

  1. Write a SELECT statement to list all cities, states, and zip codes.

  2. 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.
  3. Describe the result set of the following SQL statement:

  4. 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.12Figure 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.13Figure 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 course
  

COST ---------- $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

  1. 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.

  2. Explain the result set of the following SQL statement:

  3. 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 course
    

    COST ----------- 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.

  4. Explain what happens, and why, when you execute the following SQL statement:

  5. 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.

  1. The column names listed in the SELECT list must be separated by commas.

    1. True

    2. False

  2. A SELECT list may contain all the columns in a table.

    1. True

    2. False

  3. The asterisk may be used as a wildcard in the FROM clause.

    1. True

    2. False

  4. The following statement contains an error:
  5.  FROM course
    1. True

    2. False

Answers appear in Appendix A, Section 2.2.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020