1. Trang chủ
  2. » Công Nghệ Thông Tin

SQL VISUAL QUICKSTART GUIDE- P17 docx

10 293 0

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Cấu trúc

  • Table of Contents

  • Introduction

  • About SQL

  • About This Book

  • What You’ll Need

  • Chapter 1: DBMS Specifics

    • Running SQL Programs

    • Microsoft Access

    • Microsoft SQL Server

    • Oracle

    • IBM DB2

    • MySQL

    • PostgreSQL

  • Chapter 2: The Relational Model

    • Tables, Columns, and Rows

    • Primary Keys

    • Foreign Keys

    • Relationships

    • Normalization

    • The Sample Database

    • Creating the Sample Database

  • Chapter 3: SQL Basics

    • SQL Syntax

    • SQL Standards and Conformance

    • Identifiers

    • Data Types

    • Character String Types

    • Binary Large Object Type

    • Exact Numeric Types

    • Approximate Numeric Types

    • Boolean Type

    • Datetime Types

    • Interval Types

    • Unique Identifiers

    • Other Data Types

    • Nulls

  • Chapter 4: Retrieving Data from a Table

    • Retrieving Columns with SELECT and FROM

    • Creating Column Aliases with AS

    • Eliminating Duplicate Rows with DISTINCT

    • Sorting Rows with ORDER BY

    • Filtering Rows with WHERE

    • Combining and Negating Conditions with AND, OR, and NOT

    • Matching Patterns with LIKE

    • Range Filtering with BETWEEN

    • List Filtering with IN

    • Testing for Nulls with IS NULL

  • Chapter 5: Operators and Functions

    • Creating Derived Columns

    • Performing Arithmetic Operations

    • Determining the Order of Evaluation

    • Concatenating Strings with ||

    • Extracting a Substring with SUBSTRING()

    • Changing String Case with UPPER() and LOWER()

    • Trimming Characters with TRIM()

    • Finding the Length of a String with CHARACTER_LENGTH()

    • Finding Substrings with POSITION()

    • Performing Datetime and Interval Arithmetic

    • Getting the Current Date and Time

    • Getting User Information

    • Converting Data Types with CAST()

    • Evaluating Conditional Values with CASE

    • Checking for Nulls with COALESCE()

    • Comparing Expressions with NULLIF()

  • Chapter 6: Summarizing and Grouping Data

    • Using Aggregate Functions

    • Creating Aggregate Expressions

    • Finding a Minimum with MIN()

    • Finding a Maximum with MAX()

    • Calculating a Sum with SUM()

    • Calculating an Average with AVG()

    • Counting Rows with COUNT()

    • Aggregating Distinct Values with DISTINCT

    • Grouping Rows with GROUP BY

    • Filtering Groups with HAVING

  • Chapter 7: Joins

    • Qualifying Column Names

    • Creating Table Aliases with AS

    • Using Joins

    • Creating Joins with JOIN or WHERE

    • Creating a Cross Join with CROSS JOIN

    • Creating a Natural Join with NATURAL JOIN

    • Creating an Inner Join with INNER JOIN

    • Creating Outer Joins with OUTER JOIN

    • Creating a Self-Join

  • Chapter 8: Subqueries

    • Understanding Subqueries

    • Subquery Syntax

    • Subqueries vs. Joins

    • Simple and Correlated Subqueries

    • Qualifying Column Names in Subqueries

    • Nulls in Subqueries

    • Using Subqueries as Column Expressions

    • Comparing a Subquery Value by Using a Comparison Operator

    • Testing Set Membership with IN

    • Comparing All Subquery Values with ALL

    • Comparing Some Subquery Values with ANY

    • Testing Existence with EXISTS

    • Comparing Equivalent Queries

  • Chapter 9: Set Operations

    • Combining Rows with UNION

    • Finding Common Rows with INTERSECT

    • Finding Different Rows with EXCEPT

  • Chapter 10: Inserting, Updating, and Deleting Rows

    • Displaying Table Definitions

    • Inserting Rows with INSERT

    • Updating Rows with UPDATE

    • Deleting Rows with DELETE

  • Chapter 11: Creating, Altering, and Dropping Tables

    • Creating Tables

    • Understanding Constraints

    • Creating a New Table with CREATE TABLE

    • Forbidding Nulls with NOT NULL

    • Specifying a Default Value with DEFAULT

    • Specifying a Primary Key with PRIMARY KEY

    • Specifying a Foreign Key with FOREIGN KEY

    • Forcing Unique Values with UNIQUE

    • Adding a Check Constraint with CHECK

    • Creating a Temporary Table with CREATE TEMPORARY TABLE

    • Creating a New Table from an Existing One with CREATE TABLE AS

    • Altering a Table with ALTER TABLE

    • Dropping a Table with DROP TABLE

  • Chapter 12: Indexes

    • Creating an Index with CREATE INDEX

    • Dropping an Index with DROP INDEX

  • Chapter 13: Views

    • Creating a View with CREATE VIEW

    • Retrieving Data Through a View

    • Updating Data Through a View

    • Dropping a View with DROP VIEW

  • Chapter 14: Transactions

    • Executing a Transaction

  • Chapter 15: SQL Tricks

    • Calculating Running Statistics

    • Generating Sequences

    • Finding Sequences, Runs, and Regions

    • Limiting the Number of Rows Returned

    • Assigning Ranks

    • Calculating a Trimmed Mean

    • Picking Random Rows

    • Handling Duplicates

    • Creating a Telephone List

    • Retrieving Metadata

    • Working with Dates

    • Calculating a Median

    • Finding Extreme Values

    • Changing Running Statistics Midstream

    • Pivoting Results

    • Working with Hierarchies

  • Index

    • A

    • B

    • C

    • D

    • E

    • F

    • G

    • H

    • I

    • J

    • K

    • L

    • M

    • N

    • O

    • P

    • Q

    • R

    • S

    • T

    • U

    • V

    • W

Nội dung

Changing String Case with UPPER() and LOWER() Use the function UPPER() to return a string with lowercase letters converted to upper- case, and use the function LOWER() to return a string with uppercase letters converted to lowercase. The functions’ important charac- teristics are: ◆ A cased character is a letter that can be lowercase (a) or uppercase (A). ◆ Case changes affect only letters. Digits, punctuation, and whitespace are left unchanged. ◆ Case changes have no effect on empty strings ( ‘’ ). ◆ If its argument is null, UPPER() and LOWER() return null. (But see the Oracle exception in the DBMS Tip in this section.) 140 Chapter 5 Changing String Case Case-Insensitive Comparisons In DBMSs that perform case-sensitive WHERE -clause comparisons by default, UPPER() or LOWER() often is used to make case-insensitive comparisons: WHERE UPPER(au_fname) = ‘JOHN’ If you’re sure that your data are clean, it’s faster to look for only reasonable letter combinations than to use case functions: WHERE au_fname = ‘JOHN’ OR au_fname = ‘John’ UPPER() and LOWER() affect characters with diacritical marks (such as accents and umlauts): UPPER(‘ö’) is ‘Ö’ , for exam- ple. If your data contain such characters and you’re making case-insensitive com- parisons such as WHERE UPPER(au_fname) = ‘JOSÉ’ make sure that your DBMS doesn’t lose the marks on conversion. UPPER(‘Jos é ’) should be ‘JOSÉ’ , not ‘JOSE’ . See also “Filtering Rows with WHERE ” in Chapter 4. To convert a string to uppercase or lowercase: ◆ To convert a string to uppercase, type: UPPER(string) or To convert a string to lowercase, type: LOWER(string) string is a string expression such as a column that contains character strings, a string literal, or the result of an opera- tion or function that returns a string (Listings 5.15 and 5.16, Figures 5.15 and 5.16). ✔ Tips ■ You can use UPPER() and LOWER() in SELECT , WHERE , and ORDER BY clauses or anywhere an expression is allowed. ■ UPPER() and LOWER() don’t affect charac- ter sets with no concept of case (such as Hebrew and Chinese). ■ In Microsoft Access, the upper- and lowercase functions are UCase(string) and LCase(string) . To run Listings 5.15 and 5.16, change the case expressions to (Listing 5.15): LCase(au_fname) UCase(au_lname) and (Listing 5.16): UCase(title_name) LIKE ‘%MO%’ Oracle treats an empty string as null: UPPER(NULL) and LOWER(NULL) return ‘’ . See the DBMS Tip in “Nulls” in Chapter 3. Your DBMS might provide other string- casing functions to, say, invert case or convert strings to sentence or title case. Search your DBMS documentation for character functions or string functions. 141 Operators and Functions Changing String Case Listing 5.15 List the authors’ first names in lowercase and last names in uppercase. See Figure 5.15 for the result. SELECT LOWER(au_fname) AS "Lower", UPPER(au_lname) AS "Upper" FROM authors; Listing Lower Upper sarah BUCHMAN wendy HEYDEMARK hallie HULL klee HULL christian KELLS KELLSEY paddy O'FURNITURE Figure 5.15 Result of Listing 5.15. Listing 5.16 List the titles that contain the characters MO, regardless of case. All the letters in the LIKE pattern must be uppercase for this query to work. See Figure 5.16 for the result. SELECT title_name FROM titles WHERE UPPER(title_name) LIKE '%MO%'; Listing title_name 200 Years of German Humor I Blame My Mother Figure 5.16 Result of Listing 5.16. Trimming Characters with TRIM() Use the function TRIM() to remove unwanted characters from the ends of a string. The function’s important characteristics are: ◆ You can trim leading characters, trailing characters, or both. (You can’t use TRIM() to remove characters from within a string.) ◆ By default, TRIM() trims spaces, but you can strip off any unwanted characters, such as leading and trailing zeros or asterisks. ◆ TRIM() typically is used to format results and make comparisons in a WHERE clause. ◆ TRIM() is useful for trimming trailing spaces from CHAR values. Recall from “Character String Types” in Chapter 3 that DBMSs add spaces automatically to the end of CHAR values to create strings of exactly a specified length. ◆ Trimming has no effect on empty strings ( ‘’ ). ◆ If any argument is null, TRIM() returns null. (But see the Oracle exception in the DBMS Tip in this section.) 142 Chapter 5 Trimming Characters with TRIM() To trim spaces from a string: ◆ Type: TRIM([[LEADING | TRAILING | BOTH] FROM] string) string is a string expression such as a column that contains character strings, a string literal, or the result of an opera- tion or function that returns a string. Specify LEADING to remove leading spaces, TRAILING to remove trailing spaces, or BOTH to remove leading and trailing spaces. If this specifier is omit- ted, BOTH is assumed (Listing 5.17 and Figure 5.17). 143 Operators and Functions Trimming Characters with TRIM() Listing 5.17 This query strips leading, trailing, and both leading and trailing spaces from the string ‘ AAA ‘ . The < and > characters show the extent of the trimmed strings. See Figure 5.17 for the result. SELECT '<' || ' AAA ' || '>' AS "Untrimmed", '<' || TRIM(LEADING FROM ' AAA ') || '>' AS "Leading", '<' || TRIM(TRAILING FROM ' AAA ') || '>' AS "Trailing", '<' || TRIM(' AAA ') || '>' AS "Both"; Listing Untrimmed Leading Trailing Both < AAA > <AAA > < AAA> <AAA> Figure 5.17 Result of Listing 5.17. To trim characters from a string: ◆ Type: TRIM([LEADING | TRAILING | BOTH] ‘trim_chars’ FROM string) string is the string to trim, and trim_chars is one or more characters to remove from string. Each argument is a string expression such as a column that con- tains character strings, a string literal, or the result of an operation or function that returns a string. Specify LEADING to remove leading characters, TRAILING to remove trailing characters, or BOTH to remove leading and trailing characters. If this specifier is omitted, BOTH is assumed (Listings 5.18 and 5.19, Figures 5.18 and 5.19). 144 Chapter 5 Trimming Characters with TRIM() Listing 5.19 List the three-character title IDs that start with T1, ignoring leading and trailing spaces. See Figure 5.19 for the result. SELECT title_id FROM titles WHERE TRIM(title_id) LIKE 'T1_'; Listing title_id T10 T11 T12 T13 Figure 5.19 Result of Listing 5.19. Listing 5.18 Strip the leading H from the authors’ last names that begin with H. See Figure 5.18 for the result. SELECT au_lname, TRIM(LEADING 'H' FROM au_lname) AS "Trimmed name" FROM authors; Listing au_lname Trimmed name Buchman Buchman Heydemark eydemark Hull ull Hull ull Kells Kells Kellsey Kellsey O'Furniture O'Furniture Figure 5.18 Result of Listing 5.18. ✔ Tips ■ You can use TRIM() in SELECT , WHERE , and ORDER BY clauses or anywhere an expres- sion is allowed. ■ In Listing 5.8 earlier in this chapter, I concatenated authors’ first and last names into a single column. The result, Figure 5.8, contains a single extra space before the author named Kellsey. This space—which separates the first and last names in the other rows—appears because Kellsey has no first name. You can use TRIM() to remove this leading space. Change the concatenation expres- sion in Listing 5.8 to: TRIM(au_fname || ‘ ‘ || au_lname) ■ In Microsoft Access, the trimming functions are LTrim(string) to trim leading spaces, RTrim(string) to trailing spaces, and Trim(string) to trim both leading and trailing spaces. Use the Replace(string, find, replacement [, start[, count[, compare]]]) function to trim nonspace characters (actually, to replace nonspaces with empty strings). Use + to concate- nate strings. To run Listings 5.17 and 5.18, change the trim expressions to (Listing 5.17): ‘<’ + ‘ AAA ‘ + ‘>’ ‘<’ + LTRIM( ‘ AAA ‘) + ‘>’ ‘<’ + RTRIM( ‘ AAA ‘) + ‘>’ ‘<’ + TRIM(‘ AAA ‘) + ‘>’ and (Listing 5.18): Replace(au_lname, ‘H’, ‘’, 1, 1) 145 Operators and Functions Trimming Characters with TRIM() In Microsoft SQL Server, the trimming functions are LTRIM(string) to trim leading spaces and RTRIM(string) to trim trailing spaces. Use + to concatenate strings. To run Listing 5.17, change the trim expressions to: ‘<’ + ‘ AAA ‘ + ‘>’ ‘<’ + LTRIM(‘ AAA ‘) + ‘>’ ‘<’ + RTRIM(‘ AAA ‘) + ‘>’ ‘<’ + LTRIM(RTRIM(‘ AAA ‘)) + ‘>’ SQL Server’s LTRIM() and RTRIM() functions remove spaces but not arbitrary trim_chars characters. You can nest and chain SQL Server’s CHARINDEX() , LEN() , PATINDEX() , REPLACE() , STUFF() , SUBSTRING() , and other character functions to replicate arbitrary- character trimming. To run Listing 5.18, change the trim expression to: REPLACE( ➝ SUBSTRING(au_lname, 1, 1),’H’,’’) ➝ + SUBSTRING(au_lname, 2, ➝ LEN(au_lname)) To run Listing 5.19, change the trim expres- sion to: LTRIM(RTRIM(title_id)) LIKE ‘T1_’ In Oracle, add the clause FROM DUAL to run Listing 5.17; see the DBMS Tip in “Creating Derived Columns” earlier in this chapter. Oracle forbids multiple characters in trim_chars. In DB2, the trimming functions are LTRIM(string) to trim leading spaces and RTRIM(string) to trim trailing spaces. To run Listing 5.17, change the trim expressions: ‘<’ || ‘ AAA ‘ || ‘>’ ‘<’ || LTRIM(‘ AAA ‘) || ‘>’ ‘<’ || RTRIM(‘ AAA ‘) || ‘>’ ‘<’ || LTRIM(RTRIM(‘ AAA ‘)) || ‘>’ You also must add the clause FROM SYSIBM.SYSDUMMY1 to Listing 5.17; see the DBMS Tip in “Creating Derived Columns” earlier in this chapter. You can nest and chain DB2’s LENGTH() , LOCATE() , POSSTR() , REPLACE() , SUBSTR() , and other character functions to replicate arbitrary-character trimming. To run Listing 5.18, change the trim expression to: REPLACE( ➝ SUBSTR(au_lname, 1, 1),’H’,’’) ➝ || SUBSTR(au_lname, 2, ➝ LENGTH(au_lname)) To run Listing 5.19, change the trim expression to: LTRIM(RTRIM(title_id)) LIKE ‘T1_’ In MySQL, use CONCAT() to run Listing 5.17 (see “Concatenating Strings with || ” earlier in this chapter). Change the concatenation expressions to: CONCAT(‘<’,’ AAA ‘,’>’) CONCAT(‘<’, ➝ TRIM(LEADING FROM ‘ AAA ‘), ➝ ’>’) CONCAT(‘<’, ➝ TRIM(TRAILING FROM ‘ AAA ‘), ➝ ’>’) CONCAT(‘<’,TRIM(‘ AAA ‘),’>’) Oracle treats an empty string as null: TRIM(NULL) returns ‘’ . See the DBMS Tip in “Nulls” in Chapter 3. Your DBMS might provide padding func- tions to add spaces or other characters to strings. The Oracle and PostgreSQL padding functions are LPAD() and RPAD() , for example. Search your DBMS documentation for character functions or string functions. 146 Chapter 5 Trimming Characters with TRIM() Finding the Length of a String with CHARACTER_LENGTH() Use the function CHARACTER_LENGTH() to return the number of characters in a string. The function’s important characteristics are: ◆ CHARACTER_LENGTH() returns an integer greater than or equal to zero. ◆ CHARACTER_LENGTH() counts characters, not bytes. A multibyte or Unicode char- acter represents one character. (To count bytes, see the Tips in this section.) ◆ The length of an empty string ( ‘’ ) is zero. ◆ If its argument is null, CHARACTER_LENGTH() returns null. (But see the Oracle excep- tion in the DBMS Tip in this section.) To find the length of a string: ◆ Type: CHARACTER_LENGTH(string) string is a string expression such as a column that contains character strings, a string literal, or the result of an opera- tion or function that returns a string (Listings 5.20 and 5.21, Figures 5.20 and 5.21). 147 Operators and Functions Finding the Length of a String Listing 5.20 List the lengths of the authors’ first names. See Figure 5.20 for the result. SELECT au_fname, CHARACTER_LENGTH(au_fname) AS "Len" FROM authors; Listing au_fname Len Sarah 5 Wendy 5 Hallie 6 Klee 4 Christian 9 0 Paddy 5 Figure 5.20 Result of Listing 5.20. Listing 5.21 List the books whose titles contain fewer than 30 characters, sorted by ascending title length. See Figure 5.21 for the result. SELECT title_name, CHARACTER_LENGTH(title_name) AS "Len" FROM titles WHERE CHARACTER_LENGTH(title_name) < 30 ORDER BY CHARACTER_LENGTH(title_name) ASC; Listing title_name Len 1977! 5 Kiss My Boo-Boo 15 How About Never? 16 I Blame My Mother 17 Exchange of Platitudes 22 200 Years of German Humor 25 Spontaneous, Not Annoying 25 But I Did It Unconsciously 26 Not Without My Faberge Egg 26 Just Wait Until After School 28 Ask Your System Administrator 29 Figure 5.21 Result of Listing 5.21. ✔ Tips ■ You can use CHARACTER_LENGTH() in SELECT , WHERE , and ORDER BY clauses or anywhere an expression is allowed. ■ CHARACTER_LENGTH and CHAR_LENGTH are synonyms. ■ SQL also defines the BIT_LENGTH() and OCTET_LENGTH() functions. BIT_LENGTH(expr) returns the number of bits in an expression; BIT_LENGTH(B’01001011’) returns 8. OCTET_LENGTH(expr) returns the number of bytes in an expression; OCTET_LENGTH(B’01001011’) returns 1, and OCTET_LENGTH(‘ABC’) returns 3. Octet length equals bit-length/8 (rounded up to the nearest integer, if necessary). See the DBMS Tip in this section for information about DBMS bit- and byte-length functions. ■ In Microsoft Access and Microsoft SQL Server, the string-length function is LEN(string) . To run Listings 5.20 and 5.21, change the length expressions to (Listing 5.20): LEN(au_fname) and (Listing 5.21): LEN(title_name) In Oracle and DB2, the string-length function is LENGTH(string) . To run Listings 5.20 and 5.21, change the length expressions to (Listing 5.20): LENGTH(au_fname) and (Listing 5.21): LENGTH(title_name) Bit- and byte-count functions vary by DBMS. Microsoft Access has Len() . Microsoft SQL Server has DATALENGTH() . Oracle has LENGTHB() . DB2 has LENGTH() . MySQL has BIT_COUNT() and OCTET_ LENGTH() . PostgreSQL has BIT_LENGTH() and OCTET_LENGTH() . Oracle treats an empty string as null: LENGTH(‘’) returns NULL . Figure 5.20 will show 1 (not 0) in the next-to-last row because the author’s first name is ‘ ‘ (a space) in the Oracle database. For more information, see the DBMS Tip in “Nulls” in Chapter 3. 148 Chapter 5 Finding the Length of a String Finding Substrings with POSITION() Use the function POSITION() to locate a par- ticular substring within a given string. The function’s important characteristics are: ◆ POSITION() returns an integer (*0) that indicates the starting position of a sub- string’s first occurrence within a string. ◆ If the string doesn’t contain the sub- string, POSITION() returns zero. ◆ String comparisons are case insensitive or case sensitive, depending on your DBMS; see the DBMS Tip in “Filtering Rows with WHERE ” in Chapter 4. ◆ The position of any substring within an empty string ( ‘’ ) is zero. (But see the Oracle exception in the DBMS Tip in this section.) ◆ If any argument is null, POSITION() returns null. 149 Operators and Functions Finding Substrings with POSITION() . Microsoft Access has Len() . Microsoft SQL Server has DATALENGTH() . Oracle has LENGTHB() . DB2 has LENGTH() . MySQL has BIT_COUNT() and OCTET_ LENGTH() . PostgreSQL has BIT_LENGTH() and OCTET_LENGTH() . Oracle. ‘>’ ‘<’ + LTRIM(RTRIM(‘ AAA ‘)) + ‘>’ SQL Server’s LTRIM() and RTRIM() functions remove spaces but not arbitrary trim_chars characters. You can nest and chain SQL Server’s CHARINDEX() , LEN() , PATINDEX() , REPLACE() , STUFF() , SUBSTRING() ,. 2, ➝ LENGTH(au_lname)) To run Listing 5.19, change the trim expression to: LTRIM(RTRIM(title_id)) LIKE ‘T1_’ In MySQL, use CONCAT() to run Listing 5.17 (see “Concatenating Strings with || ” earlier in this chapter).

Ngày đăng: 05/07/2014, 05:20

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

  • Đang cập nhật ...

TÀI LIỆU LIÊN QUAN