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

SQL VISUAL QUICKSTART GUIDE- P37 ppt

10 233 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 179,43 KB

Nội dung

If you don’t name a constraint explicitly, your DBMS will generate a name and assign it to the constraint quietly and automatically. System-assigned names often contain strings of random characters and are cumbersome to use, so use the CONSTRAINT clause to assign your own name instead. Constraint names also appear in warnings, error messages, and logs, which is another good reason to name constraints yourself. To name a constraint: ◆ Preceding a constraint definition, type: CONSTRAINT constraint_name constraint_name is the name of the constraint and is a valid SQL identifier. Constraints names must be unique within a table. 340 Chapter 11 Understanding Constraints Creating a New Table with CREATE TABLE This section describes how to create a new table by using a minimal CREATE TABLE statement. Subsequent sections show you how to add column and table constraints to CREATE TABLE . To create a new table: ◆ Type: CREATE TABLE table ( column1 data_type1, column2 data_type2, columnN data_typeN ); table is the name of the new table to create. column1, column2, …, columnN are the names of the columns in table. You must create at least one column. data_type1, data_type2, …, data_typeN specify the SQL data type of each corre- sponding column. A data type can specify a length, scale, or precision, where applicable; see “Data Types” and subsequent sections in Chapter 3. The table name must be unique within the database, and each column name must be unique within the table. Listing 11.1 creates the sample-database table titles . Listing 11.2 creates the sample-database table title_authors . 341 Creating, Altering, and Dropping Tables Creating a New Table with CREATE TABLE Listing 11.1 Create the sample-database table titles . CREATE TABLE titles ( title_id CHAR(3) , title_name VARCHAR(40) , type VARCHAR(10) , pub_id CHAR(3) , pages INTEGER , price DECIMAL(5,2), sales INTEGER , pubdate DATE , contract SMALLINT ); Listing Listing 11.2 Create the sample-database table title_authors . CREATE TABLE title_authors ( title_id CHAR(3) , au_id CHAR(3) , au_order SMALLINT , royalty_share DECIMAL(5,2) ); Listing ✔ Tips ■ To see the result of a CREATE TABLE statement, examine the table’s structure by using one of the commands described in “Displaying Table Definitions” in Chapter 10. ■ Your DBMS will generate an error if you try to create a table with a name that already exists in the database. To prevent you from overwriting a table accidentally, SQL requires that you destroy a table explicitly with DROP TABLE before creating a new table with the same name; see “Dropping a Table with DROP TABLE ” later in this chapter. ■ A newly created table is empty (has zero rows). To populate the table with data, use the INSERT statement; see “Inserting Rows with INSERT ” in Chapter 10. ■ Columns allow nulls by default. If you don’t want to allow nulls, see “Forbidding Nulls with NOT NULL ” later in this chapter. ■ To modify the structure of an existing table, see “Altering a Table with ALTER TABLE ” later in this chapter. ■ To create a table by using the struc- ture and data of an existing table, see “Creating a New Table from an Existing One with CREATE TABLE AS ” later in this chapter. ■ Microsoft SQL Server doesn’t support the data type DATE . To run Listing 11.1, change the data type of the column pubdate to DATETIME . MySQL might change the type of a CHAR or VARCHAR column silently when creating a table. VARCHAR columns with a length less than four are changed to CHAR , for example. 342 Chapter 11 Creating a New Table with CREATE TABLE Forbidding Nulls with NOT NULL A column’s nullability determines whether its rows can contain nulls—that is, whether values are required or optional in the col- umn. I described nulls and their effects in “Nulls” in Chapter 3, but I’ll review the basics here: ◆ A null is not a value but a marker that means no value has been entered. ◆ A null represents a missing, unknown, or inapplicable value. A null in the col- umn 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. ◆ A null isn’t the same as zero (0), a blank, or an empty string ( ‘’ ). ◆ Nulls belong to no data type and can be inserted into any column that allows nulls. ◆ In SQL statements, the keyword NULL represents a null. When you’re defining a nullability constraint, some important considerations are: ◆ A nullability constraint always is a column constraint and not a table constraint; see “Understanding Constraints” earlier in this chapter. ◆ You define a nullability constraint by using the keywords NOT NULL in a CREATE TABLE column definition. ◆ In general, avoid allowing nulls because they complicate queries, insertions, and updates. ◆ Forbidding nulls in a column can help maintain data integrity by ensuring that users entering data must enter a value in the column. The DBMS won’t insert or update a row if a non-nullable column contains a null. ◆ Some other constraints, such as a PRIMARY KEY constraint, can’t be used with nullable columns. ◆ Nulls affect referential-integrity checks in foreign keys; see “Specifying a Foreign Key with FOREIGN KEY ” later in this chapter. ◆ If you INSERT a row but include no value for a column that allows null values, your DBMS supplies a null (unless a DEFAULT clause exists); see “Inserting Rows with INSERT ” in Chapter 10 and “Specifying a Default Value with DEFAULT ” later in this chapter. ◆ A user can enter NULL explicitly in a nullable column, no matter what data type or default value the column has. ◆ If you don’t specify a NOT NULL constraint, the column accepts nulls by default. 343 Creating, Altering, and Dropping Tables Forbidding Nulls with NOT NULL To specify a column’s nullability: ◆ Add the following column constraint to a CREATE TABLE column definition: [CONSTRAINT constraint_name] NOT NULL NOT NULL forbids nulls in a column. If the nullability constraint is omitted, the column accepts nulls. For the general syntax of CREATE TABLE , see “Creating Tables” earlier in this chapter. The CONSTRAINT clause is optional, and constraint_name is the name of the column’s nullability constraint; see “Understanding Constraints” earlier in this chapter. Listing 11.3 creates the sample-database table authors , forbidding nulls in some columns. Missing addresses and telephone numbers are common, so I’ve allowed nulls in those columns. Notice that I’ve forbidden nulls in both the first-name and last-name columns. If the author’s name has only a single word (like author A06, Kellsey), I’ll insert the name into au_lname and insert an empty string ( ‘’ ) into au_fname . Or I could have allowed nulls in au_fname and inserted a null into au_fname for one-named authors. Or I could have allowed nulls in both au_fname and au_lname and added a check constraint that required at least one of the two columns to contain a non-null, non-empty string. The database designer makes these types of decisions before creating a table. Most DBMSs let you specify only the NULL keyword (without the NOT ) to allow nulls. Listing 11.4 creates the sample-database table titles . 344 Chapter 11 Forbidding Nulls with NOT NULL Listing 11.3 Create the sample-database table authors . Where omitted, the nullability constraint defaults to allow nulls. CREATE TABLE authors ( au_id CHAR(3) NOT NULL, au_fname VARCHAR(15) NOT NULL, au_lname VARCHAR(15) NOT NULL, phone VARCHAR(12) , address VARCHAR(20) , city VARCHAR(15) , state CHAR(2) , zip CHAR(5) ); Listing Listing 11.4 Create the sample-database table titles and assign nullability constraints to each column explicitly. CREATE TABLE titles ( title_id CHAR(3) NOT NULL, title_name VARCHAR(40) NOT NULL, type VARCHAR(10) NULL , pub_id CHAR(3) NOT NULL, pages INTEGER NULL , price DECIMAL(5,2) NULL , sales INTEGER NULL , pubdate DATE NULL , contract SMALLINT NOT NULL ); Listing ✔ Tips ■ To see the result of a CREATE TABLE statement, examine the table’s structure by using one of the commands described in “Displaying Table Definitions” in Chapter 10. ■ When you insert a row into a table, you must provide values explicitly for columns that prohibit nulls (and have no default value). For the table authors created by Listing 11.3, for example, the minimal INSERT statement looks like this: INSERT INTO authors( au_id, au_fname, au_lname) VALUES( ‘A08’, ‘Michael’, ‘Polk’); The DBMS assigns nulls automatically to the columns in authors that aren’t listed in the INSERT column list ( phone , address , and so on); see “Inserting Rows with INSERT ” in Chapter 10. ■ When INSERT ing a null into a row, don’t quote the keyword NULL ; your DBMS will interpret it as the character string ‘NULL’ rather than as a null. ■ See also “Testing for Nulls with IS NULL ” in Chapter 4, and “Checking for Nulls with COALESCE() ” and “Comparing Expressions with NULLIF() ” in Chapter 5. ■ Microsoft SQL Server doesn’t support the data type DATE . To run Listing 11.4, change the data type of the column pubdate to DATETIME . Oracle treats an empty string ( ‘’ ) as null; see the DBMS Tip in “Nulls” in Chapter 3. DB2 doesn’t accept a stand-alone NULL keyword (without a NOT ) in a nullability constraint. To run Listing 11.4, omit each nullability constraint that isn’t NOT NULL . DB2 and MySQL don’t accept named NOT NULL constraints. Omit the clause CONSTRAINT constraint_name from NOT NULL column definitions. Nullability constraints for the DBMSs covered in this book are optional (and allow nulls by default), but other DBMSs might behave differently. For all DBMSs, check the documenta- tion to see how your DBMS handles nullability constraints for columns whose data type generates a unique row identifier automatically; see “Other Data Types” in Chapter 3. 345 Creating, Altering, and Dropping Tables Forbidding Nulls with NOT NULL Specifying a Default Value with DEFAULT A default specifies a value that your DBMS assigns to a column if you omit a value for the column when inserting a row; see “Inserting Rows with INSERT ” in Chapter 10. When you’re defining a default value, some important considerations are: ◆ A default applies to a single column. ◆ You define a default by using the keyword DEFAULT in a CREATE TABLE column definition. ◆ A default value can be any expression that evaluates to a constant. ◆ The default must have the same data type or must be implicitly convertible to the same type as its column; see “Converting Data Types with CAST() ” in Chapter 5. ◆ The column must be long enough to hold the default value. ◆ If you INSERT a row without specifying a value for a column, that column’s default is used. If the column definition has no DEFAULT , the default is null. ◆ If a column has no DEFAULT and is declared NOT NULL , you should specify the column’s value explicitly when you INSERT a row (see “Inserting Rows with INSERT ” in Chapter 10). If you omit an explicit value in this situation, some DBMSs will refuse to INSERT the row, whereas others will assign a default automatically based on the column’s date type. MySQL, for example, assigns a default value of zero to numeric, non-nullable columns with- out explicit defaults. 346 Chapter 11 Specifying a Default Value with DEFAULT To specify a column’s default value: ◆ Add the following clause to a CREATE TABLE column definition: DEFAULT expr expr is an expression that evaluates to a constant, such as a literal, a built-in function, a mathematical expression, or NULL . If no default is specified, NULL is assumed. For the general syntax of CREATE TABLE , see “Creating Tables” earlier in this chapter. Listing 11.5 assigns defaults to some of the columns in the sample-database table titles . The columns title_id and pub_id are NOT NULL and have no default values, so you must provide explicit values for them in an INSERT statement. The pages clause DEFAULT NULL is equivalent to omitting the DEFAULT . The pubdate and contract defaults show that the defaults can be expres- sions more complex than plain literals. Listing 11.6 shows the minimal INSERT statement that you can use to insert a row into the table titles (as created by Listing 11.5). Figure 11.1 shows the inserted row, with default values high- lighted. The title_name default, an empty string ( ‘’ ), is invisible. 347 Creating, Altering, and Dropping Tables Specifying a Default Value with DEFAULT Listing 11.5 Set default values for some of the columns in the sample-database table titles . CREATE TABLE titles ( title_id CHAR(3) NOT NULL , title_name VARCHAR(40) NOT NULL DEFAULT '' , type VARCHAR(10) DEFAULT 'undefined' , pub_id CHAR(3) NOT NULL , pages INTEGER DEFAULT NULL , price DECIMAL(5,2) NOT NULL DEFAULT 0.00 , sales INTEGER , pubdate DATE DEFAULT CURRENT_DATE, contract SMALLINT NOT NULL DEFAULT (3*7)-21 ); Listing Listing 11.6 The DBMS inserts default values into columns omitted from this INSERT statement. Where no default is specified, the DBMS inserts a null. See Figure 11.1 for the result. INSERT INTO titles(title_id, pub_id) VALUES('T14','P01'); Listing title_id title_name type pub_id pages price sales pubdate contract T14 undefined P01 NULL 0.00 NULL 2005-02-21 0 Figure 11.1 Listing 11.6 inserts this row into the table titles . ✔ Tips ■ To see the result of a CREATE TABLE statement, examine the table’s structure by using one of the commands described in “Displaying Table Definitions” in Chapter 10. ■ Microsoft Access doesn’t allow arithmetic expressions in a DEFAULT clause; use a numeric literal. Use Date() instead of CURRENT_DATE to return the system date. (See the DBMS Tip in “Getting the Current Date and Time” in Chapter 5.) To run Listing 11.5, change the default clause of the column pubdate to DEFAULT Date() and the default clause of the column contract to DEFAULT 0 . Microsoft SQL Server doesn’t support the data type DATE ; use DATETIME instead. Use GETDATE() instead of CURRENT_DATE to return the system date; see the DBMS Tip in “Getting the Current Date and Time” in Chapter 5. To run Listing 11.5, change the pubdate column’s data type to DATETIME , and change its default clause to DEFAULT GETDATE() . 348 Chapter 11 Specifying a Default Value with DEFAULT In Oracle, the DEFAULT clause follows the data type and precedes all column constraints, including the nullability constraint. Oracle 9i and later versions support CURRENT_DATE ; use SYSDATE instead of CURRENT_DATE in Oracle 8i and earlier; see the DBMS Tip in “Getting the Current Date and Time” in Chapter 5. Oracle treats an empty string ( ‘’ ) as null, so I’ve changed the title_name default to a space character ( ‘ ‘ ); see the DBMS Tip in “Nulls” in Chapter 3. See Listing 11.7 for the Oracle version of Listing 11.5. DB2 doesn’t support arithmetic expressions as default values. To run Listing 11.5, change the default clause of the column contract to DEFAULT 0 . In MySQL, a default value must be a literal and not a function or expression. This restric- tion means that you can’t set the default of a date column to CURRENT_DATE . To run Listing 11.5, delete the default clause of the column pubdate (or change the default expression to a datetime literal), and change the default clause of the column contract to DEFAULT 0 . (Exception: You can specify CURRENT_TIMESTAMP as the default for a TIMESTAMP column.) For all DBMSs, check the documentation to see how your DBMS handles default clauses for columns whose data type gener- ates a unique row identifier automatically; see “Other Data Types” in Chapter 3. 349 Creating, Altering, and Dropping Tables Specifying a Default Value with DEFAULT Listing 11.7 In Oracle, the default clause must come before all column constraints. CREATE TABLE titles ( title_id CHAR(3) NOT NULL, title_name VARCHAR(40) DEFAULT ' ' NOT NULL, type VARCHAR(10) DEFAULT 'undefined' , pub_id CHAR(3) NOT NULL, pages INTEGER DEFAULT NULL , price DECIMAL(5,2) DEFAULT 0.00 NOT NULL, sales INTEGER , pubdate DATE DEFAULT SYSDATE , contract SMALLINT DEFAULT (3*7)-21 NOT NULL ); Listing . later in this chapter. ■ Microsoft SQL Server doesn’t support the data type DATE . To run Listing 11.1, change the data type of the column pubdate to DATETIME . MySQL might change the type of a. in table. You must create at least one column. data_type1, data_type2, …, data_typeN specify the SQL data type of each corre- sponding column. A data type can specify a length, scale, or precision, where. name that already exists in the database. To prevent you from overwriting a table accidentally, SQL requires that you destroy a table explicitly with DROP TABLE before creating a new table with

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

TỪ KHÓA LIÊN QUAN

w