Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 75 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
75
Dung lượng
2,11 MB
Nội dung
Managing Datafiles 151 Managing Datafiles If you are not using OMF, you will need to manage datafiles yourself. The database will create or reuse one or more datafiles in the sizes and locations that you specify whenever you create a tablespace. A datafile belongs to only one tablespace and only one database at a time. Temp files are a special variety of datafile that are used in temporary tablespaces. When the database creates or reuses a datafile, the operating system file is allocated and initialized—filled with a regular pat- tern of mostly binary zeros. This initialization will not occur with temp files. Operations that you may need to perform on datafiles include the following: Resizing them Taking them offline or online Moving (renaming) them Recovering them A useful technique for managing disk space used by datafiles is to enable AUTOEXTEND, which tells the database to automatically enlarge a datafile when the tablespace runs out of free space. The AUTOEXTEND attributes apply to individual datafiles and not to the tablespace. To resize a datafile manually, use the ALTER DATABASE DATAFILE statement, like this: ALTER DATABASE DATAFILE 'C:\ORACLE\ORADATA\ORA10\DATA01.DBF' RESIZE 2000M; To configure a datafile to automatically enlarge as needed by adding 100MB at a time up to a maximum of 8,000MB, execute the following: ALTER DATABASE DATAFILE 'C:\ORACLE\ORADATA\ORA10\DATA01.DBF' AUTOEXTEND ON NEXT 100M MAXSIZE 8000M; Even if you do not plan to manage disk space using AUTOEXTEND, consider enabling it on your datafiles to avoid out-of-space failures in your applications. To relocate a datafile, take it offline, move it using an operating system command, rename it, recover it (sync the file header with the rest of the database), and then bring it back online. Here is an example: 1. Take it offline: ALTER DATABASE DATAFILE 'C:\ORACLE\DATA02.DBF' OFFLINE; 2. Copy it: HOST COPY C:\ORACLE\DATA02.DBF C:\ORACLE\ORADATA\ORA10\DATA02.DBF 4367.book Page 151 Wednesday, October 13, 2004 1:18 PM 152 Chapter 3 Database Storage and Schema Objects 3. Change the filename in the control files: ALTER DATABASE RENAME FILE 'C:\ORACLE\DATA02.DBF' TO 'C:\ORACLE\ORADATA\ORA10\DATA02.DBF'; 4. Sync the file header with the database: RECOVER DATAFILE 'C:\ORACLE\ORADATA\ORA10\DATA02.DBF'; 5. Bring it back online so it can be used. ALTER DATABASE DATAFILE 'C:\ORACLE\ORADATA\ORA10\DATA02.DBF' ONLINE; Working with Schema Objects A schema is collection of database objects owned by a specific database user. In an Oracle10g database, the schema has the same name as the database user, so the two terms are synonymous. Schema objects include the segments (tables, indexes, and so on) you have seen in tablespaces as well as nonsegment database objects owned by a user. These nonsegment objects include con- straints, views, synonyms, procedures, and packages. Database objects that are not owned by one user and thus are not schema objects include roles, tablespaces, and directories. In this section, you will learn about the built-in datatypes that Oracle provides for use in your tables, how to create and manage tables, how to implement business rules as constraints on your tables, and how to improve the performance of your tables with indexes. Finally, we will briefly cover other schema objects that you can use in your applications. Specifying Datatypes Oracle10g has several built-in datatypes that you can use in your tables. These datatypes fall into six major categories: Character Numeric Datetime LOB (Large Object) ROWID Binary Oracle 10g supports additional datatypes, but we will focus on these six major categories. 4367.book Page 152 Wednesday, October 13, 2004 1:18 PM Working with Schema Objects 153 Character Datatypes Character datatypes store alphanumeric data in the database character set or the Unicode char- acter set. The database character set is specified when the database is created and indicates which languages can be represented in the database. The US7ASCII character set supports the English language as well as any other language that uses a subset of the English alphabet. The WE8ISO8859P1 character set supports several European languages, including English, French, German, and Spanish. The Unicode character set AL16UTF16 is intended to concurrently sup- port every known language, although there are a few not yet included, such as Egyptian hiero- glyphs and cuneiform. The database character datatypes are as follows: CHAR(size [byte|char]), NCHAR(size) Fixed width types that always store the column- width amount of data, right padding with spaces as needed. The size specification is in bytes if you do not include the keyword char. The NCHAR variation uses the Unicode character set, and the size is always given in characters. VARCHAR(size [byte|char]), VARCHAR2(size [byte|char]), NVARCHAR2(size) Variable width types. Unlike their CHAR counterparts, the VARCHAR types store only the amount of data that is actually used. The size specification is in bytes if you do not include the keyword char. The NVARCHAR2 variation uses the Unicode character set and is always given in characters. VARCHAR and VARCHAR2 are synonymous in Oracle10g, but Oracle reserves the right to change comparison semantics of VARCHAR in future releases; so the VARCHAR2 type is preferred. LONG A legacy datatype that exists for backward compatibility. It stores variable-length alpha- numeric data up to 2GB in size. There are many restrictions on the usage of the columns of type LONG: there is a limit of one column of type LONG per table, tables containing a LONG cannot be partitioned, LONG datatypes cannot be used in subqueries, and few functions will work with LONG data. The CLOB datatype is the preferred datatype for character data larger than VARCHAR2. Here is an example of the character datatypes in use: CREATE TABLE number_samples (name VARCHAR2(48) ,country_code CHAR(2) ,address NVARCHAR2(100) ,city NVARCHAR2(64) ); Numeric Datatypes Numeric datatypes can store positive and negative fixed and floating-point numbers, zero, infinity, and the special value Not A Number. The database numeric datatypes are as follows: NUMBER[(precision[, scale])] Stores zero, positive numbers, and negative numbers. precision is the total number of digits and defaults to 38—the maximum. Scale is the number of digits to the right of the decimal point and defaults to 0. A negative scale tells the database 4367.book Page 153 Wednesday, October 13, 2004 1:18 PM 154 Chapter 3 Database Storage and Schema Objects to round off data to the left of the decimal point. scale has a valid range of –84 to 127. Table 3.1 shows how precision and scale affect the way number types are stored. BINARY_FLOAT, BINARY_DOUBLE Store single-precision and double-precision floating-point data or one of the special floating-point values listed in Table 3.2. TABLE 3.1 Precision, Scale, and Rounding Specification Actual Value Stored Value NUMBER(11,4) 12345.6789 12345.6789 NUMBER(11,2) 12345.6789 12345.68 NUMBER(11,-2) 12345.6789 12300 NUMBER(5,2) 12345.6789 Error – Precision is too small NUMBER(5,2) 123456 Error – Precision is too small TABLE 3.2 Floating-Point Constants Constant Description BINARY_FLOAT_NAN Not a number BINARY_FLOAT_INFINITY Infinite BINARY_FLOAT_MAX_NORMAL 3.40282347e+38 BINARY_FLOAT_MIN_NORMAL 1.17549435e-038 BINARY_FLOAT_MAX_SUBNORMAL 1.17549421e-038 BINARY_FLOAT_MIN_SUBNORMAL 1.40129846e-045 BINARY_DOUBLE_NAN Not a number BINARY_DOUBLE_INFINITY Infinite BINARY_DOUBLE_MAX_NORMAL 1.7976931348623157E+308 BINARY_DOUBLE_MIN_NORMAL 2.2250738585072014E-308 4367.book Page 154 Wednesday, October 13, 2004 1:18 PM Working with Schema Objects 155 Here is an example of the number datatypes in use: CREATE TABLE number_samples (id NUMBER ,cost NUMBER(11,2) ,mass BINARY_FLOAT ,velocity BINARY_DOUBLE ); Datetime Datatypes Oracle10g has several datetime datatypes that can store dates, time, and time periods: DATE Stores a date and time with a one-second granularity. The date portion can be from January 1, 4712 BCE to December 31, 9999. The time portion of a DATE datatype defaults to midnight, or 00:00:00 hours, minutes, and seconds. TIMESTAMP[(precision)] Stores a date and time with subsecond granularity. The date portion can be from January 1, 4712 BCE to December 31, 9999. precision is the number of digits of subsecond granularity. precision defaults to 6 and can range from 0 to 9. TIMESTAMP[(precision)] WITH TIMEZONE Extends the TIMESTAMP datatype by also stor- ing a time zone offset. This time zone offset defines the difference (in hours and minutes) from the local time zone and UTC (Coordinated Universal Time, also known as Greenwich mean time or GMT). Like TIMESTAMP, precision defaults to 6 and can range from 0 to 9. Two TIMESTAMP WITH TIMEZONE values are considered equal if they represent the same chronolog- ical time. For example, 10:00AM EST is equal to 9:00AM CST or 15:00 UTC. TIMESTAMP[(precision)] WITH LOCAL TIMEZONE Extends the TIMESTAMP datatype by also storing a time zone offset. The TIMESTAMP WITH LOCAL TIMEZONE datatype does not store the time zone offset with the column data. Instead, the timestamp value is converted from the local time to the database time zone. Likewise, when data is retrieved, it is con- verted from the database time zone to the local time zone. Like TIMESTAMP, precision defaults to 6 and can range from 0 to 9. INTERVAL YEAR[(precision)] TO MONTH Stores a period of time in years and months. precision is the maximum number of digits needed for the year portion of this period, with BINARY_DOUBLE_MAX_SUBNORMAL 2.2250738585072009E-308 BINARY_DOUBLE_MIN_SUBNORMAL 4.9406564584124654E-324 TABLE 3.2 Floating-Point Constants (continued) Constant Description 4367.book Page 155 Wednesday, October 13, 2004 1:18 PM 156 Chapter 3 Database Storage and Schema Objects a default of 2 and a range of 0 to 9. Use the INTERVAL YEAR TO MONTH datatype to store the difference between two datetime values if yearly or monthly granularity is needed. INTERVAL DAY[(d_precision)] TO SECOND[(s_precision)] Stores a period of time in days, hours, minutes, and seconds. d_precision is the maximum number of digits needed for the day portion of this period, with a default of 2 and a range of 0 to 9. s_precision is the number of digits to the right of the decimal point needed for the fractional seconds portion of this period, with a default of 6 and a range of 0 to 9. Use the INTERVAL DAY TO SECOND datatype to store the difference between two datetime values if granularity down to a fractional second is needed. Here is an example of the datetime datatypes in use: CREATE TABLE datetime_samples (dt DATE ,ts TIMESTAMP(3) ,ts2 TIMESTAMP ,tstz TIMESTAMP(3) WITH TIME ZONE ,tsltz TIMESTAMP WITH LOCAL TIME ZONE ,long_duration INTERVAL YEAR(4) TO MONTH ,short_duration INTERVAL DAY(3) TO SECOND(2) ); LOB Datatypes As the name implies, LOB datatypes store large objects, up to 2 32 – 1, or 4,294,967,295 data blocks. With an 8KB data block size, this comes out to about 32TB per field. LOBs are designed for text, image video, audio, and spatial data. When you create a table with LOB col- umns, you can specify a different tablespace and different attributes for the LOB data than for the rest of the table. The LOB locator, a kind of pointer, is stored inline with the row and is used to access the LOB data. The database LOB datatypes are as follows: CLOB Stores variable-length character data. NCLOB Stores variable-length character data using the Unicode character set. BLOB Stores binary variable-length data inside the database. BLOB data does not undergo char- acter set conversion when passed between databases or between client and server processes. BFILE Stores binary variable-length data outside the database. BFILEs are limited to a maxi- mum of 4GB of data and even less in some operating systems. Here is an example of the LOB datatypes in use: CREATE TABLE lob_examples ( id NUMBER , name VARCHAR2(32) , description VARCHAR2(4000) 4367.book Page 156 Wednesday, October 13, 2004 1:18 PM Working with Schema Objects 157 , definition CLOB , mp3 BLOB )TABLESPACE USERS LOB (definition) STORE AS (TABLESPACE user3_data); ROWID Datatypes ROWIDs are either physical or logical addresses that uniquely identify each row in an Oracle10g table. The database ROWID datatypes are as follows: ROWID Stores the base64-encoded physical address of any row in a heap-organized table in the database. ROWIDs incorporate the Object ID (OID), relative file number, block number, and row slot within the block. They are used internally in indexes and via the ROWID pseudocolumn in SQL. You can use ROWID datatype columns in your tables to store “row pointers” to rows in other tables. UROWID (Universal ROWID) Stores the base64-encoded string representing the logical address of a row in an index-organized table. Here is an example of the ROWID datatypes in use: CREATE TABLE rowid_samples (tab_rowid ROWID ,iot_rowid UROWID ); Binary Datatypes Oracle10g binary datatypes can be used to store unstructured data. Unlike regular character data, binary data does not undergo character set conversion when passed from database to database via a database link or export/import utility or when passed between database client and server processes. The database binary datatypes are as follows: RAW(size) Stores unstructured data up to 2000 bytes in size. LONG RAW Stores unstructured data up to 2GB in size. Like the LONG datatype, it exists to sup- port backward compatibility, and there are several restrictions on LONG RAW columns—Oracle discourages their use. Consider using the BLOB datatype instead. Here is an example of the binary datatypes in use: CREATE TABLE binary_samples (init_string RAW(2000) ,logo_image LONG RAW ); 4367.book Page 157 Wednesday, October 13, 2004 1:18 PM 158 Chapter 3 Database Storage and Schema Objects Creating Tables As you know from Chapter 1, “Installing Oracle 10g,” tables are the primary data storage con- tainers in an Oracle database. Data in a table is organized into rows and columns. Each column is named, has a specific datatype and size, such as CHAR(16), VARCHAR2(50), TIMESTAMP(6), or NUMBER. A row is a single occurrence of this set of columns. You can think of columns as fields, and you can think of rows as records. When you create a table, you must give it a name as well as specify the column names and datatypes. You can optionally specify many additional attributes, such as column default val- ues, extent sizes, which tablespace to use, and so on. Table and column names have the follow- ing requirements: Must be from 1 to 30 bytes in length. Must begin with a letter. Can include letters, numbers, the underscore symbol (_), the pound symbol (#), and the dollar symbol ($). (However, Oracle discourages the use of pound and dollar symbols in names.) Cannot be a reserved word such as NUMBER or INDEX. If the name is enclosed in double quotation marks (“ ”), the only requirement is that the name be from 1 to 30 bytes long and not contain an embedded double quotation mark. Each column name must be unique within a table, and the table name must be unique within the namespace for tables, views, sequences, private synonyms, procedures, functions, packages, materialized views, and user-defined types. The namespace is simply the domain of allowable names for the set of schema objects that it serves. In addition to the namespace shared by tables and views, the database has separate namespaces for each of the following: Indexes Constraints Clusters Database triggers Private database links Dimensions Roles Public synonyms Public database links Tablespaces Profiles Parameter files (PFILEs) For example, if you have a view named BOOKS, you cannot name a table BOOKS (tables and views share a namespace), although you can create an index named BOOKS (indexes and tables have sep- arate namespaces) and a constraint named BOOKS (constraints and tables have separate namespaces). In the following sections, you will see how to create and manage tables. 4367.book Page 158 Wednesday, October 13, 2004 1:18 PM Working with Schema Objects 159 Creating a Table To create a table, use the CREATE TABLE statement. At a minimum, you need to list the column names and datatypes for the table. Here is an example: CREATE TABLE change_log (log_id NUMBER ,who VARCHAR2(64) ,when TIMESTAMP ,what VARCHAR2(200) ); Commas delimit or separate the column definitions, which start with the column name: log_ id, who, when, and what are the columns in this example. You can add some attributes to your table definition such as the tablespace in which you want your table stored: CREATE TABLE change_log (log_id NUMBER ,who VARCHAR2(64) ,when TIMESTAMP ,what VARCHAR2(200) ) TABLESPACE users; After you create the table, you can display the structure of a table with the SQL*Plus DESCRIBE command: SQL> describe change_log Name Null? Type LOG_ID NUMBER WHO VARCHAR2(64) WHEN TIMESTAMP(6) WHAT VARCHAR2(200) Creating a Table Using a Query When you can create a table based on a query, you do not need to specify the column attributes; they are inherited from the existing schema object. Queries used in a CREATE TABLE AS SELECT statement can be on a single table, a view, or can join multiple tables. This table creation syntax is frequently identified with the abbreviation CTAS (Create Table As Select): CREATE TABLE january2004_log NOLOGGING COMPRESS TABLESPACE archives 4367.book Page 159 Wednesday, October 13, 2004 1:18 PM 160 Chapter 3 Database Storage and Schema Objects AS SELECT * FROM change_log WHERE when BETWEEN TO_DATE('01-JAN-2004','DD-Mon-YYYY’) AND TO_DATE('31-JAN-2004','DD-Mon-YYYY’); SQL> describe january2004_log Name Null? Type LOG_ID NUMBER WHO VARCHAR2(64) WHEN TIMESTAMP(6) WHAT VARCHAR2(200) The option NOLOGGING tells the database not to log the contents of the table to the redo log and not to log subsequent direct-path insert operations to the redo log. The COMPRESS option tells the database to add the data to the table using data compression, thus requiring less disk space. The TABLESPACE option tells the database where to store the table. Creating a Temporary Table You can create a temporary table whose contents are transitory and only visible to the session that inserted data into it. The definition of the table persists, but the data in a temporary table lasts only for either the duration of the transaction (ON COMMIT DELETE ROWS) or for the dura- tion of the session (ON COMMIT PRESERVE ROWS). Here is an example: CREATE GLOBAL TEMPORARY TABLE my_session (category VARCHAR2(16) ,running_count NUMBER ) ON COMMIT DELETE ROWS; Programs can manipulate data in temporary tables or join them to permanent tables in the same manner as any other table. Setting Default Values You can set default values for the columns in your table. When subsequent INSERT statements do not explicitly populate these columns, the database assigns the default value to the column. Having a default value does not ensure that the column will always have a value. An INSERT or an UPDATE statement can always explicitly set a column to NULL unless there is a NOT NULL constraint on the column. See the section “Creating Constraints” later in this chapter for more informa- tion on creating or using constraints. 4367.book Page 160 Wednesday, October 13, 2004 1:18 PM [...]... with the table’s ROWIDs In a bitmap index, a bitmap is created for each key There is a bit in each bitmap for every ROWID in the table, forming the equivalent of a two-dimensional matrix The bits are set if the corresponding row in the bitmap exists Btree indexes are the default index type, can be unique or non-unique, and are appropriate for medium- to high-cardinality columns—those having many distinct... state_bix; Managing Indexes You can perform several maintenance actions on an index, including rebuilding an index, moving it to a new tablespace, coalescing it, or renaming the index All these actions are performed with different clauses of an ALTER INDEX statement To rebuild an index, which will shrink its size and possibly reduce the Btree depth (making it more efficient), use a REBUILD clause, like... constraint Here is an example: ALTER TABLE employees ADD CONSTRAINT uniq_payroll_id UNIQUE (payroll_id) USING INDEX TABLESPACE indx EXCEPTIONS INTO exceptions; Working with PRIMARY KEY Constraints Primary keys are defined in a relational model as being the unique identifier for any tupple in an entity PRIMARY KEY constraints enforce the validity of a primary key, so a table can have only one PRIMARY... TABLE will fail B The column style will always have a value C There is no index on this table D The column style can have a NULL value 13 Which constraint-checking model is the default? A Initially immediate and deferrable B Initially immediate and not deferrable C Initially deferred and not immediately D Initially deferrable and not immediate 14 Which statement on views is true? A A view can only... at any time without prior notice and at Oracle s sole discretion Please visit Oracle s Training and Certification website (http:// www .oracle. com/education/certification/) for the most current exam objectives listing Networks have evolved from simple terminal-based systems to complex multitiered systems Today’s networks can comprise many computers on multiple operating systems using a wide variety of... subsecond granularity The timestamp datatype stores subsecond granularity, defaulting to six digits of precision 10 C Heap organized is a table that is not index organized; it is not an index type XOR is bitwise function and not an index type Bitmap is an index type, but cannot be used for a unique index Btree indexes make fine unique indexes 11 E You can rename both a constraint and an index to the same... CONSTRAINT uniq_payroll_id UNIQUE (payroll_id) USING INDEX TABLESPACE indx ; 168 Chapter 3 Database Storage and Schema Objects When adding a UNIQUE constraint to an existing table, Oracle raises an exception, and the statement fails if there are any duplicate keys (that is, violations of the constraint) To assist you in identifying any duplicates, you can specify an EXCEPTIONS INTO clause First, create... the above 16 Which allocation unit is the smallest? A Datafile B Extent C Data block D Segment Review Questions 17 Which is a valid tablespace extent management specification? A Automatic B Local C Manual D Temporary 18 Which of the following is not a valid Oracle1 0g datatype? A timestamp with local timezone B binary C blob D urowid 19 How do you specify that a temporary table will be emptied at the end... care of some high-availability maintenance actions that include staging the new version of an index using a temporary name and then in a short deployment window renaming the old and new indexes Here is an example of renaming an index: ALTER INDEX sys_c00 142 8 RENAME TO employee_pk; Working with Views Views are virtual tables consisting of a stored query A view is created with a query that incorporates... this ALTER INDEX emp_seniority REBUILD; To move an index from one tablespace to another, you specify a new tablespace in conjunction with REBUILD: ALTER INDEX uniq_payroll_id REBUILD TABLESPACE hr_indx; 1 74 Chapter 3 Database Storage and Schema Objects Coalescing an index is like a quick-and-dirty rebuild Instead of re-creating the Btree, a coalesce combines entries in nearby leaf blocks with the intent . reuses a datafile, the operating system file is allocated and initialized—filled with a regular pat- tern of mostly binary zeros. This initialization will not occur with temp files. Operations that. number BINARY_FLOAT_INFINITY Infinite BINARY_FLOAT_MAX_NORMAL 3 .40 282 347 e+38 BINARY_FLOAT_MIN_NORMAL 1.17 549 435e-038 BINARY_FLOAT_MAX_SUBNORMAL 1.17 549 421e-038 BINARY_FLOAT_MIN_SUBNORMAL 1 .40 129 846 e- 045 BINARY_DOUBLE_NAN. fails if there are any duplicate keys (that is, violations of the constraint). To assist you in identifying any duplicates, you can specify an EXCEPTIONS INTO clause. First, create an exceptions