The SELECT Statement In this chapter: How do you write a basic query using SELECT statements?. We also briefly discuss different types ofqueries, finally examining specific aspects of q
Trang 1safety can be transferred to a standby as they are created using the LogWriter (LGWR), filling a precreated archive log file on the standby data-base On the other hand, maximum performance can be achieved at theexpense of safety, thus potentially presenting possible data loss using the
Archiver (ARCn) to transfer log entries from primary to standby In this
case, redo log entries are transferred when a primary database log switchoccurs, copying each archive log file to a standby database as it is created.Using the Archiver, redo log entries are not copied as they are created butonly after primary database archiving
Physical standby has disadvantages A physical standby can only beaccessed externally in read-only mode, and it must duplicate the source(primary) database exactly A logical standby database is maintained inread-write mode, a completely open and accessible database Also, a logicalstandby can have a subset of source database objects and can even containobjects in addition to the primary database Once again, logical standby ismuch more flexible than physical standby
Clustering was previously called Oracle Parallel Server and is now calledOracle Real Application Clusters (RAC) Oracle RAC allows for sharing of
Figure 3.12
Oracle Standby/
Fail-over Database
Architecture.
Trang 23.5 Enhancing the Physical Architecture 71
So far, this book has examined the underlying logical and physical ture of Oracle Database plus new features available in both Oracle Database
struc-10g and Oracle Database 9i Now it’s time to begin looking into Oracle
SQL itself The next chapter begins this process by examining the SELECTstatement
Trang 4The SELECT Statement
In this chapter:
How do you write a basic query using SELECT statements?
What types of SELECT statements are possible?
What else is interesting about SELECT statements?
In this chapter, we dive right into the syntax and use of the SELECTstatement to query the database We also briefly discuss different types ofqueries, finally examining specific aspects of queries such as using DIS-TINCT and the DUAL table So let’s begin with the basics of the SELECTstatement and some simple examples just to get into the swing of things
SELECT is the beginning of the SQL command for querying (retrieving)data from a database table, view, or object Objects are similar to tables, butthey have a more complex structure
The SELECT statement is a specialized way to ask a question about thedata in a database Thus a SELECT statement is also called a querybecause it quite literally “queries” or asks questions of a database Thereare several uses for the SELECT statement that give you great flexibility
in the database:
Simple query A SELECT statement can be used alone to retrievedata from a table or a group of related tables You can retrieve all col-Chap4.fm Page 73 Thursday, July 29, 2004 10:03 PM
Trang 574 4.1 The Basic SELECT Statement
umns or specify some columns You can retrieve all rows or specifywhich rows you want
Complex query A SELECT statement can be embedded withinanother SELECT statement This lets you write a query within aquery The possibilities are endless Later chapters cover the details
Create a view or table A SELECT statement can be used to create aview or a new table A view is a stored query that is executed when-ever another SELECT statement retrieves data from the view byusing the view in a query Views are very useful to enforce security bylimiting the columns or rows that particular users are allowed to see
Insert, update, or delete data A SELECT statement can be usedwithin the INSERT, UPDATE, or DELETE statements to addgreater flexibility to these commands Chapter 15 examines com-mands for manipulating data
Note: There are numerous other more detailed types of queries using theSELECT statement to be described briefly later in this chapter and in detail
in later chapters
In this section, and throughout the rest of the book, you will see SQL andSQL*Plus commands listed first with their syntax and then with manyexamples, some of which you could type yourself to help you better under-stand the commands
The syntax of a command defines the set of rules governing the correctform of a command Some parts are required and never change, others areoptional, and others vary with each different statement Figure 4.1 showsthe syntax of the basic SELECT statement with descriptions of the vari-ous parts
Here is the basic syntax of the SELECT statement in a textual form(Backus-Naur Form), as shown in Figure 4.1 See Chapter 1 for details ofBackus-Naur syntax formatting
Trang 64.1 The Basic SELECT Statement 75
Curly braces mean you must choose from one of the choices betweenthem So, you can either write a list of column names, or write an expres-sion, or use * An asterisk (*) represents all column names within a querywhen used in the SELECT statement
Square brackets mean you can include the items within the square ets or leave them out entirely In the SELECT command, you can list justone column or many columns, or even simply an asterisk (*) if you choose.The lowercase words are always replaced with actual names of tables,columns, schemas, and so on The words in the syntax give you a hint onwhat should be used This structure is just the bare bones of the SELECTcommand Other chapters cover all of the many variations and optionsavailable for the SELECT command
brack-The complete syntax definition of the SELECT command in Oracle’sSQL documentation takes up five pages The description of all the variables
in the command takes up another 25 pages In this book, you will buildgradually on your knowledge, chapter by chapter, until you have enoughknowledge of the SELECT command to write complex queries easily
Note: Details of Backus-Naur syntax conventions can be found in Chapter 1.This book almost always follows a slight variation on that theme, described inChapter 1 Any variations are generally specific to particular chapters andnoted at the beginning of those chapters
Let’s look at a few examples
Figure 4.1
The Syntax of the
SELECT Statement.
Chap4.fm Page 75 Thursday, July 29, 2004 10:03 PM
Trang 776 4.1 The Basic SELECT Statement
The first example retrieves rows from an Oracle metadata view:
SELECT VIEW_NAME, TEXT FROM USER_VIEWS;
This statement has a list of two columns (VIEW_NAME and TEXT),and the view queried is named USER_VIEWS Tables and views are inter-changeable in the SELECT command No schema name is used becausethe view in this case belongs to the user who is running the query As a gen-eral rule, any time you query a table or view that belongs to the user you log
in as, no schema name is required Likewise, when you query a table orview that is in another user’s schema, you must use the schema name Forexample, if you log in as JOE and you want to query a table name CARSowned by SAM, you would have to add the schema name CARS
SELECT * FROM SAM.CARS;
Note: The semicolon is technically not considered part of the SQL ment’s syntax The semicolon marks the end of the statement and submis-sion A forward slash on a blank line following the SQL statement servesthe same purpose Submission means submission to the SQL engine, inother words “execute it!”
state-Now let’s do some simple SELECT statement examples using theMUSIC schema
Note: Diagrams and scripts for the MUSIC schema are in Chapter 1 andAppendix A
Let’s begin with a query listing all the data in the MUSICCD table:SELECT * FROM MUSICCD;
Figure 4.2 shows the result Notice the blank spaces in certain columns
Trang 84.1 The Basic SELECT Statement 77
To select specific columns, the asterisk could be changed to somethinglike PRESSED_DATE, TITLE, MUSICCD_ID, listing columns in thesequence specified
SELECT PRESSED_DATE, TITLE, MUSICCD_ID FROM MUSICCD;
The next query contains a calculation between two columns You canadd, subtract, multiply, divide, and use parentheses to affect the calculationorder of factors in expressions When you combine columns, include calcu-lations, or other operations, an expression is created Expressions can beused in a SELECT statement anywhere you use a column
SELECT ARTIST_ID, SESSION_DATE, AMOUNT_CHARGED-AMOUNT_PAID FROM STUDIOTIME;
Observe that the column heading of the third column isAMOUNT_CHARGED - AMOUNT_PAID This is long, and if you
Trang 978 4.1 The Basic SELECT Statement
were handing a report off to someone else, you might want a more tive heading To change the heading, add a column alias to the SELECTstatement A column alias redefines a column’s heading in a SELECT state-ment In this example, we change the second line by adding the alias “Bal-ance Due.”
descrip-AMOUNT_CHARGED-AMOUNT_PAID "Balance Due"
Using double quotes preserves the upper and lowercase appearance ofthe heading Without double quotes, your alias will always appear in upper-case letters in the report Additionally, in this case because the words “Bal-ance” and “Due” are separated by a space, “Due” will be interpreted as acolumn name, causing an error Figure 4.3 shows the output
Now add aliases to all three columns and change the SELECT statementagain:
SELECT ARTIST_ID Artist, SESSION_DATE "In Studio"
, AMOUNT_CHARGED-AMOUNT_PAID "Balance Due"
Trang 104.1 The Basic SELECT Statement 79
Figure 4.4 shows the result Headings have changed Because theARTIST_ID alias Artist is not in double quotes, the heading is displayed asuppercase even though it was typed in mixed case
Now add an alias to the table name Although this action does not affectyour report, it will be useful in the future when you create more complexqueries A table alias is a shortcut name that is used as a substitute for thetable name in the SELECT statement The table alias is best being shortand simple, but it does not have to be
Note: I was once hired for a contract because I used single characters andnot table names for table aliases Why? Using table names to reference col-umns can make quite a mess of SQL statements Using single-characteraliases makes for much more readable, ultimately debuggable and tunableSQL code
The table alias should be added to all of the table’s columns (not columnaliases) in the SELECT statement This is a good habit to adopt becauseyou will be able to create more readable SQL when using table aliases.Many of the examples in this book use table aliases In this case, the letter S
is used for the table alias:
Figure 4.4
Three Column Aliases, with and
without Double Quotes.
Chap4.fm Page 79 Thursday, July 29, 2004 10:03 PM
Trang 1180 4.1 The Basic SELECT Statement
SELECT S.ARTIST_ID Artist, S.SESSION_DATE "In Studio"
, S.AMOUNT_CHARGED - S.AMOUNT_PAID "Balance Due"
FROM STUDIOTIME S;
You could even add a schema name and a table alias to the table name in
a SELECT command For example, you are logged on as FRED and wish
to query the LONGBOAT table in ANGELA’s schema:
SELECT BOAT.BOAT_NAME, BOAT.DATE_CHRISTENED FROM ANGELA.LONGBOAT BOAT;
Here are a few more tips on writing good queries:
Use parentheses in either the SELECT or the WHERE clause to trol the order of evaluation of expressions Expressions within paren-theses are evaluated first For example:
con-SELECT (TOTAL_MORTGAGE-(MONTHLY_PMT * MONTHS_PAID))/36Evaluates differently to:
SELECT (TOTAL_MORTGAGE-(MONTHLY_PMT * MONTHS_PAID)/36)
Upper and lowercase make no difference so long as they are not inquotation marks For example, these three statements are identical asfar as Oracle Database 10g is concerned:
SELECT Name, Street, City from artist;
Select name, street, city from ARTIST;
SelEct nAmE, strEet, CITy From aRTist;
When enclosed in quotation marks (single or double), then upperand lowercase are considered different For example, these two state-ments are different:
SELECT * from artist where name like ('%C%');
SELECT * from artist where name like ('%c%');
Oracle Database 10g ignores line breaks and spacing in SQL mands For example, the following two SELECT statements are iden-tical when submitted in SQL*Plus, even though spacing and line
Trang 12com-4.2 Types of SELECT Queries 81
, City FROM artist;
SELECT Name , Street , City FROM artist ;
That’s enough simple examples for now Subsequent chapters examine amultitude of variations and adaptations for SELECT statements Next weexamine the different types of SELECT statements you can use
Different types of SELECT statement queries are as follows:
Simple queries simply retrieve rows, as we have already seen earlier inthis chapter
Filtered queries return a subset of rows using the WHERE clause tofilter out unwanted rows
Sorted queries use the ORDER BY clause to return rows in a fied order based on column values returned
speci- Grouping or aggregated queries create groupings or summaries oflarger row sets
Join queries merge rows from more than one table, usually based onmatching column values between tables
Subqueries are queries executed within other queries: a SELECTstatement executed within another calling SELECT statement
Queries for table and view creation generate new tables and viewsfrom the results of a SELECT statement
Hierarchical queries build tree-like hierarchical output row structuresfrom hierarchical data
Set operators and composite queries use special operators to nate results of different queries together
concate- Flashback or versions queries allow access to data at a previous point
Trang 13SELECT ARTIST_ID, NAME FROM ARTIST WHERE NAME LIKE '%a%';
Note: The percentage character (%) is used as a wild card character
repre-senting zero or more characters Oracle SQL wild card characters used withthe LIKE clause are explained in Chapter 5 under the heading “WHEREClause Expression Conditions.”
Figure 4.5
A Simple Query.
Trang 144.2 Types of SELECT Queries 83
Now let’s sort Figure 4.5 shows artists listed by their ARTIST_ID Theorder in Figure 4.5 is not because of a unique key but because that is theorder in which rows were inserted Without an ORDER BY clause, thesorted order of a query depends on columns selected and other criteria such
as the WHERE clause Using the ORDER BY clause, Figure 4.7 shows ists re-sorted in the order of their names (the NAME column values) Now,the numbers in the ARTIST_ID column appear out of order
art-SELECT ARTIST_ID, NAME FROM ARTIST ORDER BY NAME;
Now let’s do a grouping The COUNT function in this example causes anaggregate or group on the COUNTRY column The results are displayed inFigure 4.8 summary rows: one for each unique value found in the COUN-TRY column
SELECT COUNT(COUNTRY), COUNTRY FROM ARTIST GROUP BY COUNTRY; Figure 4.6
A filtered query.
Trang 154.2.5 Join Query
The next query creates a join between the ARTIST and SONG tables Ajoin does not simply retrieve all rows from multiple tables but can matchcolumns across tables The result is shown in Figure 4.9, where 93 rowsretrieved by the join is equal to the total number of songs in the SONGStable The natural join joins the two tables on a column name or column
Trang 164.2 Types of SELECT Queries 85
name sequence present in both tables In this case, the natural join nected the two tables by matching values in the ARTIST_ID column found
(SELECT ARTIST_ID FROM ARTIST);
We can create a new table using the join query from Figure 4.9 Selectingthe data from the new view would produce the same result as the query inFigure 4.9:
CREATE VIEW SONGS AS SELECT NAME, TITLE FROM ARTIST NATURAL JOIN SONG;
Figure 4.9
A Join Query.
Trang 174.2.8 Hierarchical Query
Typically, hierarchical queries are used to retrieve data hierarchies placedinto a single table A common modern-day use for hierarchies is data that isobviously hierarchical in nature Hierarchical data has parent rows contain-ing closely related sibling rows, such as a family tree In our case we can usethe INSTRUMENT table in our MUSIC schema Figure 4.11 shows asmall section of this hierarchy
This query will read a small section of the hierarchy including and tained within the Guitar node as shown in Figure 4.11 The result is shown
Hierarchy.
Trang 184.2 Types of SELECT Queries 87
We can improve on the query result from Figure 4.12 by altering itaccordingly, showing the result in Figure 4.13
SELECT LEVEL , (SELECT NAME FROM INSTRUMENT WHERE INSTRUMENT_ID = I.SECTION_ID) "Section"
, I.NAME AS Instrument
Figure 4.12
A Hierarchical Query.
Figure 4.13
A Meaningful Hierarchical Query.
Trang 19START WITH I.NAME = 'Guitar' CONNECT BY PRIOR I.INSTRUMENT_ID = I.SECTION_ID ORDER BY 1,2;
Composite queries use what are called set operators (UNION [ALL],INTERSECT, MINUS) to concatenate (add together) the results of multi-ple queries Composite queries are not the same as joins The followingquery would simply concatenate the results of the two queries as aUNION The result would include all rows from both queries together inthe result regardless of any relationship between the two tables
SELECT NAME, ARTIST_ID FROM ARTIST UNION
SELECT TITLE, SONG_ID FROM SONG;
Now that we have examined query types, let’s look at some specialaspects of queries
Various other aspects of SELECT statements are important to remember:
The DUAL table is a dummy or temporary table used to executenon-SQL-type commands with the SQL command interpreter
Using functions allows use of a large amount of built-in (provided)functionality or even custom-written functions
Arithmetic is allowed in SQL using standard arithmetic operators
The DISTINCT function allows retrieval of unique values from arow set containing duplicate values
Null values represent nothing A space character and the value 0 arenot the same as NULL A null value is never an unknown value but issimply a value that has never been set
Trang 204.3 Other Aspects of the SELECT Statement 89
Top-N queries allow restricting the number of rows to be returnedfrom a row set by using the ROWNUM pseudocolumn in theWHERE clause
Parallel queries are special queries designed to run faster in paralleland are best executed on dual-CPU platforms, particularly with Ora-cle Partitioning
All DML statements create implicit cursors Cursors are memory chunksallocated for results of SQL statements SELECT statements require asource for an implicit cursor to operate on Some types of SELECT state-ments do not retrieve from any specific table The DUAL table is a reposi-tory for an expression result applied to a single value, acting as a temporaryrepository for expression results, selected from the DUAL table
The DUAL table can only be queried, never updated The DUAL table
is owned by SYS but can be queried by any user DUAL is useful when youwant to retrieve a constant or define a variable
SELECT * FROM DUAL;
As you can see in Figure 4.14, the DUAL table contains a single umn, a single row, and the value X in that single column The column’s
col-Figure 4.14
The DUAL Table
Is Available for Special Use.
Trang 21name is DUMMY, and it is a VARCHAR2(1) datatype This does notseem like it helps much However, the DUAL table can be used to viewconstant values, such as the USER and SYSDATE values Because itreturns one row, you only see these values once rather than many times(once for each row returned).
We could modify the previous query as follows The result is shown inFigure 4.15
SELECT USER, UID, ROWNUM, ROWID FROM DUAL;
Some other interesting examples are as follows, where the first joins theresults from the DUAL table to a MUSIC schema table and the second out-puts a string:
SELECT d.*, a.* FROM DUAL d, ARTIST a;
SELECT 'Hello World!' FROM DUAL;
The DUAL table is primarily used to retrieve values in a SELECT ment, where a value is retrieved such as in the following examples:
state-SELECT SYSDATE FROM DUAL;
SELECT USER FROM DUAL;
Trang 224.3 Other Aspects of the SELECT Statement 91
groups There will be much more on using functions in later chapters, marily in Chapter 9 and Chapter 11
pri- Single-row functions operate on one row at a time
Datatype conversion functions convert values such as numbers tostrings
Group functions apply specific functionality to grouping and mary queries
sum- Object reference functions reference data across objects
User-defined functions are custom-written functions for specific tasksnot available in the functions that the Oracle Database provides
An example function would be the use of the SUBSTR and INSTRfunction in the following example, retrieving the first word of each artist’sname
SELECT SUBSTR(NAME,1,INSTR(NAME,' ')) FROM ARTIST;
Let’s use SYSDATE to calculate the time between a date stored in the base and today’s date The following query determines the number of daysbetween the due date and today Figure 4.16 shows the result
data-SELECT AMOUNT_CHARGED - AMOUNT_PAID BALANCE, DUE_DATE , SYSDATE, SYSDATE - DUE_DATE DAYS_LATE
FROM STUDIOTIME WHERE AMOUNT_CHARGED > AMOUNT_PAID;
In Figure 4.16, there are two subtraction expressions in the SELECTclause:
Subtracting two numbers (the AMOUNT_CHARGED and theAMOUNT_PAID)
Subtracting two dates (the SYSDATE and the DUE_DATE) When
you subtract dates, Oracle Database 10g will calculate the number of
days between the two dates Dates are stored internally as Julian datesand automatically converted with the default data display A Juliandate is a number in seconds from a specified date, such as January 1,
Trang 231970 The fractions you see in the results are the fraction of a day
between the times in each date Oracle Database 10g DATE
datatypes contain both a date and a time
DISTINCT will retrieve the first value of each group in multiple groupscontaining duplicates DISTINCT can operate on a single or multiple col-umns General syntax for DISTINCT is as follows
SELECT DISTINCT column [, column ]
SELECT DISTINCT (column [, column ])
SELECT [ DISTINCT | ALL ] expression
Let’s look at some examples using DISTINCT Figure 4.17 shows theoutput for the first of the three example syntax options using DISTINCT.SELECT DISTINCT COUNTRY FROM ARTIST;
Figure 4.16
Date Arithmetic
Made Easy.
Trang 244.3 Other Aspects of the SELECT Statement 93
SELECT DISTINCT STATE_PROVINCE, COUNTRY FROM ARTIST;
The parentheses require a single concatenated string Other functionscould be used within the parentheses, so long as a single string or value isproduced
SELECT DISTINCT (STATE_PROVINCE||COUNTRY) FROM ARTIST;
SELECT ALL as opposed to SELECT DISTINCT is the default for theSELECT statement and is therefore seldom used SELECT ALL simplylists all values, repeating or not, as opposed to only unique values
Some facts about null values are important to remember:
NULL represents nothing, not a space, not a zero (0), or even anunknown value
A space character or a 0 value are not NULL
Null values are not included in binary tree (BTree) indexes
Figure 4.17
Using DISTINCT.
Trang 25NULL can be tested for using the IS [ NOT ] NULL conditionaloperator.
An expression containing a null value always returns a null value
The NVL (value, replace) function replaces null values in expressions,avoiding SQL errors The SET NULL environment variable does thesame thing in SQL*Plus
Null values sort as the highest value by default
One or two simple examples will suffice with respect to the SELECT ment For example, the following query finds the ROWID (logical rowpointer) and ROWNUM (returned row number in current query) for eachrow in the query The result is shown in Figure 4.18
state-SELECT ROWNUM, NAME, ROWID FROM ARTIST;
Figure 4.18
Using Pseudocolumns.