Uploaded by Bianca Carabio

SQL

advertisement
Chapter 7:
SQL
Modern Database Management
6"' Edition
Jeffrey A. Hoffer, Mary B. Prescott, Fred R.
McFadden
C
Prentice Hall. 2002
SQL Is:
Structured Query Language
The standard for relational database management
systems (RDBMS)
SQL-92 Standard — Purpose:
- Specify syntax/semantics for data definition and
manipulation
- Define data structures
- Enable portability
- Specify minimal (level 1) and complete (level 2)
standards
- Allow for later growth/enhancement to standard
Chapter 7
© Prentice Hall,
wn
2
Benefits of a Standardized
Relational Language
Reduced training costs
Productivity
Application portability
Application longevity
Reduced dependence on a single vendor
Cross-system communication
Chapter 7
© Prentice Hall,
onno
Catalog
SQL Environment
- a set of schemas that constitute the description of a database
Schema
- The structure that contains descriptions of objects created by a user
(base tables, views, constraints)
Data Definition Language (DDL):
- Commands that define a database, including creating, altering, and
dropping tables and establishing constraints
Data Manipulation Language (DML)
- Commands that maintain and query a database
Data Control Language (DCL)
- Commands that control a database, including administering
privileges and committing data
© Prentice Hall,
4
Figure 7-1:
A simplified schematic of a typical SQL environment, as
described by the SQL-92 standard
Chapter 7
© Prentice Hall
onno
5
SQL Data types (from Oracle8)
String types
CHAR(n) - fixed-length character data, n characters long
Maximum length = 2000 bytes
- VARCHAR2(n) - variable length character data, maximum 4000
bytes
LONG - variable-length character data, up to 4GB. Maximum 1
per table
Numeric types
- NUMBER(p.q) - general purpose numeric data type
- INTEGER(p) - signed integer, p digits wide
FLOAT(p) - floating point in scientific notation with p binary
digits precision
Date/time type
- DATE - fixed-length date/time in dd-mm-yy form
Chapter 7
© Prentice Hall,
6
Figure 7-4:
DDL, DML, DCL, and the database development process
DDL
Define the database:
CREATE tables, indexes, views
Establish foreign keys
Drop or truncate tables
DML
Load the database:
INSERT data
UPDATE the database
Manipulate the database:
SELECT
DCL
Control the database:
GRANT, ADD, REVOKE
Chapter 7
© Prentice Hall
Physical Design
Implementation
Maintenance
7
SQL Database Definition
Data Definition Language (DDL)
Major CREATE statements:
- CREATE SCHEMA - defines a portion of the database
owned by a particular user
CREATE TABLE - defines a table and its columns
- CREATE VIEW - defines a logical table from one or
more views
Other CREATE statements: CHARACTER SET,
COLLATION, TRANSLATION, ASSERTION,
DOMAIN
Chapter 7
© Prentice Hall,
9009
8
Table Creation
Figure 7-5: General syntax for CREATE TABLE
CREATE TABLE tablename
({column definition [table constraint] } . , . .
[ON COMMIT {DELETE I PRESERVE} ROWS]);
where column definition ::=
column_name
[domain name I datatype [(s/ze)] }
[columnconstraint_dause ...]
[default value]
[collate clause]
and table constraint ::=
[CONSTRAINT constraint_name]
Constraint-type [constraint-attributes]
Chapter 7
© Prentice Hall,
o run
Steps in table creation:
I.
Identify data types for
attributes
2.
Identify columns that can
and cannot be null
3.
Identify columns that must
be unique (candidate keys)
4.
Identify primary keyforeign key mates
5.
Determine default values
6.
Identify constraints on
columns (domain
specifications)
7.
Create the table and
associated indexes
9
Figure 7-3: Sample Pine Valley Furniture data
7-6: SQL database definition commands for Pine Valley Furniture
CREATE TABLE CUSTOMER T
(CUSTOMER JD
NUMBER) 11.0) NOT NULL.
CUSTOMER NAME
VARCHAR2(25) NOT NULL.
VARCHAR2)3O).
CUSTOMER, ADDRESS
CITY
VARCHAR2(2O).
VARCHAR2J2).
STATE
POSTAL-CODE
VARCHAR2(0).
CONSTRAINT CUSTOMER.PK PRIMARY KEY (CUSTOMERJD));
CREATE TABLE ORDER T
(ORDER_ID
NUMBER^ 1.0) NOT NULL.
ORDER DATE
DATE
DEFAULT SYSOATE.
CUSTOMER.©
NUMBER) 11.0),
CONSTRAINT ORDER.PK PRIMARY KEY (OROERJD).
CONSTRAINT ORDER.FK FOREIGN KEY (CUSTOMER.©) REFERENCES CUSTOMER. T(CUSTOMER. IO});
CREATE TABLE PROOUCT.T
(PRODUCT ID INTEGER
NOT NULL.
PRODUCT DESCR PTON
VARCHAR2(50).
PRODUCT-FINISH
VARCHAR2(20)
CHECK (PRODUCT FINISH IN ('Cherry', 'Nahxal A>h'. White Ash’.
Rod Oak1. Natural Oak'. Walnut')).
STANDARD PRICE
DECIMAL(6.2).
PRODUCT LINE ID
INTEGER.
CONSTRAINT PRODUCT.PK PRIMARY KEY (PRODUCT-ID));
CREATE TABLE ORDER. LINE T
(OROERJD
NUMBER) 11.0) NOT NULL.
PRODUCT ID
NUMBER) 11.0) NOT NULL.
NUMBER) 11,0).
ORDERED QUANTITY
CONSTRAINT ORDER.LINE.PK PRIMARY KEY (ORDER.©. PRODUCT_ID>.
CONSTRAINT ORDER LINE FK1 FOREIGN KEY (ORDER ID) REFERENCES ORDER T(ORDER ID).
CONSTRAINT ORDER.UNE.FK2 FOREIGN KEY (PRODUCT.©) REFERENCES PROOUCT.T(PRODUCTJD));
Chapter 7
© Prentice Hall,
11
7-6: SQL database definition commands for Pine Valley Furniture
CREATE TA IIP CUSTOMER T___________
(CUSTOMER.©
CUSTOMER NAME
CUSTOMER-ADDRESS
CITY
STATE
PQSTA. CODE
CONSTRAINT CUSTOMER.PK PRIMARY KEY
NUMBER! 11.0) JOT NULL.
VARCHAR2(25) JOT NULL.
VARCHAR2(30)
VARCHAR2(20)
VARCHAR2(2).
VARCHAR2K)).
(CUSTOMER.©)):
Defining
attributes and
their data types
CREATE TAI LE ORDER.T
(ORDER.©
NUMBER{ 11.0) JOT NULL.
DEFAULT SYSDATE.
ORDER DATE
DATE
CUSTOMER ©__________ ____ NUMBER! 11.0)
CONSTRAINT ORDER_PK PRIMARY KEY (ORDER.©),
CONSTRAINT ORDER.FK FOREIGN KEY (CUSTOMER IO) REFERENCES CUSTOMER T(CUSTOMER ID});
CREATE TA£ ILE PRODUCT T
(PRODUCT.©
INTEGER
JOT NULL.
PRODUCT DESCRIPTION
VARCHAR2(5O)
PRODUCT-FINISH
VARCHAR2(20)
CHECK (PROOUCT.FINISH IN ■Cherry'. -Natural Ash'. 'Who Ash'.
Rod Oak. -Na uralOak'. Walnut')).
STANDARD-PRICE
DECIMAL (6,2).
PRODUCT LINE ©
INTEGER.
CONSTRAINT PRODUCT.PK PRIMARY KEV iPRODUCT ID));
CONSTRAINT ORDER LINE FK1 FOREIGN KEY(ORDER ID) REFERENCES ORDER T(ORDER ©).
CONSTRAINT ORDER_LINE_FK2 FOREIGN KEY (PRODUCT.©) REFERENCES PRdouCT.T(PROOUCT.ID)};
Chapter 7
© Prentice Hall,
12
7-6: SQL database definition commands for Pine Valley Furniture
CREATE TABLE CUSTOMER T
(CUSTOMER.lD
CUSTOMER NAME
CUSTOMER-ADDRESS
CITY
STATE
POSTAL-CODE
CONSTRAINT CUSTOMER.PK PRIMARY KEY
NUMBERfl 1.(4 NOT NULL.
VARCHAR2(25| NOT NULL.
VARCHAR2(30).
VARCHAR2<20).
VARCHAR2(2),
VARCHAR2(S».
(CUSTOMERJD)):
Non-nullable
specifications
C.RFATF TAR1 F ORflFR T
(ORDER.©
NUMBER! 11.14 NOT NULL.
ORDER DATE
DEFAULT SYSCate.
DATE
CUSTOMERJD
NUMBER! 11.0).
CONSTRAINT ORDER PK PRIMARY KEY (ORDER ID).
CONSTRAINT ORDER.FK FOREIGN KEY (CUSTOMER IO) REFERENCES CUSTOMER /(CUSTOMER ID});
CREATE TABLE PRODUCT/
(PRODUCT JD
INTEGER
_______________
| NOT NULL.
PRODUCT DESCRIPTION
VARCHAR2(5C)
PRODUCT-FINISH
VARCHAR2(20)
CHECK (PRODUCT.FINISH IN ('Charry'. -Natural Ash'. 'Who Ash'.
•Rod Oak'. -Natural Oak'. ’Walnut-)).
STANDARD-PRICE
DECIMAL (6,2).
PRODUCT LINE ID
INTEGER.
CONSTRAINT PRODUCT PK PRIMARY KEY I PRODUCT ID));
Note: primary
keys should not
be null
CREATE TABLE ORDER UNE T
(ORDER.©
NUMBER! 11,0 NOT NULL.
PROOUCT.ID
NUMBER! 11.0 NOT NULL.
ORDERED QUANTITY
NUMBER! 11,0),
CONSTRAINT ORDER.LINE PK PRIMARY KEY (ORDER.lD, PROOUCT.ID),
CONSTRAINT ORDER LINE FK1 FOREIGN KEY(ORDER ID) REFERENCES ORDER BORDER ©).
CONSTRAINT ORD€R_LINE_FK2 FOREIGN KEY (PROOUCT.ID) REFERENCES PRdouCT_T(PRODUCT_ID)};
Chapter 7
© Prentice Hall,
13
7-6: SQL database definition commands for Pine Valley Furniture
CREATE TABLE CUSTOMER T
(CUSTOMERJD
CUSTOMER NAME
CUSTOMER-ADDRESS
CITY
STATE
NUMBER! 11.0) NOT NULL.
VARCHAR2(25) NOT NULL.
VARCHAR2(30).
VARCHAR2(20).
Identifying
primary keys
।--------------------------------------------------- wno iar^------- | CONSTRAINT CUSTOMER PK PRIMARY KEY (CUSTOMER-ID)):
CREATE TABLE OROER.T
(ORDER.O
NUMBER! 11.0) NOT NULL.
ORDER DATE
DATE
DEFAULT SYSDATE.
,------------------------ CUSTOMER-10------------------------- NUMBUf 11.0),
CONSTRAINT ORDER PK PRIMARY KEY (ORDER ID).
UUNSIUAINI WUMfm FUREIUN REY <UUS(UMLM Io) REFERENCES CUSTOMER TfCUSTOMER ©));
CREATE TABLE PROOUCT_T
(PRODUCT.ID
INTEGER
NOT NULL.
PRODUCT DESCRIPTION
VARCHAR2(50).
PRODUCT-FINISH
VARCHAR2(20)
CHECK (PROOUCT.FINlSH IN (-Charry'. ’Natural Ash'. ’Who Ash'.
Rod Oak'. 'Natural Oak1. -Walnut*)).
STANDARO_PRICE
DECIMAL (6.2).
------------------------ RRODUGi LINE *0------------------- INTEGER:------- >
CONSTRAINT PRQOUCT PK PRIMARY KEY iPRQDOCT ID)); |
CREATE TABLE ORDER LINE T
(ORDER.O
NUMBER! 11.0) NOT NULL.
PRODUCT.ID
NUMBER( 11.0) NOT NULL.
_________________ ORDERED QUANTITY________ NUMRF.Ri 11 Ot________________
| CONSTRAINT ORDER LINE.PK PRIMARY KEY (ORDER ID. PRODUCT.ID),
|
This is a composite
primary key
CONSTRAINT ORDER LINE FK1 FOREIGN KEY(ORDER ID) REFERENCES ORDER T(ORDER iD).
CONSTRAINT ORDER.LINE.FK2 FOREIGN KEY (PRODUCT.ID) REFERENCES PRdouCT.TfPRODUCT.ID)):
Chapter 7
© Prentice Hall,
|4
7-6: SQL database definition commands for Pine Valley Furniture
CREATE TABLE CUSTOMER T
(CUSTOMERJD
CUSTOMER NAME
CUSTOMER-ADDRESS
CITY
STATE
POSTAL-CODE
CONSTRAINT CUSTOMER.PK PRIMARY KEY
NUMBER! 11.01 NOT NULL.
VARCHAR2(25) NOT NULL.
VARCHAR2(30).
VARCHAR2(20).
VARCHAR2(2).
VARCHAR2(9).
(CUSTOMERJD)):
Identifying
foreign keys and
establishing
relationships
CREATE TABLE OROER-T
(ORDER.O
NUMBER! 11.0) NOT NULL.
ORDER DATE
DATE
DEFAULT SYSDATE.
CUSTOMER-ID
NUMBER! 11.0).
CONSTRAINT ORDER PK PRIMARY KEY (ORDER ID).____________________________________________________
| CONSTRAINT ORDER FK FOREIGN KEY (CUSTOMER IO) REFERENCES CUSTOMER ^CUSTOMER ID))~l
CREATE TABLE PRODUCTS
(PROOUCT_ID INTEGER
NOT NULL.
PRODUCT DESCRIPTION
VARCHAR2(50),
PRODUCT-FINISH
VARCHAR2(20)
CHECK (PRODUCT.FINISH IN ('Ctwrry', -Natural Ash'. Who Ash'.
•Rod Oak', -Natural Oak'. 'Walnut*)).
STANDARD-PRICE
DECIMAL (6,2).
PRODUCT LINE ID
INTEGER.
CONSTRAINT PRODUCT PK PRIMARY KEY I PRODUCT ID));
CREATE TABLE ORDER UNE T
(ORDER.©
PROOUCT_ID
ORDERED QUANTITY
NUMBER! 11.0) NOT NULL.
NUMBER! 11.0) NOT NULL.
NUMBER! 11,0),
GQftLSTRAl.NI ORDER 1.1NF FK,PRIMARY .KEY 1GRDER 1D. PRODI ^11, ID)_____________________________
.ggN.g™»g.QBe^!HL^Lra^
______
CONSTRAINT OROER.LINE-FK2 FOREIGN KEY (PRODUCT.ID) REFERENCES PRODUCT.TfPRODUCT.ID));
Chapter 7
© Prentice Hall,
9AA9
15
7-6: SQL database definition commands for Pine Valley Furniture
CREATE TABLE CUSTOMER T
(CUSTOMERJD
CUSTOMER NAME
CUSTOMER-ADDRESS
CITY
STATE
POSTAL-CODE
CONSTRAINT CUSTOMER.PK PRIMARY KEY
NUMBER! 11.0) NOT NULL.
VARCHAR2(25) NOT NULL.
VARCHAR2(30).
VARCHAR2(20).
VARCHAR2(2).
VARCHAR2(S».
(CUSTOMERJD)):
Default values
and domain
constraints
CREATE TABLE OROER.T
(ORDER.©
NUMBER! 11. cpiQLUJU__________.
DATE
[ DEFAULT SYSDATE,|
ORDER DATE
NUMBER! 11. (fl.
CUSTOMER-ID
CONSTRAINT ORDER PK PRIMARY KEY (ORDER ID),
CONSTRAINT ORDER.FK FOREIGN KEY (CUSTOMER .10) REFERENCES CUSTOMER T(CUSTOMER ID});
CREATE TABLE PRODUCT,T
(PRODUCT JD INTEGER
PRODUCT DESCRIPTION
NOT NULL.
VARCHAR2(50).
PRODUCT FiMS±___________ YARGHAR2i2Ql________________________
CHECK (PRODUCT.FINISH IN ('Ctway'. -Natural Ash'. 'Who Asli'.
|__________________ Rod Oak-. -Natural Oak', -WalnuT)).______________
STANDARD PRICE
DECIMAL(«,2).
PRODUCT LINE ID
INTEGER.
CONSTRAINT PRODUCT PK PRIMARY KEY I PRODUCT ID));
CREATE TABLE ORDER UNE T
(ORDER.©
NUMBER! 11.0) NOT NULL.
PROOUCT.ID
NUMBER) 11.0) NOT NULL.
ORDERED QUANTITY
NUMBER! 11.0).
CONSTRAINT ORDER.LINEPK PRIMARY KEY (ORDER.lD, PROOUCT.ID).
CONSTRAINT ORDER LINE FK1 FOREIGN KEY(ORDER ID) REFERENCES ORDER T<ORDER ©).
CONSTRAINT OROER_LINE.FK2 FOREIGN KEY (PROOUCT.ID) REFERENCES PRdouCT.T(PRODUCT.ID)};
Chapter 7
© Prentice Hall,
16
7-6: SQL database definition commands for Pine Valley Furniture
CREATE TABLE CUSTOMER T
(CUSTOMERJO
CUSTOMER NAME
CUSTOMER.ADDRESS
CITY
STATE
POSTAL-CODE
CONSTRAINT CUSTOMER PK PRIMARY KEY
NUMBER! 11.0) NOT NULL.
VARCHAR2(25) NOT NULL.
VARCHAR2O0).
VARCHAR2(20).
VARCMAR2(2).
VARCHAR2(9).
(CUSTOMER ID)):
Overall table
definitions
CREATE TABLE OROER.T
(ORDER.©
NUMBER! 11.0) NOT NULL.
ORDER DATE
DATE
DEFAULT SYSDATE.
CUSTOMER-ID
NUMBER! 11.0).
CONSTRAINT ORDER PK PRIMARY KEY (ORDER JD).
CONSTRAINT ORDER FK FOREIGN KEY (CUSTOMER ID) REFERENCES CUSTOMER T(CUSTOMER ID));
CREATE TABLE PROOUCT.T
(PRODUCT_ID INTEGER
NOT NULL.
PRODUCT DESCRIPTION
VARCHAR2(50).
PRODUCT-FINISH
VARCHAR2(20)
CHECK (PRODUCT.FINISH IN ('Cherry'. -Natural Ash-. 'Wh<» Ash'.
Rod Oak'. Natural Oak'. ’Walnut*)).
STANDARD_PR>CE
DECIMAL (6.2).
PRODUCT LINE ID
INTEGER.
CONSTRAINT PRODUCT PK PRIMARY KEY iPRODUCT ID));
CREATE TABLE ORDER LINE T
(ORDER.O
NUMBER! 11.0) NOT NULL.
PROOUCT.ID
NUMBER! 11.0) NOT NULL.
ORDERED QUANTITY
NUMBER(11.0).
CONSTRAINT ORDER LINE PK PRIMARY KEY (ORDER JD. PRODUCT-ID).
CONSTRAINT ORDER LINE_FK1 FOREIGN KEY(ORDER ID) REFERENCES ORDER_T(ORDER D).
CONSTRAINT ORDER LINE FK2 FOREIGN KEY (PRODUCTJD) REFERENCES PRODUCT.TfPRODUCT. ID));
Chapter 7
© Prentice Hall
Using and Defining Views
Views provide users controlled access to
tables
Advantages of views:
- Simplify query commands
- Provide data security
- Enhance programming productivity
CREATE VIEW command
Chapter 7
© Prentice Hall,
18
View Terminology
Base Table
- A table containing the raw data
Dynamic View
- A “virtual table” created dynamically upon request by a user.
- No data actually stored; instead data from base table made
available to user
- Based on SQL SELECT statement on base tables or other
views
Materialized View
- Copy or replication of data
- Data actually stored
- Must be refreshed periodically to match the corresponding
base tables
© Prentice Hall,
onno
19
Sample CREATE VIEW
CREATE VIEW EXPENSIVE_STUFF_V AS
SELECT PRODUCT ID, PRODUCT NAME, UNIT PRICE
FROM PRODUCT T
WHERE UNIT_PRICE >300
WITH CHECK_OPT1ON;
• View has a name
• View is based on a SELECT statement
• CHECK OPTION works only for updateable views and
prevents updates that would create rows not included in the
view
Chapter 7
© Prentice Hall,
20
Table 7-2: Pros and Cons of Using Dynamic Views
Table 7-2 Pros and Cons ol Using Dynamic views
Positive Aspects
Negative Aspects
Simplify query commands
Use processing time re-creating view each time
it is referenced
Help provide data security and confidentiality
Improve programmer productivity
Contain most current base table data
May or may not be
directly updateable
Use little storage space
Provide a customized view for a user
Establish physical data independence
Chapter 7
© Prentice Hall,
9009
21
Data Integrity Controls
Referential integrity - constraint that
ensures that foreign key values of a table
must match primary key values of a related
table in 1 :M relationships
Restricting:
- Deletes of primary records
- Updates of primary records
- Inserts of dependent records
Chapter 7
© Prentice Hall,
22
Figure 7-7: Ensuring data integrity through updates
CUSTOMER
... -.. -...... -.... —
(PK=CUSTOMER_ID)
CREATE TABLE CUSTOMER T
(CUSTOMER ID
CUSTOMER NAME
ORDER
(FK=CUSTOMER_ID)
INTEGER DEFAULT ‘C999
VARCHAR(4O)
NOT NULL.
NOT NULL.
CONSTRAINT CUSTOMER PK PRIMARY KEY (CUSTOMER ID).
ON UPDATE RESTRICT):
Cascaded Update: Chancing a customer ID m the CUSTOMER table wit result in that
value changing in the ORDER table to match.
... ON UPDATE CASCADE):
Set Null Update. W»n«n a customer IO is changed, any customer ID in the ORDER table
that matches the old customer ID is set to NULL.
. . . ON UPDATE SET NULL):
Set Default Update: When a customer ID is changed, any customer ID in tire ORDER
tables that matches the old customer ID is set to a predefined default value.
...ON UPDATE SET DEFAULT);
Chapter 7
© Prentice Hall,
23
Changing and Removing
Tables
ALTER TABLE statement allows you to
change column specifications:
- ALTER TABLE CUSTOMERT ADD (TYPE
VARCHAR(2))
DROP TABLE statement allows you to
remove tables from your schema:
- DROP TABLE CUSTOMER T
Chapter 7
© Prentice Hall,
24
Schema Definition
Control processing/storage efficiency:
-
Choice of indexes
File organizations for base tables
File organizations for indexes
Data clustering
Statistics maintenance
Creating indexes
- Speed up random/sequential access to base table data
- Example
• CREATE INDEX NAME1DX ON
CUSTOMERT(CUSTOMERNAME)
• This makes an index for the CUSTOMER NAME field of the
CUSTOMER!' table
© Prentice Hall,
9009
25
Insert Statement
Adds data to a table
Inserting into a table
- INSERT INTO CUSTOMER_T VALUES (001. ‘CONTEMPORARY
Casuals’, 1355 S. Himes Blvd.’, ‘Gainesville’, ‘FL’, 32601);
Inserting a record that has some null attributes requires identifying the
fields that actually get data
- INSERT INTO PRODUCT_T (PRODUCTJD.
PRODUCT_DESCRIPTION.PRODUCT_FINISH, STANDARD_PRICE.
PRODUCT_ON-HAND) VALUES (I. ‘End Table', ‘Cherry’, 175. 8);
Inserting from another table
- INSERT INTO CA_CUSTOMER_T SELECT * FROM CUSTOMER_T WHERE
STATE = ‘CA’;
© Prentice Hall,
onno
26
Delete Statement
Removes rows from a table
Delete certain rows
- DELETE FROM CUSTOMER ? WHERE
STATE =‘HI’;
Delete all rows
- DELETE FROM CUSTOMER T;
Chapter 7
© Prentice Hall,
27
Update Statement
Modifies data in existing rows
UPDATE PRODUCTT SET UNITPRICE = 775
WHERE PRODUCTJD = 7;
Chapter 7
© Prentice Hall,
28
The SELECT Statement
Used for queries on single or multiple tables
Clauses of the SELECT statement:
- SELECT
• List the columns (and expressions) that should be returned from the
query
- FROM
• Indicate the table(s) or view(s) from which data will be obtained
- WHERE
• Indicate the conditions under which a row will be included in the result
- GROUP BY
• Indicate categorization of results
- HAVING
• Indicate the conditions under which a category (group) will be included
- ORDER BY
Chap°ie?<7rls l*lc rcsull according to specified criteria
on no
29
SELECT Example
Find products with standard price less than $275
SELECT PRODUCT NAME, STANDARD PRICE
FROM PRODUCT V
WHERE STANDARD PRICE < 275
Table 7-3 Comparison Operators In
SQL
Operator
Meaning
Equal to
Greater than
Table 7-3: Comparison Operators in SQL
Greater than or equal to
Less than
Less than or equal to
Nol equal to
Not equal to
Chapter 7
© Prentice Hall
31
SELECT Example with ALIAS
Alias is an alternative column or table name
SELECT CUST.CUSTOMER AS NAME,
CUST.CUSTOMERADDRESS
FROM CUSTOMERV CUST
WHERE NAME = ‘Home Furnishings’;
© Prentice Hall,
9009
32
SELECT Example
Using a Function
Using the COUNT aggregate function to find
totals
SELECT COUNT(*) FROM ORDERLINEV
WHERE ORDER ID = 1004;
Note: with aggregate functions you can’t have single­
valued columns included in the SELECT clause
Chapter 7
© Prentice Hall,
9009
33
SELECT Example - Boolean Operators
AND, OR., and NOT Operators for customizing
conditions in WHERE clause
SELECT PRODUCT DESCRIPTION,
PRODUCT FINISH, STANDARD PRICE
FROM PRODUCT V
WHERE (PRODUCT DESCRIPTION LIKE ‘%Desk’
OR PRODUCT DESCRIPTION LIKE ‘%Table’)
AND UNIT PRICE > 300;
Note: the LIKE operator allows you to compare strings using wildcards. For
example, the % wildcard in €%Desk' indicates that all strings that have any
number of characters preceding the word “Desk" will be allowed
© Prentice Hall,
34
SELECT Example Sorting Results with the ORDER BY Clause
Sort the results first by STATE, and within a state
by CUSTOMER_NAME
SELECT CUSTOMER_NAME, CITY, STATE
FROM CUSTOMER V
WHERE STATE IN (‘FL’, ‘TX’, ‘CA’, ‘HI’)
ORDER BY STATE, CUSTOMER NAME;
Note: the IN operator in this example allows you to include rows whose
STATE value is cither FL, TX, CA, or HI. It is more efficient than separate
OR conditions
Chapter 7
© Prentice Hall,
onno
35
SELECT Example Categorizing Results Using the GROUP BY Clause
For use with aggregate functions
- Scalar aggregate: single value returned from SQL query with
aggregate function
Vector aggregate: multiple values returned from SQL query with
aggregate function (via GROUP BY)
SELECT STATE, COUNT(STATE)
FROM CUSTOMERV
GROUP BY STATE;
Note: you can use single-value fields with aggregate
functions if they are included in the GROUP BY clause
© Prentice Hall,
36
SELECT Example Qualifying Results by Categories
Using the HAVING Clause
For use with GROUP BY
SELECT STATE, COUNT(STATE)
FROM CUSTOMER V
GROUP BY STATE
HAVING COUNT(STATE) > 1;
Like a WHERE clause, but it operates on groups (categories), not on
individual rows. Here, only those groups with total numbers
greater than 1 will be included in final result
© Prentice Hall,
37
Download