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

SQL VISUAL QUICKSTART GUIDE- P11 docx

10 289 0

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

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 202,87 KB

Nội dung

Interval Types DBMS conformance to standard SQL interval types is spotty or non- existent, so you might not find this section to be useful in practice. DBMSs have their own extended data types and functions that calculate intervals and perform date and time arithmetic. Use interval data types to represent sets of time values or spans of time. An interval value has these characteristics: ◆ It stores the quantity of time between two datetime values. Between 09:00 and 13:30 is an interval of 04:30 (4 hours and 30 minutes), for example. If you subtract two datetime values, you get an interval. ◆ It can be used to increment or decre- ment a datetime value; see “Performing Datetime and Interval Arithmetic” in Chapter 5. ◆ It has the same fields as datetime values ( YEAR , HOUR , SECOND , and so on), but the number can have a + (forward) or – (backward) sign to indicate a direction in time. The field separators are the same as for datetime values. ◆ It comes in two categories: year-month intervals and day-time intervals. A year- month interval expresses an interval as years and a whole number of months. A day-time interval expresses an interval as days, hours, minutes, and seconds. ◆ It has a single-field or multiple-field qualifier. A single-field qualifier is speci- fied as YEAR , MONTH , DAY , HOUR , MINUTE , or SECOND . A multiple-field qualifier is specified as: start_field TO end_field start_ field is YEAR , DAY , HOUR , or MINUTE , and end_ field is YEAR , MONTH , DAY , HOUR , MINUTE , or SECOND . end_ field must be a smaller time period than start_ field. A single-field column defined as INTERVAL HOUR could store intervals such as “4 hours” or “25 hours,” for example. A multiple- field column defined as INTERVAL DAY TO MINUTE could store intervals such as “2 days, 5 hours, 10 minutes,” for example. 80 Chapter 3 Interval Types Table 3.16 Interval Types Type Description Year-month These intervals contain only a year value, only a month value, or both. The valid column types are INTERVAL YEAR , INTERVAL YEAR( precision ) , INTERVAL MONTH , INTERVAL MONTH( precision ) , INTERVAL YEAR TO MONTH , or INTERVAL YEAR( precision ) TO MONTH . Day-time These intervals can contain a day value, hour value, minute value, second value, or some combination thereof. Some examples of the valid column types are INTERVAL MINUTE , INTERVAL DAY( precision ) , INTERVAL DAY TO HOUR , INTERVAL DAY( precision ) TO SECOND , and INTERVAL MINUTE( precision ) TO SECOND( frac_precision ) . ◆ A single-field column can have a precision that specifies the length (number of posi- tions) of the field; INTERVAL HOUR(2) , for example. The precision defaults to 2 if omitted. A SECOND field can have an addi- tional fractional precision that specifies the number of digits to the right of the decimal point— INTERVAL SECOND(5,2) , for example. The fractional precision defaults to 6 if omitted. A multiple-field column can have a pre- cision for start_ field but not end_ field (unless end_ field is SECOND , in which case it can have a fractional precision)— INTERVAL DAY(3) TO MINUTE and INTERVAL MINUTE(2) TO SECOND(4) , for example. ◆ It’s one of the types listed in Table 3.16. ✔ Tips ■ An interval literal is the word INTERVAL followed by a space, followed by an inter- val value surrounded by single quotes— INTERVAL ‘15-3’ (15 years and 3 months) and INTERVAL ‘22:06:5.5’ (22 hours, 6 minutes, and 5.5 seconds), for example. ■ An interval literal is the word INTERVAL followed by a space, followed by an interval value surrounded by single quotes, fol- lowed by the interval qualifier— INTERVAL ‘15-3’ YEAR TO MONTH (15 years and 3 months) and INTERVAL ‘22:06:5.5’ HOUR TO SECOND (22 hours, 6 minutes, and 5.5 seconds), for example. ■ See also “Working with Dates” in Chapter 15. ■ Table 3.17 lists interval and similar types for the DBMSs. See the DBMS documentation for size limits and usage restrictions. 81 SQL Basics Interval Types Table 3.17 DBMS Interval Types DBMS Types Access Not supported SQL Server Not supported Oracle interval year to month , interval day to second DB2 Not supported MySQL Not supported PostgreSQL interval Unique Identifiers Unique identifiers are used to generate primary-key values to identify rows (see “Primary Keys” in Chapter 2). An identifier can be unique universally (large random numbers unique in any context) or only within a specific table (simple serial numbers 1, 2, 3, …). Table 3.18 lists unique-identifier types and attributes for the DBMSs. See the DBMS documentation for size limits and usage restrictions. The SQL standard calls columns with auto-incrementing values identity columns. See also “Generating Sequences” in Chapter 15. 82 Chapter 3 Unique Identifiers Table 3.18 Unique Identifiers Platform Type or Attribute Standard SQL IDENTITY Access autonumber , replication id SQL Server uniqueidentifier , identity Oracle rowid , urowid , sequences DB2 Identity columns and sequences MySQL auto_increment attribute PostgreSQL serial , bigserial , uuid UUIDs A universally unique ID is called a Universally Unique Identifier (UUID) or a Globally Unique Identifier (GUID). When you define a column to have a UUID data type, your DBMS will generate a random UUID automatically in each new row, probably according to ISO/IEC 9834-8:2005 ( www.itu.int/ITU-T/studygroups/com17/oid.html ) or IETF RFC 4122 ( http:// tools.ietf.org/html/rfc4122 ). A UUID in standard form looks like: a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11 The letters actually are hexadecimal digits. Your DBMS might use an alternative form with uppercase hex digits, surrounding braces, or omitted hyphens. UUIDs aren’t technically guar- anteed to be unique, but the probability of generating a duplicate ID is so tiny that they should be considered singular. For more information, see http://en.wikipedia.org/wiki/ Universally_Unique_Identifier . Other Data Types The SQL standard defines other data types than the ones covered in the preceding sections, but some of them rarely are imple- mented or used in practice ( ARRAY , MULTISET , REF , and ROW , for example). More useful are the extended (nonstandard) data types that are available in various DBMSs. Depending on your DBMS, you can find data types for: ◆ Network and internet addresses ◆ Links to files stored outside the database ◆ Monetary (currency) amounts ◆ Geographic (spatial) coordinates ◆ Arrays and other collections ◆ XML ◆ Full text searching ◆ Enumerated (enum) values from a specified list 83 SQL Basics Other Data Types User-Defined Types Microsoft SQL Server, Oracle, DB2, and PostgreSQL let you create user-defined types (UDTs). The simplest UDT is a stan- dard or built-in data type ( CHARACTER , INTEGER , and so on) with additional check and other constraints. You can define the data type marital_status , for example, as a single-character CHARACTER data type that allows only the values S , M , W , D , or NULL (for single, married, widowed, divorced, or unknown). More-complex UDTs are simi- lar to classes in object-oriented program- ming languages such as Java. You can define a UDT once and use it in multiple tables, rather than repeat its definition in each table in which it’s used. Search your DBMS documentation for user-defined type. UDTs are created in standard SQL with the statement CREATE TYPE . ◆ When you sort a column that contains nulls, the nulls will be either greater than or less than all the non-null values, depending on the DBMS; see “Sorting Rows with ORDER BY ” in Chapter 4. ◆ Nulls propagate through computations. The result of any arithmetic expression or operation that involves a null is null: (12*NULL)/4 is null; see Chapter 5. ◆ Most aggregate functions, such as SUM() , AVG() , and MAX() , ignore nulls. COUNT(*) is an exception. See Chapter 6. ◆ If the grouping column in a GROUP BY clause contains nulls, all the nulls are put in a single group; see “Grouping Rows with GROUP BY ” in Chapter 6. ◆ Nulls affect the results of joins; see “Using Joins” in Chapter 7. ◆ Nulls can cause problems in subqueries; see “Nulls in Subqueries” in Chapter 8. ✔ Tips ■ Use caution when interpreting results in which nulls are involved. Nulls cause so many problems and complications—I’ve listed some of important ones here—that some database experts urge users to mini- mize their use or not use them at all (and instead use default values or some other missing-data scheme). Nevertheless, you won’t become a competent SQL pro- grammer without understanding nulls completely. ■ See also “Checking for Nulls with COALESCE ” and “Comparing Expressions with NULLIF ” in Chapter 5. ■ Nullable means that a column is allowed to contain nulls. Use the CREATE TABLE or ALTER TABLE statement (Chapter 11) to set a column’s nullability. Nulls When your data are incomplete, you can use a null to represent a missing or unknown value. A null has these characteristics: ◆ In SQL statements, the keyword NULL represents a null. ◆ A null is used for a value that might never be known, might be determined later, or is inapplicable. (Think of a null as a marker or flag for a missing value, rather than as a value itself.) ◆ A null differs from zero, a string that con- tains only spaces, or an empty string ( ‘’ ). A null in the column price doesn’t mean that an item has no price or that its price is zero; it means that the price is unknown or has not been set. (Oracle is a special case with respect to empty strings; see the DBMS Tip in this section.) ◆ Nulls can appear in columns of any data type that are not restricted by NOT NULL or PRIMARY KEY integrity constraints (Chapter 11). You should not allow nulls in alternate keys. ◆ To detect nulls, see “Testing for Nulls with IS NULL ” in Chapter 4. ◆ Nulls aren’t equal (or unequal) to each other. You can’t determine whether a null matches any other value, including another null, so the expressions NULL = any_value , NULL <> any_value , NULL = NULL , and NULL <> NULL are neither true nor false but unknown; see “Combining and Negating Conditions with AND , OR , and NOT ” in Chapter 4. ◆ Although nulls are never equal to each other, DISTINCT treats all the nulls in a particular column as duplicates; see “Eliminating Duplicate Rows with DISTINCT ” in Chapter 4. 84 Chapter 3 Nulls 85 SQL Basics Nulls ■ The term null value is inaccurate—a null indicates the lack of a value. ■ Don’t place the keyword NULL in quotes; your DBMS will interpret it as the char- acter string ‘NULL’ rather than as a null. ■ You can get a null from a column that doesn’t allow nulls. The column au_id in the table authors doesn’t allow nulls, but the SELECT statement in Figure 3.3 returns a null for the maximum au_id . ■ If nulls appear in a column because actual values are not meaningful (rather than unknown), you can split the column off into its own table with a one-to-one relationship with the other table. In Figure 3.4, the original table employees has the column commission , which speci- fies an employee’s sales commission. commission contains mostly nulls because most employees aren’t salespeople. To avoid the proliferation of nulls, I’ve moved commission to its own table. ■ The display of nulls in results varies by DBMS. A null might appear as NULL , (NULL) , <NULL> , - , or empty space, for example. Oracle treats an empty string ( ‘’ ) as a null. This treatment might not continue to be true in future releases, however, and Oracle recommends that you do not treat empty strings the same as nulls in your SQL code. This behavior can cause con- version problems among DBMSs. In the sample database, for example, the col- umn au_fname in the table authors is defined as NOT NULL . In Oracle, the first name of the author Kellsey (author A06) is a space ( ‘ ‘ ); in the other DBMSs, the first name is an empty string ( ‘’ ). For information about the sample database, see “The Sample Database” in Chapter 2. SELECT MAX(au_id) FROM authors WHERE au_lname = 'XXX'; MAX(au_id) NULL Figure 3.3 Getting a null from a column that isn’t nullable. emp_id emp_name commission E01 Eli McLemore NULL E02 Monty Wendt 0.25 E03 Damien Shaw NULL E04 Russell Sager NULL employees NULLJill StallworthE05 0.08Pamela GantE06 emp_id emp_name E01 Eli McLemore E02 Monty Wendt E03 Damien Shaw E04 Russell Sager employees Jill StallworthE05 Pamela GantE06 emp_id commission E02 0.25 E06 0.08 Russell Sager commissions Figure 3.4 Nulls are eliminated by splitting the original table (top) into a one-to-one relationship (bottom). This page intentionally left blank This chapter introduces SQL’s workhorse— the SELECT statement. Most SQL work involves retrieving and manipulating data by using this one (albeit complex) statement. SELECT retrieves rows, columns, and derived values from one or more tables in a database; its syntax is: SELECT columns FROM tables [JOIN joins] [WHERE search_condition] [GROUP BY grouping_columns] [HAVING search_condition] [ORDER BY sort_columns]; SELECT , FROM , ORDER BY , and WHERE are cov- ered in this chapter, GROUP BY and HAVING in Chapter 6, and JOIN in Chapter 7. By conven- tion, I call only a SELECT statement a query because it returns a result set. DBMS docu- mentation and other books might refer to any SQL statement as a query. Although SELECT is powerful, it’s not dangerous: You can’t use it to add, change, or delete data or database objects. (The dangerous stuff starts in Chapter 10.) 87 Retrieving Data from a Table 4 Retrieving Data from a Table ✔ Tip ■ Recall that italic_type denotes a variable in code that must be replaced with a value, and brackets indicate an optional clause or item; see “Typographic conventions” and “Syntax conventions” in the introduction. Retrieving Columns with SELECT and FROM In its simplest form, a SELECT statement retrieves columns from a table; you can retrieve one column, multiple columns, or all columns. The SELECT clause lists the columns to display, and the FROM clause specifies the table from which to draw the columns. To retrieve a column from a table: ◆ Type: SELECT column FROM table; column is a column name, and table is the name of the table that contains column (Listing 4.1 and Figure 4.1). To retrieve multiple columns from a table: ◆ Type: SELECT columns FROM table; columns is two or more comma-separated column names, and table is the name of the table that contains columns (Listing 4.2 and Figure 4.2). Columns are displayed in the same order in which they’re listed in columns, not the order in which they’re defined in table. 88 Chapter 4 Retrieving Columns with SELECT and FROM Listing 4.1 List the cities in which the authors live. See Figure 4.1 for the result. SELECT city FROM authors; Listing city Bronx Boulder San Francisco San Francisco New York Palo Alto Sarasota Figure 4.1 Result of Listing 4.1. Listing 4.2 List each author’s first name, last name, city, and state. See Figure 4.2 for the result. SELECT au_fname, au_lname, city, state FROM authors; Listing au_fname au_lname city state Sarah Buchman Bronx NY Wendy Heydemark Boulder CO Hallie Hull San Francisco CA Klee Hull San Francisco CA Christian Kells New York NY Kellsey Palo Alto CA Paddy O'Furniture Sarasota FL Figure 4.2 Result of Listing 4.2. To retrieve all columns from a table: ◆ Type: SELECT * FROM table; table is the name of a table (Listing 4.3 and Figure 4.3). Columns are displayed in the order in which they’re defined in table. 89 Retrieving Data from a Table Retrieving Columns with SELECT and FROM Listing 4.3 List all the columns in the table authors . See Figure 4.3 for the result. SELECT * FROM authors; Listing au_id au_fname au_lname phone address city state zip A01 Sarah Buchman 718-496-7223 75 West 205 St Bronx NY 10468 A02 Wendy Heydemark 303-986-7020 2922 Baseline Rd Boulder CO 80303 A03 Hallie Hull 415-549-4278 3800 Waldo Ave, #14F San Francisco CA 94123 A04 Klee Hull 415-549-4278 3800 Waldo Ave, #14F San Francisco CA 94123 A05 Christian Kells 212-771-4680 114 Horatio St New York NY 10014 A06 Kellsey 650-836-7128 390 Serra Mall Palo Alto CA 94305 A07 Paddy O'Furniture 941-925-0752 1442 Main St Sarasota FL 34236 Figure 4.3 Result of Listing 4.3. . restrictions. 81 SQL Basics Interval Types Table 3.17 DBMS Interval Types DBMS Types Access Not supported SQL Server Not supported Oracle interval year to month , interval day to second DB2 Not supported MySQL. Attribute Standard SQL IDENTITY Access autonumber , replication id SQL Server uniqueidentifier , identity Oracle rowid , urowid , sequences DB2 Identity columns and sequences MySQL auto_increment attribute PostgreSQL serial ,. searching ◆ Enumerated (enum) values from a specified list 83 SQL Basics Other Data Types User-Defined Types Microsoft SQL Server, Oracle, DB2, and PostgreSQL let you create user-defined types (UDTs). The

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