Chapter 3: Table Creation and Management: Creating and Modifying Database Tables
description
Transcript of Chapter 3: Table Creation and Management: Creating and Modifying Database Tables
Dr. Chen, Oracle Database System (Oracle) 1
Chapter 3: Table Creation and Management:
Creating and ModifyingDatabase Tables
Jason C. H. Chen, Ph.D.Professor of MIS
School of Business AdministrationGonzaga UniversitySpokane, WA [email protected]
Dr. Chen, Oracle Database System (Oracle) 2
Important/Useful Links for SQL1. Below are three links of free “online interactive SQL Tutorial for Data Analysis and Query Examples” https://community.modeanalytics.com/sql/tutorial/introduction-to-sql/https://www.pgexercises.com/questions/basic/https://sqlbolt.com/
2. Furthermore, the link below is a fun read about the history of SQL, and growth of SQL:
https://blog.timescale.com/why-sql-beating-nosql-what-this-means-for-future-of-data-time-series-database-348b777b847a
Dr. Chen, Oracle Database System (Oracle) 3
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) 4
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) 5
Basic SQL Concepts and CommandsSQL (Structured Query Language) is used to manipulate the database.
There are two basic types of SQL commands:
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
4Data Definition Language (DDL)
4Data Manipulation Language (DML)
Dr. Chen, Oracle Database System (Oracle) 6
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) 7
A. Names and PropertiesWhy need a name?
Dr. Chen, Oracle Database System (Oracle) 8
Creating a Table
CREATE TABLE tablename(fieldname1 data_type (size), fieldname2 data_type (size),
…);
Dr. Chen, Oracle Database System (Oracle) 9
Defining Oracle12c Database Tables
• To create a table, you must specify:– Table name– Field names– Field data types– Field sizes
vConstraintsrestrictions on the data values that a field can store
Dr. Chen, Oracle Database System (Oracle) 10
I. Names and Properties: Conventions
1. From 1 to 30 characters2. Only alphanumeric characters, and special
characters ($ , _, #)3. Must begin with a letter and can not contain blank
spaces or hyphens4. Must be unique and No reserved words are allowed
Series of rules Oracle Corporation established for naming all database objects
v Are the following names (for field) valid? Why? customer order customer-order
#orderCustomer_#Customer#
Dr. Chen, Oracle Database System (Oracle) 11
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) 12
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) 13
Basic Built-In Data Types
• Character– VARCHAR2– CHAR
• Numeric – NUMBER
• DATE• OTHERS:
– LOB, BLOB, LONG, RAW, LONG RAW
Dr. Chen, Oracle Database System (Oracle) 14
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) 15
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– 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;
[optional]
Dr. Chen, Oracle Database System (Oracle) 16
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) 17
Question: Which query will possibly generate student information?
• What data type should be used if there is any chance that all column spaces will NOT be filled?
• Answer: ______________
s_Last VARCHAR2(15);
SELECT s_Last, s_First, s_AddressFROM studentWHERE s_Last = ‘Smith’;
s_Last CHAR(15);
SELECT s_Last, s_First, s_AddressFROM studentWHERE s_Last = ‘Smith’;
L
VARCHAR2
Dr. Chen, Oracle Database System (Oracle) 18
• 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) 19
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) 20
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) 21
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:
– TO_DATE (‘ ’, ‘MM/DD/YY’) – TO_DATE (‘ ‘, ‘DD-MON-YYYY’) – TO_DATE (‘ ‘, ‘HH:MI AM’)
Dr. Chen, Oracle Database System (Oracle) 22
Table Design (continued)
Table 3-2 Oracle 11g Datatypes
Dr. Chen, Oracle Database System (Oracle) 23
Table Creation
• Column definition list must be enclosed in parentheses
• Datatype must be specified for each column• Maximum of 1,000 columns
Defining Columns
Figure 3-1 CREATE TABLE syntax
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
acctmanager
Exercise: Create a new table of “acctmanager” based on the following information
CREATE TABLE (
… NOT NULL);
Amid Amfirst Amlast AmeDate Amsal Amcomm Region
VARCHAR2(4) VARCHAR2(12) VARCHAR2(12) DATE NUMBER(8,2) NUMBER(7,2) CHAR(2)
Exercise
Complete the CREATE command
manually!(call one student…)
acctmanageramid
Dr. Chen, Oracle Database System (Oracle) 27
acctmanager
Exercise: Create a new table of “acctmanager” based on the following information
CREATE TABLE ( amfirst VARCHAR2(12) NOT NULL,amlast VARCHAR2(12) NOT NULL,amedate DATE DEFAULT SYSDATE,amsal NUMBER(8,2),amcomm NUMBER(7,2) DEFAULT 0,region CHAR(2) NOT NULL);
Amid Amfirst Amlast AmeDate Amsal Amcomm Region
VARCHAR2(4) VARCHAR2(12) VARCHAR2(12) DATE NUMBER(8,2) NUMBER(7,2) CHAR(2)
How to verify the table structure of acctmanager?
DESC acctmanager;
acctmanageramid VARCHAR2(4) PRIMARY KEY,
Dr. Chen, Oracle Database System (Oracle) 28
CREATE TABLE Command Example
Virtual Column/(Derived/computed)
Figure 3-2 The creation of the ACCTMANAGER table
What is the difference between these two versions:
Is this a good approach?
When a value of amsal or amcomm is changed, its ameran will be updated automatically.
Dr. Chen, Oracle Database System (Oracle) 29
Dr. Chen, Oracle Database System (Oracle) 30
Viewing Table Structures: DESCRIBE
• DESCRIBE displays the structure of a specified table
Figure 3-4 The DESCRIBE command
Dr. Chen, Oracle Database System (Oracle) 31
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) 32
-- chapter 3, Figure 3-5; p. 68SELECT column_name, data_type, data_defaultFROM user_tab_columnsWHERE table_name = 'ACCTMANAGER';
-- chapter 3, Figure 3-6; p. 68CREATE TABLE TEST_INVIS(col1 CHAR(1),col2 NUMBER(4) invisible);
Fig 3-5 Verify DEFAULT and virtual column settings
-- chapter 3, Figure 3-7; p. 69SELECT *FROM test_invis;
-- chapter 3, Figure 3-8; p. 69SELECT col1, col2FROM test_invis;
-- chapter 3, Figure 3-9; P. 69SELECT column_name, hidden_columnFROM user_tab_colsWHERE table_name = ’TEST_INVIS’;
Dr. Chen, Oracle Database System (Oracle) 33
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) 34
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) 35
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) 36
ALTER TABLE…ADD Command
Figure 3-16 The ALTER TABLE … ADD command
Dr. Chen, Oracle Database System (Oracle) 37
ALTER TABLE…MODIFY Command
Figure 3-22 The ALTER TABLE … MODIFY command to increase the column width
Dr. Chen, Oracle Database System (Oracle) 38
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) 39
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
39
Dr. Chen, Oracle Database System (Oracle) 40
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?
Show: test_UNUSED.sqland test_UNUSED.docx
ALTER TABLE authorDROP UNUSED COLUMNS;
Dr. Chen, Oracle Database System (Oracle) 41
AuthorID LName FNameVARCHAR2(4) VARCHAR2(10) VARCHAR2(10)
AUTHOR
SQL> SELECT * FROM author; AUTH LNAME FNAME ---- ---------- ---------- S100 SMITH SAM J100 JONES JANICE A100 AUSTIN JAMES M100 MARTINEZ SHEILA K100 KZOCHSKY TAMARA P100 PORTER LISA A105 ADAMS JUAN B100 BAKER JACK P105 PETERSON TINA W100 WHITE WILLIAM W105 WHITE LISA AUTH LNAME FNAME ---- ---------- ---------- R100 ROBINSON ROBERT F100 FIELDS OSCAR W110 WILKINSON ANTHONY 14 rows selected.
Dr. Chen, Oracle Database System (Oracle) 42
AuthorID LName FNameVARCHAR2(4) VARCHAR2(10) VARCHAR2(10)
AUTHOR
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>
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>
Show: test_UNUSED.sqland test_UNUSED.docx
Dr. Chen, Oracle Database System (Oracle) 43
"is there any way that we can retrieve the data from the UNUSED column ?“
No. The SET UNUSED syntax is a convenience for DBAs. Dropping a column is potentially a resource-intensive exercise. Marking it as UNUSED is a lot quicker, so it allows them to withdraw a column from use in busy times and run DROP UNUSED when the database is quieter. But the data is as lost as if they had just dropped the column.
The only way to retrieve the data would be to restore the column, through one of the various Flashback features (depending on what you've got configured) or else RMAN (or whichever Backup/Recovery solution you have in place).
Dr. Chen, Oracle Database System (Oracle) 44
AuthorID LName FNameVARCHAR2(4) VARCHAR2(10) VARCHAR2(10)
AUTHOR
SQL> SELECT * FROM author; AUTH----A100A105B100F100J100K100M100P100P105R100S100 AUTH----W100W105W110 14 rows selected.
Dr. Chen, Oracle Database System (Oracle) 45
• 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) 46
Homework - Hands-On Assignments
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 before next class begins. Turn in a hardcopy of spooled file (*.txt ONLY) to me in the class.
Upload the SQL and spooled files (*.sql and *.txt) to the Bb (under “Assignments & Projects”) by the deadline
Dr. Chen, Oracle Database System (Oracle) 47
How to Spool your Script and Output FilesAfter 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) 48
TRUNCATING a TABLE
Dr. Chen, Oracle Database System (Oracle) 49
Renaming a Table
• RENAME…TO is used to rename a table – the old name is no longer valid
Figure 3-32 The RENAME … TO command
--chapter 3, Figure 3-34; p.84
SELECT *FROM cust_mkt_092009;
Dr. Chen, Oracle Database System (Oracle) 50
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) 51
Deleting a Table
• DROP TABLE command – table structure and contents are deleted
51
Figure 3-36 Deleting a Table command
--chapter 3, Figure 3-39; p. 87
DESC cust_mkt_092009
Dr. Chen, Oracle Database System (Oracle) 52
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) 53
FLASHBACK Command
• The FLASHBACK command recovers a table from the recycle bin
53
Figure 3-41 Using FLASHBACK TABLE to restore a dropped table
Dr. Chen, Oracle Database System (Oracle) 54
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) 55
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
55
--chapter 3, Figure 3-44; p. 90
DROP TABLE cust_mkt_092009 PURGE;
Dr. Chen, Oracle Database System (Oracle) 56
• End of chapter 3