* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download Oracle_ch3 - Gonzaga University Student Web Server
Survey
Document related concepts
Microsoft Access wikipedia , lookup
Concurrency control wikipedia , lookup
Entity–attribute–value model wikipedia , lookup
Microsoft SQL Server wikipedia , lookup
Microsoft Jet Database Engine wikipedia , lookup
Ingres (database) wikipedia , lookup
Extensible Storage Engine wikipedia , lookup
Open Database Connectivity wikipedia , lookup
Clusterpoint wikipedia , lookup
Relational model wikipedia , lookup
Transcript
Chapter 3: Table Creation and Management: Creating and Modifying Database Tables Jason C. H. Chen, Ph.D. Professor of MIS School of Business Administration Gonzaga University Spokane, WA 99258 [email protected] Dr. Chen, Oracle Database System (Oracle) 1 Objectives • Become acquainted with Structured Query Language (SQL) • Identify the table name and structure • Create a new table using the CREATE TABLE command • Use a subquery to create a new table • Add a column to an existing table • Modify the definition of a column in an existing table • Delete a column from an existing table • Mark a column as unused and then delete it at a later time • Rename a table • Truncate a table • Drop a table Dr. Chen, Oracle Database System (Oracle) 2 Database Objects and Queries • An Oracle database consists of multiple user accounts • Each user account owns database objects • • – Tables – Views – Stored programs, etc. Query: command to perform operation on database object Structured Query Language (SQL) – Industry standard query language for most of relational databases – Consists of about 30 commands Dr. Chen, Oracle Database System (Oracle) 3 Basic SQL Concepts and Commands SQL (Structured Query Language) is used to manipulate the database. There are two basic types of SQL commands: Data Definition Language (DDL) Data Manipulation Language (DML) DDL commands work with the structure of the objects (tables, indexes, views) in the database. DML commands work with the data in the database (i.e.,manipulate the data). Reserved words - SQL command words Dr. Chen, Oracle Database System (Oracle) 4 Oracle12c User Accounts • User account - identified by a unique username and password • User schema - all of the objects that the user creates and stores in the database • Database objects – Also called schema objects – Objects in user schema • Object owner has privileges to perform all possible actions on an object • Schema is a collection of objects in a specific Oracle account (tables, views etc.) Dr. Chen, Oracle Database System (Oracle) 5 A. Names and Properties Why need a name? Dr. Chen, Oracle Database System (Oracle) 6 Creating a Table CREATE TABLE tablename (fieldname1 data_type (size), fieldname2 data_type (size), …); Dr. Chen, Oracle Database System (Oracle) 7 Defining Oracle12c Database Tables • To create a table, you must specify: – – – – Table name Field names Field data types Field sizes Constraints restrictions on the data values that a field can store Dr. Chen, Oracle Database System (Oracle) 8 I. Names and Properties: Conventions Series of rules Oracle Corporation established for naming all database objects 1. From 1 to 30 characters 2. Only alphanumeric characters, and special characters ($ , _, #) 3. Must begin with a letter and can not contain blank spaces or hyphens 4. Must be unique and No reserved words are allowed Are the following names (for field) valid? Why? customer order customer-order #order Customer_# Customer# Dr. Chen, Oracle Database System (Oracle) 9 Oracle 12c Data Types • Data type – Specifies kind of data that column stores – Provides means for error checking – Enable DBMS to use storage space more efficiently by internally storing different types of data in different ways – Basic types • Character • Number • Date/time Dr. Chen, Oracle Database System (Oracle) 10 II. Data Types • Built-in – provided by the system • Library – built by the software vendor or a third party • User-defined – built by users Dr. Chen, Oracle Database System (Oracle) 11 Basic Built-In Data Types • Character – VARCHAR2 – CHAR • Numeric • • – NUMBER DATE OTHERS: – LOB, BLOB, LONG, RAW, LONG RAW Dr. Chen, Oracle Database System (Oracle) 12 Character Data Types • 1. VARCHAR2 – Stores variable-length character data up to a maximum of 4,000 characters – Values in different records can have a different number of characters – fieldname VARCHAR2(maximum_size) • (e.g.) emp_name VARCHAR2(20); • an instance: ‘Jason Chen’ Dr. Chen, Oracle Database System (Oracle) 13 Character Data Types (cont.) • 2. CHAR – Fixed-length character data (<= 2000 characters) – default is 1 if no field size is specified – Data values for different records all have the same number of characters – DBMS adds trailing blank spaces to the end of the entry to make the entry fill the maximum_size value – Data longer than maximum_size causes an error [optional] – fieldname CHAR[(maximum_size)] • pros: use data storage space more efficiently and processed faster • cons: causes inconsistent query results in other Oracle applications – e.g. s_class CHAR(2); ‘SR’ ‘JR’ ‘SO’ ‘FR’ ‘GR’ – State CHAR(2) DEFAULT ‘WA’; – student_gender CHAR; Dr. Chen, Oracle Database System (Oracle) 14 Character Subtypes Examples: VARCHAR2(5) ‘Smith’ or ‘Smi’ CHAR(5) ‘Smith’ or ‘Smi LONG ‘Smith...’ ’ Note that you do not need to specify a size for LONG. To include a single quote in a literal character string, use two in a row: ‘This is Herald’’s string.’ Dr. Chen, Oracle Database System (Oracle) 15 Question: Which query will possibly generate student information? s_Last VARCHAR2(15); s_Last CHAR(15); SELECT s_Last, s_First, s_Address FROM student WHERE s_Last = ‘Smith’; SELECT s_Last, s_First, s_Address FROM student WHERE s_Last = ‘Smith’; • What data type should be used if there is any chance that all column spaces will NOT be filled? VARCHAR2 • Answer: ______________ L Dr. Chen, Oracle Database System (Oracle) 16 • When use Query: SELECT s_last, s_first, ssn, telephone FROM student WHERE s_last = ‘Smith’; • Case is sensitive within the single quotation. • SQL Plus commands are NOT case sensitive, but Query within the single quotation are case sensitive. Dr. Chen, Oracle Database System (Oracle) 17 3. Number Data Types • Stores negative, positive, fixed, and floating point numbers between 10 -130 <= <=10 +126 precision up to 38 decimal places • General Syntax: fieldname NUMBER [([precision,] [scale])] • Integer: fieldname NUMBER(precision) • Fixed point: fieldname NUMBER[([precision],[scale])] • Floating point: fieldname NUMBER Dr. Chen, Oracle Database System (Oracle) 18 Number Data Types (examples) • a) Integer: Number (n) – e.g. s_id NUMBER(5) • 12345 • b) Fixed-point numbers – e.g. current_price NUMBER (5, 2); • 259.99 33.89 • c) Fixed-point numbers (cont.) – e.g. total_mileage NUMBER (5, 1); • 259.9 33.8 • d) Floating-point Number – with a variable number of decimal places – e.g. s_gpa NUMBER; • 3.89 2.7569 3.2 Dr. Chen, Oracle Database System (Oracle) 19 4. Date and Time Data Types • Date, time data subtypes – Store actual date and time values – DATE • Dates from December 31, 4712 BC to December 31, 4712 AD – Default format DD-MON-YY – Default time format HH:MI:SS A.M. – fieldname DATE – Sample declaration: • OrderDate DATE NOT NULL; – Use one of the following format masks: – – – Dr. Chen, Oracle Database System (Oracle) TO_DATE (‘ TO_DATE (‘ TO_DATE (‘ ’, ‘MM/DD/YY’) ‘, ‘DD-MON-YYYY’) ‘, ‘HH:MI AM’) 20 Table Design (continued) Table 3-2 Oracle 11g Datatypes Dr. Chen, Oracle Database System (Oracle) 21 Table Creation Figure 3-1 CREATE TABLE syntax Defining Columns • Column definition list must be enclosed in parentheses • Datatype must be specified for each column • Maximum of 1,000 columns Dr. Chen, Oracle Database System (Oracle) 22 Exercise: Create a new table of “acctmanager” based on the following information acctmanager Amid Amfirst Amlast AmeDate Amsal Amcomm Region VARCHAR2(4) VARCHAR2(12) VARCHAR2(12) DATE NUMBER(8,2) NUMBER(7,2) CHAR(2) CREATE TABLE acctmanager ( amid … Dr. Chen, Oracle Database System (Oracle) NOT NULL); GROUP WORK Complete the CREATE command manually! 23 Exercise: Create a new table of “acctmanager” based on the following information acctmanager Amid Amfirst Amlast AmeDate Amsal Amcomm Region VARCHAR2(4) VARCHAR2(12) VARCHAR2(12) DATE NUMBER(8,2) NUMBER(7,2) CHAR(2) CREATE TABLE acctmanager ( amid VARCHAR2(4) PRIMARY KEY, SELECT * amfirst VARCHAR2(12) NOT NULL, FROM acctmanager; amlast VARCHAR2(12) NOT NULL, amedate DATE DEFAULT SYSDATE, amsal NUMBER(8,2), amcomm NUMBER(7,2) DEFAULT 0, region CHAR(2) NOT NULL); Dr. Chen, Oracle Database System (Oracle) 24 Refresh the Database • 1. Create a new folder on c:\ as follows: c:\oradata\chapter3 • 2. Go to Blackboard and download data files from Oracle chapter3 and save under c:\oradata\chapter3\ • 3. Run the following script file – Start c:\oradata\chapter3\JLDB_Build_3.sql Dr. Chen, Oracle Database System (Oracle) 25 Exercise – Your Turn • Type the following commands: 1) SELECT TABLE_NAME FROM USER_TABLES; 2) DROP TABLE ACCTMANAGER CASCADE CONSTRAINTS; 3) DROP TABLE ACCTMANAGER2 CASCADE CONSTRAINTS; 4) SELECT TABLE_NAME FROM USER_TABLES; You now are able to create acctmanager table Dr. Chen, Oracle Database System (Oracle) 26 CREATE TABLE Command Example What is the difference between these two versions: Virtual Column/ (Derived/computed) Is this a good approach? When a value of amsal or amcomm is changed, its ameran will be updated automatically. Figure 3-2 The creation of the ACCTMANAGER table Dr. Chen, Oracle Database System (Oracle) 27 Viewing Table Structures: DESCRIBE • DESCRIBE displays the structure of a specified table Figure 3-4 The DESCRIBE command Dr. Chen, Oracle Database System (Oracle) 28 Invisible Columns (p.68) • Invisible columns are a new option in Oracle 12c. We can now create a column to make it hidden so it is not visible in basic statement such as a “SELECT” query. • A developer may wish to make invisible columns if they need to reference a value in application logic but do not intend these values to be directly visible to users. • Including the “invisible” option on a column definition as shown in Fig. 3-6 will establish an invisible column. Dr. Chen, Oracle Database System (Oracle) 29 -- chapter 3, Figure 3-5; p. 68 SELECT column_name, data_type, data_default FROM user_tab_columns WHERE table_name = 'ACCTMANAGER'; -- chapter 3, Figure 3-7; p. 69 SELECT * FROM test_invis; -- chapter 3, Figure 3-8; p. 69 SELECT col1, col2 FROM test_invis; Fig 3-5 Verify DEFAULT and virtual column settings -- chapter 3, Figure 3-6; p. 68 CREATE TABLE TEST_INVIS (col1 CHAR(1), col2 NUMBER(4) invisible); Dr. Chen, Oracle Database System (Oracle) -- chapter 3, Figure 3-9; P. 69 SELECT column_name, hidden_column FROM user_tab_cols WHERE table_name = ’TEST_INVIS’; 30 Table Creation through Subqueries • You can use subqueries to retrieve data from an existing table • Requires use of AS keyword • New column names can be assigned CREATE TABLE…AS Figure 3-10 CREATE TABLE … AS command syntax Dr. Chen, Oracle Database System (Oracle) 31 CREATE TABLE…AS Command Example (You need to apply this to #7 on p.97) Figure 3-11 Creating a table based on a subquery SELECT * FROM cust_mkt; DESC cust_mkt; Dr. Chen, Oracle Database System (Oracle) 32 Modifying Existing Tables • Accomplished through the ALTER TABLE command • Use an ADD clause to add a column • Use a MODIFY clause to change a column • Use a DROP COLUMN to drop a column – both “column” and its “data values” are deleted ALTER TABLE Command Syntax Figure 3-14 Arithmetic operations with NULL values Dr. Chen, Oracle Database System (Oracle) 33 ALTER TABLE…ADD Command Figure 3-16 The ALTER TABLE … ADD command Dr. Chen, Oracle Database System (Oracle) 34 ALTER TABLE…MODIFY Command Figure 3-22 The ALTER TABLE … MODIFY command to increase the column width Dr. Chen, Oracle Database System (Oracle) 35 Modification Guidelines • Column must be as wide as the data it already contains • If a NUMBER column already contains data, size cannot be decreased • Adding or changing default data does not affect existing data Dr. Chen, Oracle Database System (Oracle) 36 ALTER TABLE…SET UNUSED Command • Once marked for deletion (i.e., SET UNUSED), a column cannot be restored • Storage space is freed at a later time 37 Dr. Chen, Oracle Database System (Oracle) 37 ALTER TABLE…DROP UNUSED Command • Frees up storage space from columns previously marked as unused However, once a table is set “UNUSED” it can’t be DROPPED using the following (regular) command: ALTER TABLE tablename DROP COLUMN colname; Then, what command can drop the “UNUSED” columns? ALTER TABLE author DROP UNUSED COLUMNS; Dr. Chen, Oracle Database System (Oracle) Show: test_UNUSED.sql and test_UNUSED.docx 38 AUTHOR AuthorID LName VARCHAR2(4) VARCHAR2(10) FName VARCHAR2(10) SQL> SELECT * FROM author; AUTH ---S100 J100 A100 M100 K100 P100 A105 B100 P105 W100 W105 LNAME ---------SMITH JONES AUSTIN MARTINEZ KZOCHSKY PORTER ADAMS BAKER PETERSON WHITE WHITE FNAME ---------SAM JANICE JAMES SHEILA TAMARA LISA JUAN JACK TINA WILLIAM LISA AUTH ---R100 F100 W110 LNAME ---------ROBINSON FIELDS WILKINSON FNAME ---------ROBERT OSCAR ANTHONY 14 rows selected. Dr. Chen, Oracle Database System (Oracle) 39 AUTHOR AuthorID LName VARCHAR2(4) VARCHAR2(10) FName VARCHAR2(10) SQL> describe author; Name Null? Type ------------ -------- --------------AUTHORID NOT NULL VARCHAR2(4) LNAME VARCHAR2(10) FNAME VARCHAR2(10) SQL> SQL> ALTER TABLE author SET UNUSED COLUMN fname; Table altered. SQL> describe author; Name Null? Type ----------- -------- ------------AUTHORID NOT NULL VARCHAR2(4) LNAME VARCHAR2(10) SQL> Dr. Chen, Oracle Database System (Oracle) Show: test_UNUSED.sql and test_UNUSED.docx SQL> ALTER TABLE author DROP COLUMN lname; Table altered. SQL> ALTER TABLE author DROP COLUMN fname; ALTER TABLE author DROP COLUMN fname * ERROR at line 1: ORA-00904: "FNAME": invalid identifier SQL> ALTER TABLE author 2 DROP UNUSED COLUMNS; Table altered. SQL> describe author; Name Null? Type ----------- -------- ------------AUTHORID NOT NULL VARCHAR2(4) SQL> 40 AUTHOR AuthorID LName VARCHAR2(4) VARCHAR2(10) FName VARCHAR2(10) SQL> SELECT * FROM author; AUTH ---A100 A105 B100 F100 J100 K100 M100 P100 P105 R100 S100 AUTH ---W100 W105 W110 14 rows selected. Dr. Chen, Oracle Database System (Oracle) 41 TRUNCATING a TABLE Dr. Chen, Oracle Database System (Oracle) 42 • Practice all the rest of examples in the text. • A Script file is available on the Bb (file name: Ch3Queries.sql) • After completing all examples, do the HW. Dr. Chen, Oracle Database System (Oracle) 43 Homework - Hands-On Assignments Upload the SQL and spooled files (*.sql and *.txt) to the Bb (under “Assignments & Projects”) by the deadline Read and Practice all examples on Chapters 3 • 1. Run the script files (in the folder \oradata\chapter3\): JLDB_Build_3.sql • 2. Read Oracle assignment and create a script file Oracle_ch3_Lname_Fname.sql for questions (#1 to #8; p.97) on “Hands-on Assignments”. . • 3. Execute and test one problem at a time and make sure they are all running successfully. • 4. When you done, spool the script files (see next slide for spooling instructions) and upload SQL and the spooled files (Oracle_ch3_Spool_Lname_Fname.txt) to Bb by midnight this coming Sunday. Turn in a hardcopy of spooled file (*.txt ONLY) to me in the class. Dr. Chen, Oracle Database System (Oracle) 44 How to Spool your Script and Output Files After you tested the script file of Oracle_ch3_Lname_Fname.sql successfully, follow the instructions below to spool both script and output files: Step 0. Run the following script file from SQL*Plus (since you have created JLDB tables) – Start c:\oradata\chapter3J\LDB_Build_3.sql • 1. type the following on SQL> – Spool c:\oradata\Oracle_ch3_Spool_Lname_Fname.txt (make sure your name is entered) • 2. open Oracle_ch3_Lname_Fname.sql that you already tested • 3. copy and paste all the SQL commands (including all comments) to the SQL*PLUS • 4. type Spool Off on the SQL> The output should contain your personal information, all SQL commands and their solution on the .txt file and saved in C: drive (oradata\ folder) Upload the SQL and spooled files (*.sql and *.txt) to the Bb (under “Assignments & Projects”) by the deadline Dr. Chen, Oracle Database System (Oracle) 45 TRUNCATING a TABLE Dr. Chen, Oracle Database System (Oracle) 46 Renaming a Table • RENAME…TO is used to rename a table – the old name is no longer valid --chapter 3, Figure 3-34; p.84 SELECT * FROM cust_mkt_092009; Figure 3-32 The RENAME … TO command Dr. Chen, Oracle Database System (Oracle) 47 Truncating a Table • TRUNCATE TABLE command – rows are deleted • Structure of table remains Figure 3-36 The TRUNCATE TABLE command Dr. Chen, Oracle Database System (Oracle) 48 Deleting a Table • DROP TABLE command – table structure and contents are deleted --chapter 3, Figure 3-39; p. 87 DESC cust_mkt_092009 Figure 3-36 Deleting a Table command 49 Dr. Chen, Oracle Database System (Oracle) 49 DROP TABLE without Purge Option • Starting with Oracle 10g, a new feature of recycle bin was introduced. • Dropped tables can be recovered from the recycle bin Figure 3-40 Checking the recycle bin Dr. Chen, Oracle Database System (Oracle) 50 FLASHBACK Command • The FLASHBACK command recovers a table from the recycle bin Figure 3-41 Using FLASHBACK TABLE to restore a dropped table 51 Dr. Chen, Oracle Database System (Oracle) 51 Use PURGE to Remove a Table from the Recycle Bin Figure 3-40 Removing a table from the recycle bin Dr. Chen, Oracle Database System (Oracle) 52 PURGE Option Available for DROP TABLE Command • Using the PURGE option will permanently remove a table from the database • The table will not be copied into the recycle bin --chapter 3, Figure 3-44; p. 90 DROP TABLE cust_mkt_092009 PURGE; 53 Dr. Chen, Oracle Database System (Oracle) 53 • End of chapter 3 Dr. Chen, Oracle Database System (Oracle) 54