Home > Articles > Data > SQL

Oracle SQL: The Basics

This chapter is from the book

This chapter is from the book

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

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

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

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

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

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

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

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

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

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

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

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

  1. Write a SELECT statement that lists the first and last names of all students.

  2. Write a SELECT statement that lists all cities, states, and zip codes.

  3. 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
    
  4. Explain what happens, and why, when you execute the following SQL statement.

    SELECT DISTINCT course_no
      FROM class
    
  5. 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

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

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

    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

    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.

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

    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

    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

    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.

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

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

    _______

    a) True

    _______

    b) False

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

    _______

    a) True

    _______

    b) False

  4. The following statement contains an error:

    SELECT courseno
      FROM course
    

    _______

    a) True

    _______

    b) False

  5. The Cancel icon stops a long-running SQL statement.

    _______

    a) True

    _______

    b) False

  6. The Ctrl-Quote keystroke allows you to toggle the case of text entered in the SQL Worksheet.

    _______

    a) True

    _______

    b) False

  7. Syntax highlighting in SQL Developer helps you distinguish between Oracle keywords and table/column names.

    _______

    a) True

    _______

    b) False

  8. All SQL commands must be entered in uppercase only.

    _______

    a) True

    _______

    b) False

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

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