Вы находитесь на странице: 1из 11

Oracle9i Features expect an enterprise database to manage.

It can also
Oracle offers a comprehensive high-performance be unstructured data like:
infrastructure for e-business. It is called Oracle9i.  Spreadsheets
Oracle9i includes everything needed to develop,  Word documents
deploy, and manage Internet applications.  PowerPoint presentations
 XML
Benefits include:  Multimedia data types like MP3, graphics,
 Scalability from departments to enterprise e- video, and more
business sites
 Robust, reliable, available, secure About the Oracle Server
architecture The Oracle9i server supports both the relational and
 One development model, easy deployment object relation models.
options The Oracle server extends the data modeling
 Leverage an organization’s current skillset capabilities to support an object relational database
throughout the Oracle platform (including model that brings object-oriented programming,
SQL, PL/SQL, Java, and XML) complex data types, complex business objects, and full
 One management interface for all compatibility with the relational world.
applications It includes several features for improved performance
 Industry standard technologies, no and functionality of online transaction processing
proprietary lock-in (OLTP) applications, such as better sharing of run-time
data structures, larger buffer caches, and deferrable
Oracle9i constraints.
There are two products, Oracle9i Application Server
and Oracle9i Database, that provide a complete and Data warehouse applications will benefit from
simple infrastructure for Internet applications. enhancements such as parallel execution of insert,
update, and delete operations; partitioning; and
1. Oracle9i Application Server parallel-aware query optimization.
The Oracle9i Application Server (Oracle9iAS) runs all
your applications. Operating within the Network Computing
Architecture (NCA) framework, Oracle9i supports
2. The Oracle9i Database stores all your data. client-server and Web-based applications that are
distributed and multitiered.
Oracle9i Application Server is the only application Oracle9i can scale tens of thousands of concurrent
server to include services for all the different server users, support up to 512 petabytes of data (a petabyte
applications you will want to run. is 1,000 terabytes), and can handle any type of data,
including text, spatial, image, sound, video, and time
Oracle9iAS can run your: series as well as traditional structured data.
 Portals or Web sites For more information, see Oracle9i Concepts.
 Java transactional applications Oracle Internet Platform
 Business intelligence applications it also
provides integration between users, Oracle offers a comprehensive high-performance
applications, and data throughout your Internet platform for e-commerce and data
organization. warehousing. This integrated platform includes
everything needed to develop, deploy, and manage
Oracle9i Database Internet applications.
The roles of the two products are very
straightforward. Oracle9i Database manages all your The Oracle Internet Platform is built on three core
data. This is not just the object relational data that you pieces:
 Browser-based clients to process Refine the prototype. Move an application into
presentation production with user acceptance testing, conversion
 Application servers to execute business logic of existing data, and parallel operations. Make any
and serve presentation logic to browser- modifications required.
based clients
 Databases to execute database-intensive 5. Production
business logic and serve data Roll out the system to the users. Operate the
production system. Monitor its performance, and
Oracle offers a wide variety of the most advanced enhance and refine the system.
graphical user interface (GUI) driven development Note: The various phases of the system development
tools to build business applications, as well as a large life cycle can be carried out iteratively. This course
suite of software applications for many areas of focuses on the build phase of the system development
business and industry. Stored procedures, functions, life cycle.
and packages can be written by using SQL, PL/SQL, or
Java. Storing Information
Every organization has some information needs. A
System Development Life Cycle library keeps a list of members, books, due dates, and
From concept to production, you can develop a fines. A company needs to save information about
database by using the system development life cycle, employees, departments, and salaries. These pieces of
which contains multiple stages of development. This information are called data.
top-down, systematic approach to database
development transforms business information Organizations can store data on various media and in
requirements into an operational database. different formats, such as a hard-copy document in a
filing cabinet or data stored in electronic spreadsheets
1. Strategy and Analysis or in databases.
Study and analyze the business requirements.
Interview users and managers to identify the A database is an organized collection of information.
information requirements. Incorporate the enterprise
and application mission statements as well as any To manage databases, you need database
future system specifications. management systems (DBMS).
Build models of the system. Transfer the business A DBMS is a program that stores, retrieves, and
narrative into a graphical representation of business modifies data in the database on request.
information needs and rules. Confirm and refine the
model with the analysts and experts. There are four main types of databases:
 hierarchical,
2. Design  network,
Design the database based on the model developed in  relational, and more recently
the strategy and analysis phase.  object relational.

3. Build and Document Relational Model


Build the prototype system. Write and execute the The principles of the relational model were first
commands to create the tables and supporting objects outlined by Dr. E. F. Codd in a June 1970 paper called
for the database. “A Relational Model of Data for Large Shared Data
Develop user documentation, Help text, and Banks.” In this paper, Dr. Codd proposed the relational
operations manuals to support the use and operation model for database systems.
of the system.
The more popular models used at that time were
4. Transition hierarchical and network, or even simple flat file data
structures. Relational database management systems
(RDBMS) soon became very popular, especially for  Provides a clear picture of the scope of the
their ease of use and flexibility in structure. In information requirement
addition, a number of innovative vendors, such as  Provides an easily understood pictorial map
Oracle, supplemented the RDBMS with a suite of for the database design
powerful application development and user products,  Offers an effective framework for integrating
providing a total solution. multiple applications

Components of the Relational Model Key Components


Collections of objects or relations that store the data. Entity: A thing of significance about which information
A set of operators that can act on the relations to needs to be known.
produce other relations
Data integrity for accuracy and consistency Attribute: Something that describes or qualifies an
For more information, see E. F. Codd, The Relational entity.
Model for Database Management Version 2 (Reading,
Mass.: Addison-Wesley, 1990). Relationship: A named association between entities
showing optionality and degree.
Definition of a Relational Database
A relational database uses relations or two- ER Modeling (continued)
dimensional tables to store information. Entities
To represent an entity in a model, use the following
Data Models conventions:
Models are a cornerstone of design. Engineers build a  Soft box with any dimensions
model of a car to work out any details before putting it  Singular, unique entity name
into production. In the same manner, system  Entity name in uppercase
designers develop models to explore ideas and  Optional synonym names in uppercase within
improve the understanding of the database design. parentheses: ( )
Attributes
Purpose of Models
To represent an attribute in a model, use the following
Models help communicate the concepts in people’s
conventions:
minds. They can be used to do the following:
 Use singular names in lowercase.
 Communicate
 Tag mandatory attributes, or values that must
 Categorize be known, with an asterisk: *.
 Describe
 Tag optional attributes, or values that may be
 Specify known, with the letter o.
 Investigate Relationships
 Evolve Each direction of the relationship contains:
 Analyze A label, for example, taught by or assigned to
 Imitate An optionality, either must be or may be
A degree, either one and only one or one or more
ER Modeling Note: The term cardinality is a synonym for the term
In an effective system, data is divided into discrete degree.
categories or entities. An entity relationship (ER)
model is an illustration of various entities in a business Each source entity {may be | must be} relationship
and the relationships between them. name {one and only one | one or more} destination
entity.
Benefits of ER Modeling Note: The convention is to read clockwise.
 Documents information for the organization
in a clear, precise format
Unique Identifiers A relational database can contain one or many tables.
A unique identifier (UID) is any combination of A table is the basic storage structure of an RDBMS. A
attributes or relationships, or both, that serves to table holds all the data necessary about something in
distinguish occurrences of an entity. Each entity the real world, such as employees, invoices, or
occurrence must be uniquely identifiable. customers.
Tag each attribute that is part of the UID with a The slide shows the contents of the EMPLOYEES table
number symbol: # or relation. The numbers indicate the following:
Tag secondary UIDs with a number sign in 1. A single row or table representing all data
parentheses: (#) required for a particular employee. Each row in a table
should be identified by a primary key, which
Relating Multiple Tables allows no duplicate rows. The order of rows is
Each table contains data that describes exactly one insignificant; specify the row order when the data is
entity. For example, the EMPLOYEES table contains retrieved.
information about employees. Categories of data are 2. A column or attribute containing the
listed across the top of each table, and individual cases employee number. The employee number identifies a
are listed below. Using a table format, you can readily unique employee in the EMPLOYEES table. In this
visualize, understand, and use information. example, the employee number column is designated
Because data about different entities is stored in as the primary key. A primary key must contain a
different tables, you may need to combine two or value, and the value must be unique.
more tables to answer a particular question. For 3. A column that is not a key value. A column
example, you may want to know the location of the represents one kind of data in a table; in the example,
department where an employee works. In this the salary of all the employees. Column order is
scenario, you need information from the EMPLOYEES insignificant when storing data; specify the column
table (which contains data about employees) and the order when the data is retrieved.
DEPARTMENTS table (which contains information 4. A column containing the department number,
about departments). With an RDBMS you can relate which is also a foreign key. A foreign key is a column
the data in one table to the data in another by using that defines how tables relate to each other. A foreign
the foreign keys. A foreign key is a column or a set of key refers to a primary key or a unique key in the same
columns that refer to a primary key in the same table table or in another table. In the example,
or another table. DEPARTMENT_ID uniquely identifies a department in
You can use the ability to relate data in one table to the DEPARTMENTS table.
data in another to organize information in separate, 5. A field may have no value in it. This is called a
manageable units. Employee data can be kept logically null value. In the EMPLOYEES table, only employees
distinct from department data by storing it in a who have a role of sales representative have a value in
separate table. the COMMISSION_PCT (commission) field.
6. A field can be found at the intersection of a
Guidelines for Primary Keys and Foreign Keys row and a column. There can be only one value in it.
 You cannot use duplicate values in a primary
key. Properties of a Relational Database
 Primary keys generally cannot be changed. In a relational database, you do not specify the access
 Foreign keys are based on data values and are route to the tables, and you do not need to know how
purely logical, not physical, pointers. the data is arranged physically.
 A foreign key value must match an existing To access the database, you execute a structured
primary key value or unique key value, or else query language (SQL) statement, which is the
be null. American National Standards Institute (ANSI) standard
 A foreign key must reference either a primary language for operating relational databases.
key or unique key column.

Terminology Used in a Relational Database


The language contains a large set of operators for EMPLOYEES table, which gives details of all the
partitioning and combining relations. The database employees
can be modified by using the SQL statements. DEPARTMENTS table, which gives details of all the
departments
Structured Query Language JOB_GRADES table, which gives details of salaries for
Using SQL, you can communicate with the Oracle various grades
server. SQL has the following advantages: Note: The structure and data for all the tables are
 Efficient provided in Appendix B.
 Easy to learn and use
 Functionally complete (With SQL, you can Capabilities of SQL SELECT Statements
define, retrieve, and manipulate data in the A SELECT statement retrieves information from the
tables.) database. Using a SELECT statement, you can do the
following:
Relational Database Management System  Projection: You can use the projection
Oracle provides a flexible RDBMS called Oracle9i. capability in SQL to choose the columns in a
Using its features, you can store and manage data with table that you want returned by your query.
all the advantages of a relational structure plus You can choose as few or as many columns of
PL/SQL, an engine that provides you with the ability to the table as you require.
store and execute program units. Oracle9i also  Selection: You can use the selection capability
supports Java and XML. The Oracle server offers the in SQL to choose the rows in a table that you
options of retrieving data based on optimization want returned by a query. You can use
techniques. It includes security features that control various criteria to restrict the rows that you
how a database is accessed and used. Other features see.
include consistency and protection of data through  Joining: You can use the join capability in SQL
locking mechanisms. to bring together data that is stored in
different tables by creating a link between
Every time a database is started, a system global area them. You learn more about joins in a later
(SGA) is allocated, and Oracle background processes lesson.
are started. The system global area is an area of
memory used for database information shared by the Basic SELECT Statement
database users. The combination of the background In its simplest form, a SELECT statement must include
processes and memory buffers is called an Oracle the following:
instance. A SELECT clause, which specifies the columns to be
displayed
SQL Statements A FROM clause, which specifies the table containing
Oracle SQL complies with industry-accepted the columns listed in the SELECT clause
standards. Oracle Corporation ensures future In the syntax:
compliance with evolving standards by actively SELECT is a list of one or
involving key personnel in SQL standards committees. more columns
Industry-accepted committees are the American * selects all
National Standards Institute (ANSI) and the columns
International Standards Organization (ISO). Both ANSI DISTINCT
and ISO have accepted SQL as the standard language suppresses duplicates
for relational databases. column|expression selects the named
column or the expression
alias gives selected
Tables Used in the Course columns different headings
The following main tables are used in this course: FROM table specifies the table
containing the columns
Note: Throughout this course, the words keyword, Keywords cannot be split across lines or abbreviated.
clause, and statement are used as follows: Clauses are usually placed on separate lines for
A keyword refers to an individual SQL element. readability and ease of editing.
For example, SELECT and FROM are keywords. Indents should be used to make code more readable.
A clause is a part of a SQL statement. Keywords typically are entered in uppercase; all other
For example, SELECT employee_id, last_name, ... is a words, such as table names and columns, are entered
clause. in lowercase.

A statement is a combination of two or more clauses. Executing SQL Statements


Using iSQL*Plus, click the Execute button to run the
For example, SELECT * FROM employees is a SQL command or commands in the editing
statement. window.
Selecting All Columns of All Rows Column Heading Defaults
You can display all columns of data in a table by In iSQL*Plus, column headings are displayed in
following the SELECT keyword with an asterisk (*). In uppercase and centered.
the example on the slide, the department table SELECT last_name, hire_date, salary
contains four columns: DEPARTMENT_ID, FROM employees;
DEPARTMENT_NAME, MANAGER_ID, and
LOCATION_ID. The table contains seven rows, one for Arithmetic Expressions
each department. Using Arithmetic Operators
You can also display all columns in the table by listing The example in the slide uses the addition operator to
all the columns after the SELECT keyword. For calculate a salary increase of $300 for all employees
example, the following SQL statement, like the and displays a new SALARY+300 column in the output.
example on the slide, displays all columns and all rows Note that the resultant calculated column
of the DEPARTMENTS table: SALARY+300 is not a new column in the EMPLOYEES
SELECT department_id, department_name, table; it is for display only. By default, the name of a
manager_id, location_id new column comes from the calculation that
FROM departments; generated it—in this case, salary+300.
Selecting Specific Columns of All Rows Note: The Oracle9i server ignores blank spaces before
You can use the SELECT statement to display specific and after the arithmetic operator.
columns of the table by specifying the column names, These are all possible using arithmetic expressions. An
separated by commas. The example on the slide arithmetic expression can contain column names,
displays all the department numbers and location constant numeric values, and the arithmetic
numbers from the DEPARTMENTS table. operators.
In the SELECT clause, specify the columns that you
want, in the order in which you want them to appear Arithmetic Operators
in the output. For example, to display location before The slide lists the arithmetic operators available in
department number going from left to right, you use SQL. You can use arithmetic operators in any clause of
the following statement: a SQL statement except in the FROM clause.
SELECT location_id, department_id
FROM departments; Operator Precedence
If an arithmetic expression contains more than one
Writing SQL Statements operator, multiplication and division are evaluated
Using the following simple rules and guidelines, you first. If operators within an expression are of same
can construct valid statements that are both easy to priority, then evaluation is done from left to right.
read and easy to edit: You can use parentheses to force the expression
SQL statements are not case sensitive, unless within parentheses to be evaluated first.
indicated. Operator Precedence (continued)
SQL statements can be entered on one or many lines.
The example on the slide displays the last name, column heading. This heading may not be descriptive
salary, and annual compensation of employees. It and hence may be difficult to understand. You can
calculates the annual compensation as 12 multiplied change a column heading by using a column alias.
by the monthly salary, plus a one-time bonus of $100. Specify the alias after the column in the SELECT list
Notice that multiplication is performed before using a space as a separator. By default, alias headings
addition. appear in uppercase. If the alias contains spaces or
Note: Use parentheses to reinforce the standard order special characters (such as # or $), or is case sensitive,
of precedence and to improve clarity. For example, enclose the alias in double quotation marks (" ").
the expression on the slide can be written as Column Aliases (continued)
(12*salary)+100 with no change in the result. The first example displays the names and the
Using Parentheses commission percentages of all the employees. Notice
You can override the rules of precedence by using that the optional AS keyword has been used before
parentheses to specify the order in which operators the column alias name. The result of the query is the
are executed. same whether the AS keyword is used or not. Also
The example on the slide displays the last name, notice that the SQL statement has the column aliases,
salary, and annual compensation of employees. It name and comm, in lowercase, whereas the result of
calculates the annual compensation as monthly salary the query displays the column headings in uppercase.
plus a monthly bonus of $100, multiplied by 12. As mentioned in a previous slide, column headings
Because of the parentheses, addition takes priority appear in uppercase by default.
over multiplication. The second example displays the last names and
Null Values annual salaries of all the employees. Because Annual
If a row lacks the data value for a particular column, Salary contain a space, it has been enclosed in double
that value is said to be null, or to contain a null. quotation marks. Notice that the column heading in
A null is a value that is unavailable, unassigned, the output is exactly the same as the column alias.
unknown, or inapplicable. A null is not the same as Concatenation Operator
zero or a space. Zero is a number, and a space is a You can link columns to other columns, arithmetic
character. expressions, or constant values to create a character
Columns of any data type can contain nulls. However, expression by using the concatenation operator (||).
some constraints, NOT NULL and PRIMARY KEY, Columns on either side of the operator are combined
prevent nulls from being used in the column. to make a single output column.
In the COMMISSION_PCT column in the EMPLOYEES Concatenation Operator (continued)
table, notice that only a sales manager or sales In the example, LAST_NAME and JOB_ID are
representative can earn a commission. Other concatenated, and they are given the alias Employees.
employees are not entitled to earn commissions. A Notice that the employee last name and job code are
null represents that fact. combined to make a single output column.
Null Values (continued) The AS keyword before the alias name makes the
If any column value in an arithmetic expression is null, SELECT clause easier to read.
the result is null. For example, if you attempt to Literal Character Strings
perform division with zero, you get an error. However, A literal is a character, a number, or a date that is
if you divide a number by null, the result is a null or included in the SELECT list and that is not a column
unknown. name or a column alias. It is printed for each row
In the example on the slide, employee King does not returned. Literal strings of free-format text can be
get any commission. Because the COMMISSION_PCT included in the query result and are treated the same
column in the arithmetic expression is null, the result as a column in the SELECT list.
is null. Date and character literals must be enclosed within
single quotation marks (' '); number literals need not.
Column Aliases Literal Character Strings (continued)
When displaying the result of a query, iSQL*Plus The example on the slide displays last names and job
normally uses the name of the selected column as the codes of all employees. The column has the heading
Employee Details. Notice the spaces between the Formats query results into a basic report
single quotation marks in the SELECT statement. The Accesses local and remote databases
spaces improve the readability of the output. SQL and iSQL*Plus (continued)
In the following example, the last name and salary for The following table compares SQL and iSQL*Plus
each employee are concatenated with a literal to give
the returned rows more meaning. iSQL*Plus
SELECT last_name ||': 1 Month salary = '||salary iSQL*Plus is an environment in which you can do the
Monthly following:
FROM employees; Execute SQL statements to retrieve, modify, add, and
remove data from the database
Duplicate Rows Format, perform calculations on, store, and print
Unless you indicate otherwise, iSQL*Plus displays the query results in the form of reports
results of a query without eliminating duplicate rows. Create script files to store SQL statements for
The example on the slide displays all the department repetitive use in the future
numbers from the EMPLOYEES table. Notice that the iSQL*Plus commands can be divided into the following
department numbers are repeated. main categories:
Duplicate Rows (continued)
To eliminate duplicate rows in the result, include the Limiting the Rows Selected
DISTINCT keyword in the SELECT clause immediately You can restrict the rows returned from the query by
after the SELECT keyword. In the example on the slide, using the WHERE clause. A WHERE clause contains a
the EMPLOYEES table actually contains 20 rows but condition that must be met, and it directly follows the
there are only seven unique department numbers in FROM clause. If the condition is true, the row meeting
the table. the condition is returned.
You can specify multiple columns after the DISTINCT In the syntax:
qualifier. The DISTINCT qualifier affects all the selected WHERE restricts the query to rows
columns, and the result is every distinct combination that meet a condition
of the columns. condition is composed of
SELECT DISTINCT department_id, job_id column names, expressions,
FROM employees; constants,
and a comparison operator
SQL and iSQL*Plus The WHERE clause can compare values in columns,
SQL is a command language for communication with literal values, arithmetic expressions, or functions. It
the Oracle server from any tool or application. Oracle consists of three elements:
SQL contains many extensions. Column name
iSQL*Plus is an Oracle tool that recognizes and Comparison condition
submits SQL statements to the Oracle server for Column name, constant, or list of values
execution and contains its own command language. Character Strings and Dates
Features of SQL
Can be used by a range of users, including those with Character strings and dates in the WHERE clause must
little or no programming experience be enclosed in single quotation marks (''). Number
Is a nonprocedural language constants, however, should not be enclosed in single
Reduces the amount of time required for creating and quotation marks.
maintaining systems All character searches are case sensitive. In the
Is an English-like language following example, no rows are returned because the
Features of iSQL*Plus EMPLOYEES table stores all the last names in mixed
Accessed from a browser case:
Accepts ad hoc entry of statements SELECT last_name, job_id, department_id
Provides online editing for modifying SQL statements FROM employees
Controls environmental settings WHERE last_name = 'WHALEN';
Oracle databases store dates in an internal numeric SELECT employee_id, manager_id, department_id
format, representing the century, year, month, day, FROM employees
hours, minutes, and seconds. The default date display WHERE last_name IN ('Hartstein', 'Vargas');
is DD-MON-RR. If characters or dates are used in the list, they must be
Note: Changing the default date format is covered in a enclosed in single quotation marks ('').
subsequent lesson. The LIKE Condition
Comparison Conditions You may not always know the exact value to search
Comparison conditions are used in conditions that for. You can select rows that match a character
compare one expression to another value or pattern by using the LIKE condition. The character
expression. They are used in the WHERE clause in the pattern-matching operation is referred to as a
following format: wildcard search. Two symbols can be used to
Syntax construct the search string.
... WHERE expr operator value
For Example The SELECT statement on the slide returns the
... WHERE hire_date='01-JAN-95' employee first name from the EMPLOYEES table for
... WHERE salary>=6000 any employee whose first name begins with an S. Note
... WHERE last_name='Smith' the uppercase S. Names beginning with an s are not
An alias cannot be used in the WHERE clause. returned.
Note: The symbol != and ^= can also represent the not The LIKE condition can be used as a shortcut for some
equal to condition. BETWEEN comparisons. The following example
Using the Comparison Conditions displays the last names and hire dates of all employees
In the example, the SELECT statement retrieves the who joined between January 1995 and December
last name and salary from the EMPLOYEES table, 1995:
where the employee salary is less than or equal to SELECT last_name, hire_date
3000. Note that there is an explicit value supplied to FROM employees
the WHERE clause. The explicit value of 3000 is WHERE hire_date LIKE '%95';
compared to the salary value in the SALARY column of Combining Wildcard Characters
the EMPLOYEES table. The % and _ symbols can be used in any combination
The BETWEEN Condition with literal characters. The example on the slide
You can display rows based on a range of values using displays the names of all employees whose last names
the BETWEEN range condition. The range that you have an o as the second character.
specify contains a lower limit and an upper limit. The ESCAPE Option
The SELECT statement on the slide returns rows from When you need to have an exact match for the actual
the EMPLOYEES table for any employee whose salary % and _ characters, use the ESCAPE option. This
is between $2,500 and $3,500. option specifies what the escape character is. If you
Values specified with the BETWEEN condition are want to search for strings that contain ‘SA_’, you can
inclusive. You must specify the lower limit first. use the following SQL statement:
The IN Condition
To test for values in a specified set of values, use the SELECT employee_id, last_name, job_id
IN condition. The IN condition is also known as the FROM employees
membership condition. WHERE job_id LIKE '%SA\_%' ESCAPE '\';
The slide example displays employee numbers, last
names, salaries, and manager’s employee numbers for The ESCAPE option identifies the backslash (\) as the
all the employees whose manager’s employee number escape character. In the pattern, the escape character
is 100, 101, or 201. precedes the underscore (_). This causes the Oracle
The IN condition can be used with any data type. The Server to interpret the underscore literally.
following example returns a row from the EMPLOYEES The NULL Conditions
table for any employee whose last name is included in The NULL conditions include the IS NULL condition and
the list of names in the WHERE clause: the IS NOT NULL condition.
The IS NULL condition tests for nulls. A null value The NOT Operator
means the value is unavailable, unassigned, unknown, The slide example displays the last name and job ID of
or inapplicable. Therefore, you cannot test with = all employees whose job ID is not IT_PROG, ST_CLERK,
because a null cannot be equal or unequal to any or SA_REP.
value. The slide example retrieves the last names and The NOT Truth Table
managers of all employees who do not have a The following table shows the result of applying the
manager. NOT operator to a condition:
For another example, to display last name, job ID, and
commission for all employees who are NOT entitled to Rules of Precedence
get a commission, use the following SQL statement: The rules of precedence determine the order in which
SELECT last_name, job_id, commission_pct expressions are evaluated and calculated. The table
FROM employees lists the default order of precedence. You can override
WHERE commission_pct IS NULL; the default order by using parentheses around the
expressions you want to calculate first.
Logical Conditions
A logical condition combines the result of two The ORDER BY Clause
component conditions to produce a single result based The order of rows returned in a query result is
on them or inverts the result of a single condition. A undefined. The ORDER BY clause can be used to sort
row is returned only if the overall result of the the rows. If you use the ORDER BY clause, it must be
condition is true. Three logical operators are available the last clause of the SQL statement. You can specify
in SQL: an expression, or an alias, or column position as the
AND sort condition.
OR Syntax
NOT SELECT expr
All the examples so far have specified only one FROM table
condition in the WHERE clause. You can use several [WHERE condition(s)]
conditions in one WHERE clause using the AND and OR [ORDER BY {column, expr} [ASC|DESC]];
operators. In the syntax:
ORDER BY specifies the order
The AND Operator in which the retrieved rows are displayed
In the example, both conditions must be true for any ASC orders the rows in
record to be selected. Therefore, only employees who ascending order (this is the default order)
have a job title that contains the string MAN and earn DESC orders the rows in
$10,000 or more are selected. descending order
All character searches are case sensitive. No rows are If the ORDER BY clause is not used, the sort order is
returned if MAN is not in uppercase. Character strings undefined, and the Oracle server may not fetch rows
must be enclosed in quotation marks. in the same order for the same query twice. Use the
AND Truth Table ORDER BY clause to display the rows in a specific
The following table shows the results of combining order.
two expressions with AND:
Default Ordering of Data
The OR Operator  The default sort order is ascending:
In the example, either condition can be true for any  Numeric values are displayed with the lowest
record to be selected. Therefore, any employee who values first—for example, 1–999.
has a job ID containing MAN or earns $10,000 or more  Date values are displayed with the earliest
is selected. value first—for example, 01-JAN-92 before
The OR Truth Table 01-JAN-95.
The following table shows the results of combining  Character values are displayed in alphabetical
two expressions with OR: order—for example, A first and Z last.
 Null values are displayed last for ascending
sequences and first for descending
sequences.

Reversing the Default Order


To reverse the order in which rows are displayed,
specify the DESC keyword after the column name in
the ORDER BY clause. The slide example sorts the
result by the most recently hired employee.

Sorting by Multiple Columns


You can sort query results by more than one column.
The sort limit is the number of columns in the given
table.
In the ORDER BY clause, specify the columns, and
separate the column names using commas. If you
want to reverse the order of a column, specify DESC
after its name. You can also order by columns that are
not included in the SELECT clause.
Example
Display the last names and salaries of all employees.
Order the result by department number, and then in
descending order by salary.
SELECT last_name, salary
FROM employees
ORDER BY department_id, salary DESC;

Вам также может понравиться