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

SQL VISUAL QUICKSTART GUIDE- P37 ppt

10 240 0
Tài liệu đã được kiểm tra trùng lặp

Đ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

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

CREATE TABLE titles title_id CHAR3 , title_name VARCHAR40 , type VARCHAR10 , pub_id CHAR3 , pages INTEGER , price DECIMAL5,2, sales INTEGER , pubdate DATE , contract SMALLINT ; Listing

Trang 1

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 CONSTRAINTclause 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

Trang 2

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

toCREATE 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

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

Trang 3

✔ 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 TABLEbefore 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 INSERTstatement; 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 pubdatetoDATETIME

MySQL might change the type of a

Trang 4

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-umnpricedoesn’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 NULLin a CREATE

TABLEcolumn 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 KEYconstraint, 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 INSERTa 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 NULLexplicitly in a nullable column, no matter what data type or default value the column has

◆ If you don’t specify a NOT NULLconstraint, the column accepts nulls by default

Trang 5

To specify a column’s nullability:

◆ Add the following column constraint to

aCREATE TABLEcolumn definition:

[CONSTRAINT constraint_name]

NOT NULL

NOT NULLforbids 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

TheCONSTRAINTclause 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_lnameand insert an empty string (‘’)

into au_fname Or I could have allowed nulls

inau_fnameand inserted a null into au_fname

for one-named authors Or I could have

allowed nulls in both au_fnameandau_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.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

Trang 6

✔ 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 INSERTstatement 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 authorsthat aren’t

listed in the INSERTcolumn list (phone,

address, and so on); see “Inserting Rows

with INSERT” in Chapter 10

■ When INSERTing 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 pubdatetoDATETIME

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 NULLconstraints Omit the clause

CONSTRAINT constraint_namefromNOT NULLcolumn 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

Trang 7

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 DEFAULTin 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 INSERTa 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 DEFAULTand is declared

NOT NULL, you should specify the column’s value explicitly when youINSERTa row (see “Inserting Rows with INSERT” in Chapter 10) If you omit an explicit value

in this situation, some DBMSs will refuse

toINSERTthe row, whereas others will assign a default automatically based on

the column’s date type MySQL, for

Trang 8

To specify a column’s default value:

◆ Add the following clause to a CREATE

TABLEcolumn definition:

DEFAULT expr

expr is an expression that evaluates to

a constant, such as a literal, a built-in

function, a mathematical expression,

orNULL 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_idandpub_id

are NOT NULLand have no default values, so you must provide explicit values for them

in an INSERTstatement The pagesclause

DEFAULT NULLis equivalent to omitting the DEFAULT The pubdateandcontract

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_namedefault, an empty string (‘’), is invisible

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

Trang 9

✔ 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

DEFAULTclause; use a numeric literal Use

Date()instead of CURRENT_DATEto 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

toDEFAULT Date()and the default clause

of the column contracttoDEFAULT 0

Microsoft SQL Server doesn’t support

the data type DATE; use DATETIMEinstead 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 pubdatecolumn’s data type to

DATETIME, and change its default clause

toDEFAULT GETDATE()

Trang 10

In Oracle, the DEFAULTclause follows the

data type and precedes all column constraints,

including the nullability constraint Oracle 9i

and later versions support CURRENT_DATE; use

SYSDATEinstead of CURRENT_DATEin 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_namedefault 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 contractto

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 columnpubdate(or change the default expression to a datetime literal), and change the default clause of the column contract

toDEFAULT 0 (Exception: You can specify

CURRENT_TIMESTAMPas the default for a

TIMESTAMPcolumn.)

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

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

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

TỪ KHÓA LIÊN QUAN

w