Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 1Ć240 minutes Lecture 25 minutes Practice 65 minutes Total Class Management Note: Files required for lesson are: Demonstrat
Trang 1Selecting Rows
1
Trang 2Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 1Ć2
40 minutes Lecture
25 minutes Practice
65 minutes Total
Class Management Note:
Files required for lesson are:
Demonstration: l1prec1.sql, l1prec2.sql, l1alias.sql, l1null1.sql
Practice: None
Trang 3Selecting Rows 1Ć3
In order to extract data from the database you need to use the Structured Query Language (SQL) SELECT command You may need to restrict the columns that are displayed This lesson explains all of the commands you will use to perform these actions.
You will want to create SELECT statements that can be used time and time again In this lesson you will also see how to save your statements for later use.
At the end of this lesson, you should be able to
D Write a SELECT statement to query the database
D Perform arithmetic calculations using SQL arithmetic operators
D Handle null values
D Specify alternative column headings using aliases
D Concatenate columns
D Edit SQL statements in the SQL*Plus buffer and create command files
Trang 4Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 1Ć4
Trang 5where: SELECT is a list of at least one column.
DISTINCT suppresses duplicates
* selects all columns
column selects the named column
alias gives selected columns a different heading
FROM table specifies the table containing the columns
Trang 6Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 1Ć6
Trang 7Selecting Rows 1Ć7
Writing SQL Commands
By following these simple rules and guidelines, you will be able to construct validstatements that are easy both to read and to edit
D SQL commands may be entered on one or many lines
D Clauses are usually placed on separate lines for readability and ease of editing
D Tabs and indents can be used to make code more readable
D Command words cannot be split across lines or abbreviated
D Keywords and commands typically are entered in uppercase; all other words,such as table names and columns, are entered in lowercase
D SQL commands are not case sensitive, unless indicated
D An SQL command is entered at the SQL prompt, and subsequent lines are
numbered This is called the SQL buffer.
D Only one statement can be current at any time within the buffer, and the
statement can be executed in a number of ways:
D Place a semicolon (;) at the end of last clause
D Place a semicolon or slash on the last line in the buffer
D Place a slash at the SQL prompt
D Issue a SQL*Plus RUN command at the SQL prompt
For more information, see
Oracle Applications: Coding Standards, Release 10G.
Trang 8Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 1Ć8
Simplest SELECT statement contains the following two clauses:
Trang 9Selecting Rows 1Ć9
In its simplest form, a SELECT statement must include the following:
D A SELECT clause, which specifies the columns to be displayed
D A FROM clause, which specifies the table containing the columns listed in the SELECT clause
Selecting All Columns and Rows
The asterisk (*) selects all columns from the table
Example
List all columns and all rows from the S_DEPT table
SQL> SELECT *
2 FROM s_dept;
ID NAME REGION_ID
- -
10 Finance 1
31 Sales 1
32 Sales 2
33 Sales 3
34 Sales 4
35 Sales 5
41 Operations 1
42 Operations 2
43 Operations 3
44 Operations 4
45 Operations 5
50 Administration 1
12 rows selected
Class Management Note:
Let the students know that the details of all the tables are given in Appendix B
Trang 10Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 1Ć10
Trang 11Selecting Rows 1Ć11
Selecting Specific Columns
You restrict the query to display only certain columns by specifying the column names, separated by commas, in the SELECT clause
Example
Display all department numbers, employee last names, and manager numbers in the S_EMP table
SQL> SELECT dept_id, last_name, manager_id
2 FROM s_emp;
DEPT_ID LAST_NAME MANAGER_ID
-
50 Velasquez 41 Ngao 1
31 Nagayama 1
10 Quick-To-See 1
50 Ropeburn 1
41 Urguhart 2
42 Menchu 2
43 Biri 2
44 Catchpole 2
25 rows selected
Specify the columns you want to see, in the order in which you want to see them, in the SELECT clause Do not forget to use the comma as a column name separator
Column Heading Defaults
Character and date column headings and data are left-justified within a column and numbers are right-justified Character and date column headings may be truncated, but number headings may not be truncated The column labels appear in uppercase by default You can override the column label display with an alias
Trang 12Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 1Ć12
Trang 13Selecting Rows 1Ć13
You may need to modify the way data is displayed, perform calculations, or look atwhat-if scenarios This is possible using arithmetic expressions
An arithmetic expression may contain column names, constant numeric values, and
the arithmetic operators
Arithmetic Operators
These are the arithmetic operators available in SQL You may use arithmetic
operators in any clause of a SQL statement except the FROM clause
Trang 14Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 1Ć14
Trang 15Class Management Note:
Let the students know that SQL*Plus ignores blank spaces before and afterthe arithmetic operator Formatting column values will be covered in laterlessons
Trang 16Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 1Ć16
Trang 17Selecting Rows 1Ć17
Operator Precedence
If an arithmetic expression contains more than one operator, multiplication and
division are evaluated first If operators within an expression are of the same priority,then evaluation is from left to right
Note: Use parentheses to reinforce the standard order of precedence and to improve
clarity For example, the expression above can be written as (12 * salary) +
100 with no change in the result
Trang 18Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 1Ć18
Class Management Note:
DEMO: l1prec1.sql, l1prec2.sql
PURPOSE: l1prec1.sql demonstrates the previous page’s example with no
parentheses Note the first couple rows of totals
Then, execute demo file l1prec2.sql, which demonstrates using the
parentheses to override the rules of precedence Note that the totals arelarger
Trang 19Selecting Rows 1Ć19
Override the rules of precedence with parentheses to specify the order in which
operators are executed
Example
Display the last name, salary, and annual compensation of employees Calculate the annual compensation as monthly salary plus a monthly bonus of $100, multiplied by 12
SQL> SELECT last_name, salary, 12 * (salary + 100)
2 FROM s_emp;
LAST_NAME SALARY 12*(SALARY+100)
- -
-Velasquez 2500 31200
Ngao 1450 18600
Nagayama 1400 18000
Quick-To-See 1450 18600
Ropeburn 1550 19800
Urguhart 1200 15600
Trang 20
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 1Ć20
Class Management Note:
DEMO: l1alias.sql.
PURPOSE: The column headings for each of the examples on the nextpage Demonstrate how to modify the file to demonstrate the other example
Trang 21Selecting Rows 1Ć21
When displaying the result of a query, SQL*Plus normally uses the selected column’sname as the heading In many cases, that heading may be difficult to understand oreven meaningless You can change a column’s heading by using a column alias.Specify the alias after the column in the SELECT list using a space as a separator Bydefault, alias headings will be forced to uppercase and cannot contain blank spaces,unless the alias is enclosed in double quotation marks (“ ”)
Example
Display the last name, salary, and annual compensation of employees Calculate theannual compensation as monthly salary plus a monthly bonus of $100, multiplied by
12 Name the column ANNUAL_SALARY
SQL> SELECT last_name, salary,
2 12 * (salary + 100) AS ANNUAL_SALARY
3 FROM s_emp;
Note: You can include the AS keyword before the alias name to comply with ANSI
SQL 92 standards
Column Aliases with Double Quotation Marks
If the alias contains spaces, special characters (such as # or $), or is case-sensitive,enclose the alias in double quotation marks (“ ”)
SQL> SELECT last_name, salary,
2 12 * (salary + 100) ”Annual Salary”
3 FROM s_emp;
Class Management Note:
Within a SQL statement, a column alias can be used in both the SELECTand the ORDER BY clauses You cannot use column aliases in the WHEREclause Both alias features comply with the ANSI SQL 92 standard Youcan use this method of achieving mixed case column headings for now In alater section, you can format headings using the SQL*Plus COLUMNcommand section
Trang 22Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 1Ć22
Trang 23Selecting Rows 1Ć23
You can link columns to other columns, arithmetic expressions, or constant values tocreate a character expression by using the concatenation operator (||) Columns oneither side of the operator are combined to make one single output column
Example
Display the full names of the employees with the heading Employees
SQL> SELECT first_name||last_name AS ”Employees”
The AS keyword before the alias name makes the SELECT clause easier to read
Class Management Note:
The resulting column is VARCHAR2 datatype
Trang 24Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 1Ć24
Trang 25Selecting Rows 1Ć25
A literal is any character, expression, or number included in the SELECT list that isnot a column name or a column alias It is printed for each row returned Literalstrings of free-format text can be included in the query result and are treated like acolumn in the SELECT list
Date and character literals must be enclosed within single quotation marks (‘ ’);
number literals must not
Example
Display the full names of the employees and their titles with the heading Employees
Be sure to add punctuation
SQL> SELECT first_name || ’ ’ || last_name
2 || ’, ’|| title ”Employees”
3 FROM s_emp;
Employees
-Carmen Velasquez, President
LaDoris Ngao, VP, Operations
Midori Nagayama, VP, Sales
Mark Quick-To-See, VP, Finance
Audry Ropeburn, VP, Administration
Molly Urguhart, Warehouse Manager
Class Management Note:
Point out to students that there is a blank space between single quotes in themiddle of first_name and last_name, in the select statement
Trang 26Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 1Ć26
Class Management Note:
Make sure everyone is aware of exactly what a null is
DEMO: l1null1.sql
PURPOSE: Demonstrates why sales representatives have values andeveryone else has a null No commission values exist for non-sales
representatives, therefore the calculation with null results in null
Currently, Oracle treats a character value with length of zero as null
However, this may not continue to be true in future versions of Oracle
Trang 27A null value is not the same as zero or a space Zero is a number, and a space is acharacter.
Columns of any datatype can contain null values, unless the column was defined asNOT NULL or as PRIMARY KEY when the table was created
Null Values in Arithmetic Expressions
If any column value in an expression is null, the result is null For example, if youattempt to perform division with zero, you will get an error However, if you divide
by null, the result is null
Example
Display the last name, salary, title, and calculated commission
SQL> SELECT last_name, title,
Havel Warehouse Manager
Magee Sales Representative 140
Giljum Sales Representative 186.25
Sedeghi Sales Representative 151.5
Nguyen Sales Representative 228.75
Dumas Sales Representative 253.75
Maduro Stock Clerk
For more information, see
Oracle7 Server SQL Reference, Release 7.3, “Elements of SQL.”
Trang 28Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 1Ć28
Trang 29expr2 is the target value for converting null.
Note: You can use the NVL function to convert any datatype, but the return value is
always the same as the datatype of expr1.
Example
To calculate values for all employees from the previous example, use the NVL
function to convert null values to zero
SQL> SELECT last_name, title,
2 salary * NVL(commission_pct,0)/100 COMM
3 FROM s_emp;
LAST_NAME TITLE COMM
-
-
Havel Warehouse Manager 0
Magee Sales Representative 186.25
Giljum Sales Representative 186.25
NVL Conversions for Various Datatypes
Datatype Conversion Example
NUMBER NVL(number_column,9)
DATE NVL(date_column,‘01-JAN-95’)
CHAR or VARCHAR2 NVL(character_column,‘Unavailable’)
Trang 30Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 1Ć30
1 At the prompt, enter: SELECT name FROM s_dept;
2 Show the students the duplicate rows in the output
3 At the prompt, enter: SELECT DISTINCT name FROM s_dept;
4 Now display the unique department names
Trang 31Selecting Rows 1Ć31
Unless you indicate otherwise, SQL*Plus displays the results of a query withouteliminating duplicate rows
Example Displaying All Rows
Display all department names in the S_DEPT table
The DISTINCT Keyword
To eliminate duplicate rows in the result, include the DISTINCT keyword in theSELECT clause immediately after the SELECT command word
Example Displaying Unique Rows
Display all unique department names in the S_DEPT table.
SQL> SELECT DISTINCT name
Trang 32Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 1Ć32
Trang 33Selecting Rows 1Ć33
DISTINCT with Multiple Columns
You can specify multiple columns after the DISTINCT qualifier The DISTINCTqualifier affects all selected columns
Example
Display all the different combinations of job titles and department numbers
SQL> SELECT DISTINCT dept_id, title
Trang 34Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 1Ć34
Trang 35Selecting Rows 1Ć35
In this lesson, you saw how SQL commands are executed within a product calledSQL*Plus SQL*Plus is a SQL and PL/SQL command execution environment withadditional features
You can use a number of SQL*Plus commands when writing even the most basic ofSQL statements This section covers some basic SQL*Plus commands to help you to
D Describe the table structure
D Edit SQL in the buffer
D Save files containing SQL for editing purposes
D Execute saved files
D Load SQL commands from a file into the SQL buffer
D Obtain online help
For more information, see
SQL*Plus User’s Guide and Reference, Release 3.3.
Trang 36Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 1Ć36
Trang 37Selecting Rows 1Ć37
How you invoke SQL*Plus depends upon which type of operating system or
windows environment you are running
Log In Through a Windows Environment
You double-click the SQL*Plus icon in the window manager, then enter the
username, password, and database, if required
Log In Through a Command Line Environment
Once you log on to your machine, at the operating system prompt enter the SQL*Pluscommand
sqlplus [username [/password [@database]]]
where: username is your database username
password is your database password If you enter your
password here, it is visible
@database is the database connect string
Note: To ensure the integrity of your password, do not enter it at the operating
system prompt Instead, only enter your username Enter your password at thePassword prompt
Once you are successfully logged in SQL*Plus, you see the following message:
SQL*Plus: Version 3.1.2 Production on Fri May 12th 15:31:32 1995 Copyright (c) Oracle Corporation 1979, 1992, All rights reserved SQL>