Download as pdf or txt
Download as pdf or txt
You are on page 1of 70

Oracle Developer Essentials: Data Types

Why Data Types Matter

David Berry
http://buildingbettersoftware.blogspot.com/
Why data types matter

Character data types


Data Types Numeric data types
Roadmap
Date/time data types

Large object data types


Oracle Developer Essentials Course Sequence

Views,
Tables and
Data Types Synonyms
Indexes
and Triggers
Why Data Types Matter

Ease of Use

• Store data how an application would expect it


• Avoid need to convert data in data access layer

Storage and Performance Considerations

• Incorrect data type may require more storage


• Data type impacts performance

Built in Functionality
• Take advantage of what Oracle offers
Everything is a VARCHAR

The Antipattern The Impact

All columns are defined as To perform numeric functions, a


VARCHAR data type, even type conversion must occur
columns that contain numeric
data Improper sort order

Need to convert values to


numbers in our application
Everything is a VARCHAR – Date Edition

The Antipattern The Impact

Instead of using date/time data Cannot use any Oracle date/time


types, we store all date/time data functions
as VARCHAR2 columns
Values may not sort correctly

Ability to store illegal dates


(February 30)

Need to parse and encode dates


in our application
Numbers With Leading Zeros

The Antipattern The Impact

A numeric value contains a Leading zeros are not retained in


significant leading zero, but is a numeric data type
stored as a number
Application must “fix” the value
Examples include zip codes and before displaying
bank routing numbers
Using a CHAR Instead of a VARCHAR

The Antipattern The Impact

String data is stored in CHAR Storing string data takes


columns instead of VARCHAR significantly more space
columns
Need to trim data before use

Bind variable queries may not


match column values
Using an NVARCHAR2 Just in Case

The Antipattern The Impact

All character columns are defined Depending on your national


as NVARCHAR2 columns, just in character set, string data may
case we ever need to store foreign take significantly more space
language characters
Performance may be degraded
THINK!
Use the knowledge of the
data you need to store to
choose the correct data type
Module Summary

Roadmap for modules on data types

Why data types matter

PL/SQL DUMP() function


DUMP() Function
Outputs a string that
describes the raw bytes
stored in a column
DUMP() Function Output

Indicator of the column data type


(http://bit.ly/Oracle12cDataTypeSummary)

Length of value stored in row (in bytes)

Array of the bytes Oracle stores for the value


Calling the DUMP() Function

SELECT
state_name,
DUMP(state_name),
date_of_statehood,
DUMP(date_of_statehood, 16)
FROM states;
Character Data Types

David Berry
http://buildingbettersoftware.blogspot.com/
Module Introduction

Fixed length vs.


Character data
variable width
types overview
character types

Character sets,
Oracle RAW data
VARCHAR2 and
type
NVARCHAR2 types
Character Data Types in Oracle

Space padded Variable length

Default
CHAR VARCHAR2
character set

Unicode
NCHAR NVARCHAR2
character set
Column Specifications

CREATE TABLE world_cities


(
country_code CHAR(2),
country_name VARCHAR2(40 byte),
captital_city VARCHAR2(40 char),
national_country_name NCHAR(2),
national_country_name NVARCHAR2(40),
national_capital_name NVARCHAR2(40)
);
Character Column Maximums

CHAR,
2000 bytes
NCHAR

4000 bytes
VARCHAR2,
NVARCHAR2 32,767 bytes
(Oracle 12c - MAX_STRING_SIZE=EXTENDED)
Attempt to insert/update
Oracle will throw an error
column with value longer
(data is not auto-truncated)
than column size
CHAR vs. VARCHAR2

Field Type: VARCHAR2(16)

I D A H O

5 bytes of data

Field Type: CHAR2(16)

I D A H O

16 bytes of data
Problems With Space Padded Data

Additional Trim data Require


storage before use padding of
bind variables
Character Data Type Recommendation

Use VARCHAR2/NVARCHAR2 in tables you create

Understand CHAR behavior when you encounter these


CHAR/VARCHAR2 vs. NCHAR/NVARCHAR2
What are the differences?
How do I choose when to use each one?
National Language Settings and Strings

CHAR, VARCHAR2 NCHAR, NVARCHAR2

Data is stored in the default Data is stored in national


character set of the database character set of the database
(Unicode)
NLS Character Sets

SELECT *
FROM nls_database_parameters
WHERE parameter IN
('NLS_CHARACTERSET', 'NLS_NCHAR_CHARACTERSET');

PARAMETER VALUE
------------------------- --------------------
NLS_CHARACTERSET WE8MSWIN1252
NLS_NCHAR_CHARACTERSET AL16UTF16
Character Set Properties

Character Set Properties


WE8MSWIN1252 Western European characters
One byte per character

Most ASCII characters are one byte


AL32UTF8
Good when ASCII characters most common

AL16UTF16 Most characters are two bytes


ASCII characters are two bytes
Character Set Implications

Multi-byte characters cannot be stored in single byte


Data integrity character set columns

Data storage Character set impacts length of data on disk

Column data Character set impacts what length of strings can be


length stored
Character Set Implications on Data Type Choice

• Data stored in default character set


CHAR
• Best choice if you only need characters in this
VARCHAR2 character set

• Data is stored in national character set


NCHAR (Unicode)
NVARCHAR2 • Use when you need characters outside of
default character set
Character Sets and Data Type Selection

CHAR/VARCHAR2 limited to characters in default


What characters character set
can be stored
NCHAR/NVARCHAR2 can store virtually any character

Number of bytes per character varies by


character set
Storage
considerations Affects length of string you can store

Affects amount of space taken up by row


VARCHAR vs. VARCHAR2

VARCHAR data type currently synonymous with VARCHAR2

VARCHAR behavior in Oracle may change at some point in


the future

Oracle recommends always using VARCHAR2


RAW Data Type

Purpose Store raw binary data (an array of bytes)

2000 bytes
Maximum Size 32,767 bytes
(Oracle 12c - MAX_STRING_SIZE=EXTENDED)
RAW Data Type

CREATE TABLE data_transfer_files


(
file_id NUMBER(6),
file_receive_time DATE,
file_size NUMBER(10),
file_checksum RAW(64)
);
Basic of character data types

Differences between fixed and


variable length character data
Module types
Summary Differences between VARCHAR2
and NVARCHAR2 data types

Oracle RAW data type


Numeric Data Types

David Berry
http://buildingbettersoftware.blogspot.com/
Module Introduction

Oracle NUMBER Native numeric


Identity column
type data types
NUMBER(p, s)
Precision (p) • Total number of digits in the number
• Maximum of 38

Scale (s) • Digits to the right of the decimal place


• Can be from -84 to 127

Defaults • Number is stored as given if no


precision/scale specified
• Scale defaults to 0 if only precision given
NUMBER Data Type in Use

Value Data Type Result

123,456.78 NUMBER 123456.78

123,456.78 NUMBER(6) 123457

123,456.78 NUMBER(8,2) 123456.78

123,456.78 NUMBER(7,2) Exceeds precision error

123,456.78 NUMBER(8,3) Exceeds precision error


NUMBER Data Type Range Examples

Data Type Range


NUMBER(6) -999,999 to 999,999

NUMBER(8,2) -999,999.99 to 999,999.99

NUMBER(7,2) -99,999.99 to 99,999.99

NUMBER(8,3) -99,999.999 to 99,999.999


Negative Scale

 Negative scale can be used to round to the left of the decimal place

Value Data Type Result


123,456.78 NUMBER(8, -2) 123500
NUMBER Data Type Characteristics

Software Exact
data type precision
Native Numeric Data Types

• IEEE 32 bit floating point value


BINARY_FLOAT • Range of +/- 3.4E+38
• Precision of 6-7 digits

• IEEE 64 bit floating point value


BINARY_DOUBLE • Range of +/- 1.79E+308
• Precision of 15 digits
Native Numeric Types Properties

IEEE 754 compliant Wide Range Approximate Values

Can take advantage of Can store smaller/larger Not suitable for


hardware acceleration numbers than NUMBER financial calculations
type
Date and Time Data Types

• Precision to one second


DATE • January 1, 4712 BC, to December 31, 9999 AD

• 0-9 digits for fractional seconds


TIMESTAMP • Default precision is 6 digits (microseconds)

TIMESTAMP WITH • Same precision as TIMESTAMP


TIME ZONE • Time zone data stored with value

TIMESTAMP WITH • Value will be converted to database time zone


LOCAL TIME ZONE • Converted to client time zone when queried
Identity Columns
Identity Columns

Oracle will auto-generate a sequential value for a


numeric field

In versions prior to 12c, combination of trigger


and sequence used for this behavior

Useful for surrogate primary keys


Defining Identity Columns

CREATE TABLE students


(
student_id NUMBER(10) GENERATED ALWAYS
IDENTITY START WITH 100,
first_name VARCHAR2(40) NOT NULL,
middle_name VARCHAR2(40) NOT NULL,
last_name VARCHAR2(40) NOT NULL,
gender VARCHAR2(1) NOT NULL,
street_address VARCHAR2(50) NOT NULL,
city VARCHAR2(30) NOT NULL,
state VARCHAR2(2) NOT NULL
);
Generating Identity Values

Oracle always generates a value for identity column


GENERATED ALWAYS
Inclusion of a value results in an error

Value generated if no value provided


GENERATED BY DEFAULT
Attempt to insert NULL causes error

GENERATED BY DEFAULT Value generated if no value or NULL value


ON NULL provided
Identity Value Options

Option Definition

START WITH <value> Controls the initial value to use for the
identity column

INCREMENT BY <value> Defines the interval between generated


values

CACHE <value> Defines how many values Oracle should pre-


allocate for performance reasons

http://bit.ly/Ora12cCreateSequence
Using Date Time Data Types

CREATE TABLE date_time_test


(
event_id INT,
event_message VARCHAR2(50),
event_date DATE,
event_timestamp TIMESTAMP,
event_timestamp_timezone TIMESTAMP(3) WITH TIME ZONE,
event_timestamp_local TIMESTAMP(9) WITH LOCAL TIME ZONE
);
GRANT Command

 Basic syntax

GRANT privileges ON object TO user;

 Examples
GRANT select ON courses TO students_web, faculty_web;

GRANT select, update ON students TO students_web;


REVOKE Command

 Basic syntax

REVOKE privileges ON object FROM user;

 Examples
REVOKE update ON students FROM students_web, faculty_web;

REVOKE insert ON courses FROM faculty_web;


Table Privileges

Privilege Description
ALTER Change the table definition using ALTER TABLE
DEBUG Debug the PL/SQL in a trigger on the table
DELETE Remove rows on the table via a DELETE statement
INDEX Create an index on the table
INSERT Add new rows to the table via an INSERT statement
READ Allows queries from the table but not a SELECT … FOR
UPDATE statement (pessimistic locking)
REFERENCES Allows a foreign key constraint to the table (can only be
granted to a user, not a role)
SELECT Allows reads from the table including SELECT … FOR
UPDATE statements
UPDATE Modify rows in the table via an UPDATE statement
View Privileges

Privilege Description
DEBUG Debug the PL/SQL in a trigger on the view
DELETE Remove rows on the view via a DELETE statement
INSERT Add new rows to the via via an INSERT statement
READ Allows queries from the view but not a SELECT … FOR
UPDATE statement (pessimistic locking)
REFERENCES Allows a foreign key constraint to the view (can only be
granted to a user, not a role)
SELECT Allows reads from the view including SELECT … FOR
UPDATE statements
UPDATE Modify rows in the view via an UPDATE statement
Column Level Privileges

GRANT select, update ON students TO students_web;

User students_web can update any column


on the students table
Column Level Privileges

GRANT update (street_address, city, state, telephone, email)


ON students TO students_web;

User students_web can only update


columns included in this list

• Individual columns can be supplied for the insert,


update and references privileges
Using a View to Restrict Visible Columns

• A table contains columns I do not want


Problem
another user to see

Column Level
• Not available for the select privileges
Privileges

• Create a view with only the columns you


Solution want to expose
• Grant select access to the view
Example – Employee Phone Directory

desc employees;

Name Null Type


--------------- -------- ------------
EMPLOYEE_ID NOT NULL NUMBER(8),
FIRST_NAME NOT NULL VARCHAR2(30),
LAST_NAME NOT NULL VARCHAR2(30),
DATE_OF_BIRTH NOT NULL DATE,
TITLE NOT NULL VARCHAR2(30),
DEPARTMENT_ID NOT NULL NUMBER(4),
PHONE NOT NULL VARCHAR2(20),
EMAIL NOT NULL VARCHAR2(60),
SALARY NOT NULL NUMBER(10,2)
Example – Employee Phone Directory

CREATE VIEW v_employee_contact_info AS


SELECT
employee_id, first_name, last_name,
title, department_id, phone, email
FROM employees;

GRANT select ON v_employee_contact_info TO web_user;


Stored Procedure/Function Privileges

EXECUTE Access to run the procedure or function

DEBUG Access to debug through the procedure/function


Procedure Execution Permissions

students schema

execute Procedure:
UpdateGrade()

user

Procedures execute with


the permissions of the Table:
owner of the procedure course_enrollments
Direct Table Access and Security Concerns

SELECT user_id
FROM users users
WHERE username = ? user_id username password
AND password = ?
Login 101 jason 7c222…
Process 102 chad ff9e4…
103 amanda 1fff8…

Direct access to the table


Stored Procedures and Security

function
Login
check_password(
Process
username, password)

users
user_id username password
101 jason 7c222…
Access restricted to
102 chad ff9e4…
one use case
103 amanda 1fff8…
Grant EXECUTE privilege to allow users to run

Users only need EXECUTE privilege, not


Stored access to underlying objects
Procedure
Can restrict access to a specific use case
Wrap Up
Consider using when you have sensitive data
Roles Introduction

GRANT select ON departments TO john;


GRANT select ON courses TO john;
GRANT select ON students TO john;

GRANT select ON departments TO erica;


GRANT select ON courses TO erica;
GRANT select ON students TO erica;

GRANT select ON departments TO robert;


GRANT select ON courses TO robert;
GRANT select ON students TO robert;

Database Roles

Definition Container to group a set of privileges together

Benefit Simplify management of permissions


Role Management

-- Create the role


-- Most likely will need to be done by a DBA
CREATE ROLE technology_staff;

-- Assign privileges to role


GRANT select ON departments TO technology_staff;
GRANT select ON courses TO technology_staff;
GRANT select ON students TO technology_staff;

-- Assign the role to users


GRANT technology_staff TO john;
GRANT technology_staff TO erica;
GRANT technology_staff TO robert;
Thoughts on Database Privileges

Principle of Least Privilege


Only grant access to the data that an application or user absolutely
needs and no more

Defense in Depth
Use multiple mechanisms to secure access to your data
Some Good Practices

Separate application users from the schema owner


Schema owner has full access to all objects
Schema owner can perform DDL statements

Use a separate Oracle user for each application


Applications usually have different access requirements
Easier to tell what application a statement was executed from

Take time to assign appropriate access permissions


Don’t rely solely on application code to enforce security
Only give a user the access they need
Multiple users
GRANT and REVOKE
Object privileges

Summary Column level permissions


Stored procedures and security
Database roles
Security principles

You might also like