Presentation is loading. Please wait.

Presentation is loading. Please wait.

Guide to Oracle 10g Chapter 2: Creating and Modifying Database Tables.

Similar presentations


Presentation on theme: "Guide to Oracle 10g Chapter 2: Creating and Modifying Database Tables."— Presentation transcript:

1 Guide to Oracle 10g Chapter 2: Creating and Modifying Database Tables

2 The Oracle 10g Client/Server Database
Latest release of Oracle Corporation’s relational database Client/server database Server side DBMS server process Oracle Net Utility that enables network communication between client and server Guide to Oracle 10g

3 Client/Server Architecture for Oracle 10g DBMS
Guide to Oracle 10g

4 The Oracle 10g Client/Server Database (continued)
Oracle Application Server Used to create World Wide Web pages that allow users to access Oracle databases Oracle client products: SQL*Plus Oracle 10g Developer Suite Enterprise Manager Guide to Oracle 10g

5 Database Objects An Oracle database consists of multiple user accounts
Each user account owns database objects Tables Views Stored programs Etc.

6 Database Queries Query: command to perform operation on database object Create Modify View Delete Structured Query Language (SQL) Standard query language for relational databases

7 SQL Command Types Data Definition Language (DDL)
Used to create and modify the structure of database objects Data Manipulation Language (DML) Used to insert, update, delete, and view database data

8 DDL Commands Used to create and modify the structure of database objects CREATE ALTER DROP DDL commands execute as soon as they are issued, and do not need to be explicitly saved

9 DML Commands Used to insert, view, and modify database data
UPDATE DELETE SELECT DML commands need to be explicitly saved or rolled back COMMIT ROLLBACK

10 User Accounts Each Oracle database user has a user schema
Area in the database where the user’s database objects are stored Identified by a unique username and protected by a password Each user schema is granted specific privileges

11 Types of Database Privileges
System Privileges Control the operations that the user can perform within the database Connecting to the database (Create Session), creating new tables, shutting down the database, etc. Object Privileges Granted on individual database objects Controls operations that a user can perform on a specific object (insert data, delete data, etc.) When you create an object in your user schema, you can then grant object privileges on that object to other database users

12 Break Time: SQL Plus Oracle SQL command line utility for issuing SQL commands Starting SQL Plus LOGON to YOUR Oracle Account

13 How to Access Your Oracle Account
1. Click the START button, point to Programs 2. Select Oracle –Oracle10g, then 3. Click Application Development, then 4. Select SQL PLUS User Name: Password: Host string:

14 Creating New User Accounts
Done by DBA Syntax: CREATE USER username IDENTIFIED BY password;

15 Oracle Naming Standard
Oracle database objects must adhere to the Oracle Naming Standard 1 to 30 characters long Must begin with a character Can contain characters, numbers, and the symbols $, _, and #

16 Defining Database Tables
To create a table, you must specify: Table name Field names Field data types Field sizes Constraints

17 Table and Field Names Must follow the Oracle Naming Standard
Each table in a user schema must have a unique name within that user schema Each field in a table must have a unique name within that table

18 CREATE TABLE tablename
Creating a Table CREATE TABLE tablename (fieldname1 data_type, (fieldname2 data_type, …)

19 Oracle Data Types Data type: specifies type of data stored in a field
Date, character, number. LONG, RAW, LONG RAW, BLOB Uses Error checking Efficient use of storage space

20 Oracle Character Data Types
VARCHAR2 columnname VARCHAR2(max_size) Variable-length character strings Max_size can be between 1 and 4,000 characters Must specify the size No trailing blank spaces are added If more than max_size data is inserted, an error occurs. Example declaration: student_name VARCHAR2(30)

21 Character Data Types CHAR columnname CHAR(max_size)
Fixed-length character data Max_size can be between 1 and 2000 characters Max_size is optional. Default is 1. Adds trailing blank spaces to pad width If more than max_size data is inserted, an error occurs. Example declaration: student_gender CHAR(2)

22 Character Subtypes Examples: VARCHAR2(5) ‘Smith’ or ‘Smi’

23 Question: Which query will possibly generate student information?
s_last CHAR(15); SELECT s_last, s_first, s_address FROM student WHERE s_last = ‘Smith’; s_last VARCHAR2(15); 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? Answer: VARCHAR2

24 Character Data Types 3. NVARCHAR2 and NCHAR
Analogous to VARCHAR2 and CHAR but use Unicode rather than ASCII Used to hold character data in languages other than English (Japanese).

25 Number Data Type NUMBER General declaration format:
stores negative, positive, fixed, and floating point numbers values between and 10126 General declaration format: variable_name NUMBER(precision, scale)

26 NUMBER Data Types Number type (integer, fixed point, floating point) specified by precision and scale Precision: total number of digits on either side of the decimal point. It does not include the decimal point itself or any commas or any formatting symbols. Scale: number of digits to right of decimal point

27 Integer Numbers Whole number with no digits to right of decimal point
Precision is maximum width Scale is omitted Sample declaration: s_age NUMBER (2)

28 Fixed Point Numbers Contain a specific number of decimal places
Precision is maximum width Scale is number of decimal places Sample declaration: item_price NUMBER(5, 2) (decimal point is not included)

29 Floating Point Numbers
Contain a variable number of decimal places Precision and scale are omitted Sample declaration: s_GPA NUMBER

30 Date Data Type DATE Default date format: DD-MON-YY HH:MI:SS AM
Stores dates from 1/1/4712 BC to 12/31/4712 AD Stores both a date and time component Default date format: DD-MON-YY HH:MI:SS AM example: 05-JUN-03 12:00:00 AM Sample declaration: s_dob DATE

31 Specifying Date and Time Values
If no time value is given when a new date is inserted, default value is 12:00:00 AM If no date value is given when a new time is inserted, default date is first day of current month

32 TIMESTAMP Data Type The same as Date DT, but it stores also fractional seconds. Field Timestamp(Fr_Se_Precision) E.g: ship_dt Timestamp(2) Fractional Seconds Precision default value is 6 (If omitted).

33 Interval Year to Month Data Type
Field Interval Year(Y_Pr) To Month. Y_Pr: Year Precision(Default: 6). E.g: elapsed Interval Year(2) To Month. Possible Values: :add 2 years and 11 months to a known date. -11-4:subtract 11 years and 4 months.

34 Interval Day to Second Data Type
Field Interval Day(D_Pr) To Second(Fr_Se_pr). D_Pr: Day Precision(Default : 2). Fr_Se_Pr: Fractional Seconds Precision (Default : 6). Possible value: -04 03:20:32.00 (Days Hours:Minutes:Seconds.Fractions)

35 Examples Source: java2s.com

36 Large Object (LOB) Data Types
Binary Large Object (BLOB) Stores up to 4 GB of binary data Character Large Object (CLOB) Stores up to 4 GB of character data BFILE Stores a reference to a binary file maintained in the operating system NCLOB Character LOB that supports 16-bit character code

37 6. Large Object (LOB) Data Types
Ex: f_image BLOB;

38 Declaring LOB Data Fields
Item size is not specified Examples: item_image BLOB item_image BFILE

39 Creating a Database Table
Syntax: CREATE TABLE table_name ( fieldname1 datatype, fieldname2 datatype, …); Example: CREATE TABLE my_students ( s_id NUMBER(6), s_name VARCHAR2(30), s_dob DATE, s_class CHAR(2));

40 Constraints Rules that restrict the values that can be inserted into a field Types of constraints Integrity: define primary and foreign keys Value: specify values or ranges of values that can be inserted

41 Constraint Levels Table constraint Column constraint
Restricts the value of a field with respect to all other table records Example: primary key value must be unique for each record Column constraint Restricts values in a specific column Example: values in an S_GENDER field must be ‘M’ or ‘F’

42 Constraint Names Internal name used by DBMS to identify the constraint
Each constraint name in a user schema must be unique If you do not name a constraint, the system will automatically generate an unintuitive name

43 Constraint Names Constraint naming convention: Constraint ID values:
tablename_fieldname_constraintID Constraint ID values: Primary key: pk Foreign key: fk Check condition: cc Not NULL: nn Unique: uk Example constraint name: my_students_s_id_pk

44 Primary Key Constraints
Table-level Defining a primary key: CONSTRAINT constraint_name PRIMARY KEY Example: s_id NUMBER(6) CONSTRAINT student_s_id_pk PRIMARY KEY

45 Primary Key Constraints
Can be defined when field is declared

46 Primary Key Constraints
Can also be defined after all table field definitions are completed

47 Composite Primary Keys
Syntax: CONSTRAINT constraint_name PRIMARY KEY (field1, field2) Must be defined after fields that compose key are defined

48 Foreign Key Constraints
Table-level Can only be defined after field is defined as a primary key in another table Syntax: CONSTRAINT constraint_name REFERENCES primary_key_table_name (field_name)

49 Foreign Key Constraints
Can be defined when field is declared

50 Foreign Key Constraints
Can also be defined after all table field definitions are completed

51 Value Constraints Column-level
Restricts data values that can be inserted in a field In general, avoid value constraints because they make the database very inflexible

52 Types of Value Constraints
Check condition: restricts to specific values Example: s_gender (M or F) CONSTRAINT my_students_s_gender_cc CHECK (s_gender = ‘M’) OR (s_gender = ‘F’) Not NULL: specifies that a field cannot be NULL Example: CONSTRAINT my_students_s_dob_nn NOT NULL

53 Types of Value Constraints
Default: specifies a default value that is inserted automatically Example: s_state CHAR(2) DEFAULT ‘WI’ Unique Table constraint Specifies that a non-primary key field must have a unique value CONSTRAINT consultant_c_ _uk UNIQUE (c_ )

54 SQL*Plus Oracle SQL command line utility for issuing SQL commands
Starting SQL*Plus

55 Using SQL*Plus All commands must be terminated with a semicolon
Use a text editor and copy and paste commands Character data is case sensitive and must be in single quotes ‘M’ ‘Sarah’

56 Exiting SQL*Plus Type exit at SQL> prompt
or Click Close button on SQL*Plus window

57 Oracle Help Resources Ora.hlp file Oracle Technology Network (OTN)

58 Viewing Table Information
Viewing a table’s structure DESCRIBE table_name;

59 Oracle Data Dictionary
Contains tables that describe the database structure Is in the SYSTEM user schema Is automatically updated as users create and modify tables Cannot be updated directly Contains views that allow users to retrieve information about the database structure

60 Data Dictionary Views Views present data in different formats depending on the privileges of the user USER: shows all objects belonging to the current user ALL: shows all objects belonging to the current user, as well as objects current user has privileges to manipulate DBA: allows users with DBA privileges to view objects of all database users

61 Querying the Data Dictionary Views
Syntax: SELECT field1, field2, … FROM privilege_viewname;

62 Summary of Oracle Data Dictionary Views
OBJECTS All database objects TABLES Database tables INDEXES Table indexes created to improve query performance VIEWS Database views SEQUENCES Sequences created to automatically generate surrogate key values USERS Database users CONSTRAINTS Table constraints CONS_CONSTRAINTS Table columns that have constraints IND_COLUMNS Indexed columns TAB_COLUMNS All table columns

63 Modifying Tables Unrestricted actions Renaming tables
GF: Rename Old_tableName To new_tableName; Ex Rename Faculty To New_Faculty

64 Modifying Tables ALTER TABLE T_name Action Rename Add Modify Drop
E / D F_old_name To F_new_name (Field_name DataType [Constraint]) (Field_name TYPE ) Column Field_name Enable Const_name Constraint Const_name Disable Const_name Constraint Cons_specif New_one Increase_size Decrease_size

65 Modifying Tables Unrestricted actions Adding new columns
GF: ALTER TABLE table_name ADD (Field Data type Constraint); Ex: ALTER Table Faculty Add (Start_date date);

66 Modifying Tables Unrestricted actions Increasing column sizes
ALTER TABLE table_name MODIFY (column new_datType); Dropping columns ALTER TABLE table_name DROP COLUMN column_name; Dropping constraints ALTER TABLE table_name DROP COSRAINT constraint_name;

67 Modifying Tables Restricted actions Dropping tables
Only allowed if table does not contain any fields that are referenced as foreign keys, or if foreign key constraints are dropped Changing a column’s data specification Only allowed if existing data is compatible with new data specification Decreasing column sizes Only allowed if column does not contain any data Adding constraints Only allowed if existing data meets requirements of new constraint

68 Altering Tables Adding a new field: ALTER TABLE tablename
ADD (fieldname field_specification);

69 Altering Tables Modifying an existing field: ALTER TABLE tablename
MODIFY (fieldname new_field_specification);

70 Altering Tables Deleting an existing field: ALTER TABLE tablename
DROP COLUMN fieldname;

71 Altering Tables Enabling and Disabling Constraints:
ALTER TABLE tablename Enable|Disable CONSTRAINT constraint_name; E.g: Alter Table faculty Disable Constraint faculty_f_id_fk;

72 Deleting Tables Syntax to delete table if no table fields are referenced as foreign keys: DROP TABLE tablename; Syntax to delete table and constraints if table contains fields that are referenced as foreign keys: DROP TABLE tablename CASCADE CONSTRAINTS;

73 DROP: CASCADE CONSTRAINTS
Dropping the table that has the primary key which is used as a foreign key in another table (using CASCADE CONSTRAINTS) will keep the values of that foreign key of the importing table. However, there is no reference at this point


Download ppt "Guide to Oracle 10g Chapter 2: Creating and Modifying Database Tables."

Similar presentations


Ads by Google