The Programmer's Guide
  • About
  • Algorithm
    • Big O Notation
      • Tree
      • Problems
    • Basic Notes
    • Data Structure Implementation
      • Custom LinkedList
      • Custom Stack
      • Custom Queue
      • Custom Tree
        • Binary Tree Implementation
        • Binary Search Tree Implementation
        • Min Heap Implementation
        • Max Heap Implementation
        • Trie Implementation
      • Custom Graph
        • Adjacency List
        • Adjacency Matrix
        • Edge List
        • Bidirectional Search
    • Mathematical Algorithms
      • Problems - Set 1
      • Problems - Set 2
    • Bit Manipulation
      • Representation
      • Truth Tables
      • Number System
        • Java Program
      • Problems - Set 1
    • Searching
    • Sorting
    • Array Algorithms
    • String Algorithms
    • Tree
      • Tree Traversal Techniques
      • Tree Implementation
      • Applications of Trees
      • Problems - Set 1
    • Graph
      • Graph Traversal Techniques
      • Shortest Path Algorithms
      • Minimum Spanning Tree (MST) Algorithms
    • Dynamic Programming
      • Problems - Set 1
    • Recursion
    • Parallel Programming
    • Miscellaneous
      • Problems - Set 1
  • API
    • API Basics
      • What is an API?
      • Types of API
        • Comparison - TBU
      • Synchronous vs Asynchronous API
    • API Architecture
      • Synchronous & Asynchronous Communication
    • API Specification
  • Cloud Computing
    • Cloud Fundamentals
      • Cloud Terminology
      • Core Terminology
      • Cloud Models
      • Cloud Service Models
      • Benefits, Challenges and Risk of Cloud Computing
      • Cloud Ecosystem
  • Database
    • DBMS
      • Types of DBMS
        • Relational DBMS (RDBMS)
        • NoSQL DBMS
        • Object-Oriented DBMS (OODBMS)
        • Columnar DBMS
        • In-Memory DBMS
        • Distributed DBMS
        • Cloud-Based DBMS
        • Hierarchical DBMS
      • DBMS Architecture
      • DBMS Structure
    • SQL Databases
      • Terminology
      • RDBMS Concepts
        • Entity Relationship Diagram (ERD)
          • ERD Examples
        • Normalization
        • Denormalization
        • ACID & BASE Properties
          • ACID Properties
          • BASE Properties
        • Locking and Unlocking
      • SQL Fundamentals
        • SQL Commands
          • DDL (Data Definition Language)
          • DML (Data Manipulation Language)
          • DCL (Data Control Language)
          • TCL (Transaction Control Language)
          • DQL (Data Query Language)
        • SQL Operators
          • INTERSECT
          • EXCEPT
          • MINUS
          • IN and NOT IN
          • EXISTS and NOT EXISTS
        • SQL Clauses
          • Joins
          • OVER
          • WITH
          • CONNECT BY
          • MODEL
          • FETCH FIRST
          • KEEP
          • OFFSET with FETCH
        • SQL Functions
          • Oracle Specific
        • SQL Data Types
          • Numeric Types
          • Character Types
          • Date & Time Types
          • Large Object Types
        • Others
          • Indexing
      • Vendor Specific Concepts
        • Oracle Specific
          • Data Types
          • Character Set
          • Rownum, Rowid, Urowid
          • Order of Execution of the query
          • Keys
          • Tablespace
          • Partition
      • Best Practice
      • Resources & References
        • O’Reilly SQL Cookbook (2nd Edition)
          • 1. Retrieving Records
          • 2. Sorting Query Results
          • 3. Working with Multiple Tables
          • 4. Inserting, Updating, and Deleting
          • 5. Metadata Queries
          • 6. Working with Strings
          • 7. Working with Numbers
          • 8. Date Arithmetic
          • 9. Date Manipulation
          • 10. Working with Ranges
          • 11. Advanced Searching
          • 12. Reporting and Reshaping
          • 13. Hierarchical Queries
          • 14. Odds 'n' Ends
    • SQL vs NoSQL
    • Best Practices
  • Git
    • Commands
      • Setup and Configuration Commands
      • Getting and Creating Projects
      • Tracking Changes
      • Branching and Merging
      • Sharing and Updating Projects
      • Inspection and Comparison
      • Debugging
      • Patching
      • Stashing and Cleaning
      • Advanced Manipulations
    • Workflows
      • Branching Strategies
        • Git Flow
        • Trunk-Based Development
        • GitHub Flow
        • Comparison
      • Merge Strategies
        • Merge
        • Rebase
        • Squash
        • Fast-forward vs No-fast-forward
        • MR vs PR
      • Conflict Resolution
        • Handling Merge Conflicts
        • Merge Conflicts
        • Rebase Conflicts
        • Divergent Branches After git pull
        • Force Push
      • Patch & Recovery
        • Cherry-pick strategies
        • Revert vs Reset
        • Recover from a bad rebase
      • Rebasing Practices
        • Merge vs Rebase
        • Rebase develop branch on main branch
      • Repository Management
        • Working Directory
        • Mirror a repository
        • Convert a local folder to a Git repo
        • Backup and restore a Git repository
  • Java
    • Java Installation
    • Java Distributions
    • Java Platform Editions
      • Java SE
      • Java EE
      • Jakarta EE
      • Java ME
      • JavaFX
    • Java Overview
      • OOP Principles
        • Encapsulation
        • Inheritance
        • Polymorphism
        • Abstraction
          • Abstract Class & Method
          • Interface
            • Functional Interfaces
            • Marker Interfaces
          • Abstract Class vs Interface
      • OOP Basics
        • What is a Class?
          • Types of Classes
        • What is an Object?
          • Equals and HashCode
            • FAQ
          • Shallow Copy and Deep Copy
          • Ways to Create Object
          • Serialization & Deserialization
        • Methods & Fields
          • Method Overriding & Overloading
          • Method Signature & Header
          • Variables
        • Constructors
        • Access Modifiers
      • Parallelism & Concurrency
        • Ways to Identify Thread Concurrency or Parallelism
        • Thread Basics
          • Thread vs Process
          • Creating Threads
          • Thread Context Switching
          • Thread Lifecycle & States
          • Runnable & Callable
          • Types of Threads
          • Thread Priority
        • Thread Management & Synchronisation
          • Thread Resource Sharing
          • Thread Synchronization
            • Why is Synchronization Needed?
            • Synchronized Blocks & Methods
          • Thread Lock
            • Types of Locks
            • Intrinsic Lock (Monitor Lock)
            • Reentrant Lock
          • Semaphore
          • Thread Starvation
          • Thread Contention
          • Thread Deadlock
          • Best Practices for Avoiding Thread Issues
      • Keywords
        • this
        • super
        • Access Modifiers
      • Data Types
        • Default Values
        • Primitive Types
          • byte
          • short
          • int
          • long
          • float
          • double
          • char
          • boolean
        • Non-Primitive (Reference) Types
          • String
            • StringBuilder
            • StringBuffer
              • Problems
            • Multiline String
            • Comparison - String, StringBuilder & StringBuffer
          • Array
          • Collections
            • List
              • Array vs List
              • ArrayList
              • Vector
                • Stack
                  • Problems
              • LinkedList
            • Queue
              • PriorityQueue
              • Deque (Double-Ended Queue)
                • ArrayDeque
                • ConcurrentLinkedDeque - TBU
                • LinkedBlockingDeque - TBU
            • Map
              • HashMap
              • Hashtable
              • LinkedHashMap
              • ConcurrentHashMap
              • TreeMap
              • EnumMap
              • WeakHashMap
            • Set
              • HashSet
              • LinkedHashSet
              • TreeSet
              • EnumSet
              • ConcurrentSkipListSet
              • CopyOnWriteArraySet
        • Specialized Classes
          • BigInteger
          • BigDecimal
            • Examples
          • BitSet
          • Date and Time
            • Examples
          • Optional
          • Math
          • UUID
          • Scanner
          • Formatter
            • Examples
          • Properties
          • Regex (Pattern and Matcher)
            • Examples
          • Atomic Classes
          • Random
          • Format
            • NumberFormat
            • DateFormat
            • DecimalFormat
        • Others
          • Object
          • Enum
            • Pre-Defined Enum
            • Custom Enum
            • EnumSet and EnumMap
          • Record
          • Optional
          • System
          • Runtime
          • ProcessBuilder
          • Class
          • Void
          • Throwable
            • Error
            • Exception
              • Custom Exception Handling
              • Best Practice
            • Error vs Exception
            • StackTraceElement
    • Java Features by Version
      • How New Java Features are Released ?
      • Java Versions
        • Java 8
        • Java 9
        • Scoped Values
        • Unnamed Variables & Patterns
      • FAQ
    • Concepts
      • Set 1
        • Streams
          • flatmap
          • Collectors Utility Class
          • Problems
        • Functional Interfaces
          • Standard Built-In Interfaces
          • Custom Interfaces
        • Annotation
          • Custom Annotation
          • Meta Annotation
        • Generics
          • Covariance and Invariance
        • Asynchronous Computation
          • Future
          • CompletableFuture
          • Future v/s CompletableFuture
          • ExecutorService
            • Thread Pool
            • Types of Work Queues
            • Rejection Policies
            • ExecutorService Implementations
            • ExecutorService Usage
          • Locks, Atomic Variables, CountDownLatch, CyclicBarrier - TBU
          • Parallel Streams, Fork/Join Framework,Stream API with Parallelism - TBU
      • Set 2
        • Standards
          • ISO Standards
          • JSR
            • JSR 303, 349, 380 (Bean Validation)
        • Operator Precedence
      • Set 3
        • Date Time Formatter
        • Validation
      • Set 4
        • Input from User
        • Comparison & Ordering
          • Object Equality Check
          • Comparable and Comparator
            • Comparator Interface
          • Sorting of Objects
          • Insertion Ordering
    • Packages
      • Core Packages
        • java.lang
          • java.lang.System
          • java.lang.Thread
      • Jakarta Packages
        • jakarta.validation
        • javax.validation
      • Third-party Packages
    • Code Troubleshoot
      • Thread Dump
      • Heap Dump
    • Code Quality & Analysis
      • ArchUnit
      • Terminologies
        • Cyclic dependencies
    • Code Style
      • Naming Convention
      • Package Structure
      • Formatting
      • Comments and Documentation
      • Imports
      • Exception Handling
      • Class Structure
      • Method Guidelines
      • Page 1
      • Code Smells to Avoid
      • Lambdas and Streams Style
      • Tools
    • Tools
      • IntelliJ IDEA
        • Shortcuts for MAC
      • Apache JMeter
        • Examples
      • Thread Dump Capture
        • jstack
        • VisualVM - TBU
        • jcmd - TBU
        • JConsole - TBU
        • YourKit Java Profiler - TBU
        • Eclipse MAT - TBU
        • IntelliJ IDEA Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Thread Dump Analyzers - TBU
      • Heap Dump Capture
        • jmap
        • VisualVM - TBU
        • jcmd - TBU
        • Eclipse MAT (Memory Analyzer Tool) - TBU
        • IntelliJ IDEA Profiler - TBU
        • YourKit Java Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Kill -3 Command - TBU
        • jhat (Java Heap Analysis Tool) - TBU
        • JVM Options - TBU
      • Wireshark
        • Search Filters
    • Best Practices
      • Artifact and BOM Versioning
  • Maven
    • Installation
    • Local Repository & Configuration
    • Command-line Options
    • Build & Lifecycle
    • Dependency Management
      • Dependency
        • Transitive Dependency
        • Optional Dependency
      • Dependency Scope
        • Maven Lifecycle and Dependency Scope
      • Dependency Exclusions & Overrides
      • Bill of Materials (BOM)
      • Dependency Conflict Resolution
      • Dependency Tree & Analysis
      • Dependency Versioning Strategies
    • Plugins
      • Build Lifecycle Management
      • Dependency Management
      • Code Quality and Analysis
      • Documentation Generation
      • Code Generation
      • Packaging and Deployment
      • Reporting
      • Integration and Testing
      • Customization and Enhancement
        • build-helper-maven-plugin
        • properties-maven-plugin
        • ant-run plugin
        • exec-maven-plugin
        • gmavenplus-plugin
      • Performance Optimization
    • FAQs
      • Fixing Maven SSL Issues: Unable to Find Valid Certification Path
  • Spring
    • Spring Basics
      • What is Spring?
      • Why Use Spring
      • Spring Ecosystem
      • Versioning
      • Setting Up a Spring Project
    • Core Concepts
      • Spring Core
        • Dependency Injection (DI)
        • Stereotype Annotation
      • Spring Beans
        • Bean Lifecycle
        • Bean Scope
          • Singleton Bean
        • Lazy & Eager Initialization
          • Use Case of Lazy Initialization
        • BeanFactory
        • ApplicationContext
      • Spring Annotations
        • Spring Boot Specific
        • Controller Layer (Web & REST Controllers)
    • Spring Features
      • Auto Configuration
        • Spring Boot 2: spring.factories
        • Spring Boot 3: spring.factories
      • Spring Caching
        • In-Memory Caching
      • Spring AOP
        • Before Advice
        • After Returning Advice
        • After Throwing Advice
        • After (finally) Advice
        • Around Advice
      • Spring File Handling
      • Reactive Programming
        • Reactive System
        • Reactive Stream Specification
        • Project Reactor
          • Mono & Flux
      • Asynchronous Computation
        • @Async annotation
      • Spring Security
        • Authentication
          • Core Components
            • Security Filter Chain
              • HttpSecurity
              • Example
            • AuthenticationManager
            • AuthenticationProvider
            • UserDetailsService
              • UserDetails
              • PasswordEncoder
            • SecurityContext
            • SecurityContextHolder
            • GrantedAuthority
            • Security Configuration (Spring Security DSL)
          • Authentication Models
            • One-Way Authentication
            • Mutual Authentication
          • Authentication Mechanism
            • Basic Authentication
            • Form-Based Authentication
            • Token-Based Authentication (JWT)
            • OAuth2 Authentication
            • Multi-Factor Authentication (MFA)
            • SAML Authentication
            • X.509 Certificate Authentication
            • API Key Authentication
            • Remember-Me Authentication
            • Custom Authentication
          • Logout Handling
        • Authorization
        • Security Filters and Interceptors
        • CSRF
          • Real-World CSRF Attacks & Prevention
        • CORS
        • Session Management and Security
        • Best Practices
      • Spring Persistence
        • JDBC
          • JDBC Components
          • JDBC Template
          • Transaction Management
          • Best Practices in JDBC Usage
          • Datasource
            • Connection Pooling
              • HikariCP
            • Caching
        • JPA (Java Persistence API)
          • JPA Fundamentals
          • ORM Mapping Annotations
            • 1. Entity and Table Mappings
            • 2. Field/Column Mappings
            • 3. Relationship Mappings
            • 4. Inheritance Mappings
            • 5. Additional Configuration Annotations
          • Querying Data
            • JPQL
            • Criteria API
            • JPA Specification
              • Example - Employee Portal
            • Native SQL Queries
            • Named Queries
            • Query Return Types
            • Pagination & Sorting
              • Example - Employee Portal
            • Projection
          • Fetch Strategies in JPA
        • JPA Implementation
          • Hibernate
            • Properties
            • Example
        • Spring Data JPA
          • Repository Abstractions
          • Entity-to-Table Mapping
          • Derived Query Methods
        • Cross-Cutting Concerns
          • Transactions
          • Caching
          • Concurrency
        • Examples
          • Employee Portal
            • API
    • Distributed Systems & Communication
      • Distributed Scheduling
      • Inter-Service Communication
        • 1. RestTemplate
        • 2. WebClient
        • 3. OpenFeign
        • Retry Mechanism
          • @Retryable annotation
            • Example
    • Security & Data Protection
      • Encoding | Decoding
        • Types
          • Base Encoding
            • Base16 - TBD
              • Encoding and Decoding in Java - TBD
            • Base32
              • Encoding and Decoding in Java
            • Base64 -TBD
              • Encoding and Decoding in Java - TBD
          • Text Encoding - TBD
            • Extended ASCII
              • Encoding and Decoding in Java - TBD
                • ISO-8859-1
                • Windows-1252 - TBD
                • IBM Code Pages - TBD
            • ASCII
              • Encoding and Decoding in Java
        • Java Guidelines
          • Text Encoding Decoding Examples
          • Base Encoding Decoding Examples
          • Best Practices and Concepts
          • Libraries
      • Cryptography
        • Terminology
        • Java Cryptography Architecture (JCA)
        • Key Management
          • Key Generation
            • Tools and Libraries
              • OpenSSL
              • Java Keytool
                • Concept
                • Use Cases
            • Key & Certificate File Formats
          • Key Distribution
          • Key Storage
          • Key Rotation
          • Key Revocation
        • Encryption & Decryption
          • Symmetric Encryption
            • Algorithm
            • Modes of Operation
            • Examples
          • Asymmetric Encryption
            • Algorithm
            • Mode of Operation
            • Examples
    • Utilities & Libraries
      • Apache Libraries
        • Apache Camel
          • Camel Architecture
            • Camel Context
            • Camel Endpoints
            • Camel Components
            • Camel Exchange & MEP
          • Spring Dependency
          • Different Components
            • Camel SFTP
        • Apache Commons Lang
      • MapStruct Mapper
      • Utilities by Spring framework
        • FileCopyUtils
    • General Concepts
      • Spring Boot Artifact Packaging
      • Classpath and Resource Loading
      • Configuration - Mapping Properties to Java Class
      • Validations in Spring Framework
        • Jakarta Validation
          • Jakarta Bean Validation Annotations
    • Practical Guidelines
      • Spring Configuration
      • Spring Code Design
  • Software Testing
    • Software Testing Methodologies
      • Functional Testing
      • Non Functional Testing
    • Software Testing Life Cycle (STLC)
    • Integration Test
      • Dynamic Property Registration
    • Java Test Framework
      • JUnit
        • JUnit 4
          • Examples
        • JUnit 5
          • Examples
        • JUnit 4 vs JUnit 5
  • System Design
    • Foundations
      • Programming Paradigms
      • Object-Oriented Design
        • SOLID Principles
        • GRASP Principles
        • Composition
        • Aggregation
        • Association
      • Design Pattern
        • Creational Pattern
        • Structural Pattern
        • Behavioral Pattern
        • Examples
          • Data Collector
          • Payment Processor
        • Design Enhancements
          • Fluent API Design
            • Examples
    • Architectural Building Blocks
      • CAP Theorem
      • Load Balancer
        • Load Balancer Architecture
        • Load Balancing in Java Microservices
          • Client-Side Load Balancing Example
          • Server-Side Load Balancing Example
        • Load Balancer Monitoring Tool
      • Scaling
        • Vertical Scaling (Scaling Up)
        • Horizontal Scaling (Scaling Out)
        • Auto-Scaling
        • Database Scaling via Sharding
      • Caching
        • Pod-Level vs Distributed Caching
      • Networking Metrics
        • Types of Delay
        • Scenario
      • System Characteristics
      • Workload Types
      • Resilience & Failure Handling
    • Performance
      • Why Is My API Sometimes Slow ?
    • Security
      • Security by Design
      • Zero Trust Security Model
      • Zero Trust Architecture
      • Principles
        • CIA
        • Least Privilege Principle
        • Defense in Depth
      • Security Threats & Mitigations
        • OWASP
          • Top 10 Security Threats
          • Application Security Verification Standard
          • Software Assurance Maturity Model
          • Dependency Check
          • CSRFGuard
          • Cheat Sheets
          • Security Testing Guide
          • Threat Dragon
        • Threat Modeling
      • Compliance & Regulation
        • PCI DSS
    • Deployment Patterns
    • Diagrams
      • UML Diagrams
        • PlantUML
          • Class Diagram
          • Object Diagram
          • Sequence Diagram
          • Use Case Diagram
          • Activity Diagram
          • State Diagram
          • Architecture Diagram
          • Component Diagram
          • Timing Diagram
          • ER Diagram (Entity-Relationship)
          • Network Diagram
    • Common Terminologies
    • Problems
      • Reference Materials
      • Cache Design
  • Interview Guide
    • Non-Technical
      • Behavioural or Introductory Guide
      • Project Specific
    • Technical
      • Java Interview Companion
        • Java Key Concepts
          • Set 1
          • Set 2
        • Java Code Snippets
        • Java Practice Programs
          • Set 3 - Strings
          • Set 4 - Search
          • Set 5 - Streams and Collection
      • SQL Interview Companion
        • SQL Practice Problems
          • Set 1
      • Spring Interview Companion
        • Spring Key Concepts
          • Set 1 - General
          • Set 2 - Core Spring
        • Spring Code Snippets
          • JPA
      • Application Server
      • Maven
      • Containerized Application
      • Microservices
    • General
      • Applicant Tracking System (ATS)
      • Flowchart - How to Solve Coding Problem?
Powered by GitBook
On this page
  • About
  • 1. Character (Text) Data Types
  • Description
  • Types
  • Byte and Character Limits
  • Storage and Performance Implications
  • 2. Numeric Data Types
  • Description
  • Types
  • NUMBER(p, s) – General Purpose Numeric Type
  • FLOAT(p) – Approximate with Decimal Precision
  • BINARY_FLOAT and BINARY_DOUBLE – Binary Floating Point Types
  • NUMBER vs BINARY_FLOAT/DOUBLE
  • 3. Date & Time Data Types
  • Description
  • DATE
  • TIMESTAMP
  • TIMESTAMP WITH TIME ZONE (abbreviated: TIMESTAMP WITH TZ)
  • TIMESTAMP WITH LOCAL TIME ZONE (abbreviated: TIMESTAMP WITH LTZ)
  • INTERVAL YEAR TO MONTH
  • INTERVAL DAY TO SECOND
  • 4. Large Object (LOB) Data Types
  • Description
  • LOB Types
  • Internal LOB vs External LOB
  • Storage Characteristics
  • When to Use Which LOB Type?
  • SecureFile LOBs vs BasicFile LOBs
  • Example
  • Best Practices
  • 1. Character (Text) Data Types
  • 2. Numeric Data Types
  • 3. Date & Time Data Types
  • 4. Large Object (LOB) Data Types

Was this helpful?

  1. Database
  2. SQL Databases
  3. Vendor Specific Concepts
  4. Oracle Specific

Data Types

About

Oracle provides a rich set of data types that extend beyond the standard SQL types to support advanced features and performance optimizations.

In Oracle Database, data types define the kind of values a column, variable, or expression can hold. Every data element in Oracle must be declared with an appropriate type that governs:

  • The format and size of stored data

  • The set of valid operations

  • The amount of space allocated in memory or disk

  • Compatibility with other types during operations like joins or comparisons

Oracle offers both standard scalar types (such as numbers, text, and dates) and advanced or abstract types (LOBs, XML, objects).

These types are broadly grouped into categories, each optimized for a specific domain of data representation.

1. Character (Text) Data Types

Description

Character types are used to store text in either fixed or variable length. Oracle supports both single-byte character sets (like ASCII) and multi-byte Unicode character sets.

  • Character semantics vs byte semantics: Length can be interpreted in number of characters or number of bytes.

  • Padding behavior: Fixed-length types are padded with spaces to meet their defined size.

  • Encoding awareness: NCHAR, NVARCHAR2, and NCLOB are designed for internationalization.

VARCHAR is reserved for possible future standardization and should be avoided in production schemas.

For Unicode support, Oracle recommends using AL32UTF8 character set with NCHAR/NVARCHAR2

Types

Data Type
Description
Key Characteristics
Example Value

CHAR(n)

Fixed-length character string, space-padded to length n

- Always stores n bytes - Padded with spaces if shorter

'Y' is stored as 'Y ' in case CHAR(2)

VARCHAR2(n)

Variable-length character string up to n bytes

- Efficient storage - No padding

'Hello' stored as 'Hello'

VARCHAR(n)

ANSI SQL equivalent, internally treated as VARCHAR2

- Supported but not recommended - Future behavior undefined

'Hi' stored as 'Hi'

NCHAR(n)

Fixed-length Unicode character string

- Unicode-aware - Always n characters (not bytes)

'नमस्ते' stored with padding

NVARCHAR2(n)

Variable-length Unicode character string up to n characters

- Unicode-aware - No padding

'你好' stored as-is

Byte and Character Limits

Oracle imposes specific maximum limits depending on the data type and database settings (especially character set and semantics).

Character semantics: If the database or column uses character semantics, the limits apply to characters instead of bytes. This is useful in multibyte/Unicode character sets.

Data Type
Max Length (Bytes)
Max Length (Characters)
Notes

CHAR(n)

2000 bytes

Depends on byte-per-char

Fixed-length; may waste space if short data is stored.

VARCHAR2(n)

4000 bytes (SQL), 32767 bytes (PL/SQL)

Depends on byte-per-char

Most common string type; n is byte count unless CHAR semantics used.

NCHAR(n)

2000 bytes

1000 characters (UTF-16)

Always uses national character set (usually UTF-16).

NVARCHAR2(n)

4000 bytes (SQL), 32767 bytes (PL/SQL)

2000 characters (UTF-16)

Used for Unicode multilingual data.

VARCHAR(n)

Same as VARCHAR2

Deprecated

Reserved by Oracle; avoid using.

Storage and Performance Implications

Data Type
Storage Efficiency
Performance Impact
Best Use Case

CHAR(n)

Low (always fixed)

Slower for short values

Fields with consistent, small size (e.g., 'Y'/'N')

VARCHAR2(n)

High

Fast and efficient

General-purpose strings

NCHAR(n)

Medium

Slight overhead (Unicode)

Fixed-width internationalized values

NVARCHAR2(n)

Medium-High

More space needed (UTF-16)

Multilingual applications

VARCHAR(n)

Same as VARCHAR2

No gain; discouraged

Not recommended

2. Numeric Data Types

Description

Numeric types in Oracle are highly flexible and configurable. They support exact (fixed-point) and approximate (floating-point) representations.

  • Precision (p): Total number of significant digits.

  • Scale (s): Number of digits to the right of the decimal point.

  • Overflow and rounding: Operations that exceed scale may be rounded or truncated based on context.

  • Binary vs decimal: Oracle supports both binary floats and precise decimal arithmetic.

Types

Oracle provides two main categories of numeric types:

  1. Exact Numeric Types

    • NUMBER

    • INTEGER, INT, SMALLINT, DEC, DECIMAL, NUMERIC (ANSI-compatible synonyms)

  2. Approximate Numeric Types

    • BINARY_FLOAT

    • BINARY_DOUBLE

NUMBER(p, s) – General Purpose Numeric Type

  • A variable-precision numeric type that can store integers and decimals.

  • p is precision (total number of significant digits).

  • s is scale (number of digits to the right of the decimal point).

Ranges

  • Maximum precision: 38 digits

  • Scale range: -84 to 127

Examples

Declaration
Description
Acceptable Values

NUMBER

Maximum flexibility. Default precision/scale.

42, 3.1415, -9999.99

NUMBER(5)

Up to 5 digits. No decimal.

12345, -9999

NUMBER(7, 2)

7 digits total, 2 after decimal.

12345.67

NUMBER(*, 0)

Any number of digits, no decimal.

Integer values only

Behavior

  • If the number exceeds the specified precision, Oracle raises an error.

  • If scale is higher than actual decimals, Oracle appends trailing zeroes.

  • If scale is lower, Oracle rounds the value.

ANSI-Compatible Synonyms

These are alternative names mapped to NUMBER:

Synonym
Oracle Equivalent

INTEGER

NUMBER(38,0)

INT

NUMBER(38,0)

SMALLINT

NUMBER(38,0)

DEC

NUMBER(p,s)

DECIMAL

NUMBER(p,s)

NUMERIC

NUMBER(p,s)

FLOAT(p) – Approximate with Decimal Precision

  • Floating-point number with p bits of binary precision.

  • FLOAT(p) is internally treated as NUMBER(p).

Although named FLOAT, Oracle does not use IEEE floating point here unless we use BINARY_FLOAT or BINARY_DOUBLE.

Example

  • FLOAT(10) means up to 10 digits of precision.

Use FLOAT with caution as its behavior may be misleading—use BINARY_FLOAT or BINARY_DOUBLE if we truly need floating-point arithmetic.

Example 1: Basic FLOAT column

CREATE TABLE sample_float_table (
    id        NUMBER,
    value     FLOAT -- same as NUMBER with default precision (usually 126)
);

We can insert values like:

INSERT INTO sample_float_table (id, value) VALUES (1, 12345.6789);
INSERT INTO sample_float_table (id, value) VALUES (2, -0.000345);

Example 2: FLOAT with precision

CREATE TABLE precise_float_table (
    id         NUMBER,
    value      FLOAT(10) -- same as NUMBER(10)
);

This means the column value can store up to 10 significant digits, e.g.,

INSERT INTO precise_float_table VALUES (1, 123456.7890); -- OK
INSERT INTO precise_float_table VALUES (2, 1234567890.12); -- Error or rounded

BINARY_FLOAT and BINARY_DOUBLE – Binary Floating Point Types

These types use IEEE 754 format for representing approximate decimal numbers.

Data Type
Size
Precision
Use Case

BINARY_FLOAT

32 bits

~6 digits

Fast approximate calculations

BINARY_DOUBLE

64 bits

~15 digits

Higher precision computations

Key Characteristics

  • Support NaN, positive/negative infinity, and subnormal numbers.

  • Faster than NUMBER due to hardware-level operations.

  • Cannot be indexed using B-tree indexes.

  • Not exact—do not use in financial or accounting systems.

Examples

CREATE TABLE temperature_data (
  city_name VARCHAR2(100),
  avg_temp  BINARY_FLOAT
);

INSERT INTO temperature_data VALUES ('Delhi', 42.57);

NUMBER vs BINARY_FLOAT/DOUBLE

Feature

NUMBER

BINARY_FLOAT / DOUBLE

Precision

Exact (up to 38 d)

Approximate

Storage

Variable

Fixed (4 or 8 bytes)

Performance

Slower

Faster

Usage

Financial

Scientific, statistical

Indexing

B-tree supported

Not supported

Rounding

Controlled

IEEE-based

3. Date & Time Data Types

Description

Temporal types store points in time or durations. Oracle aligns partially with SQL standards but also adds its own enhancements for timezone-aware storage and interval management.

  • Oracle’s DATE includes time: Unlike standard SQL, DATE in Oracle includes both date and time down to seconds.

  • Fractional seconds and precision: Timestamps support up to 9 digits of fractional seconds.

  • Timezone handling: Oracle supports both session-relative and absolute time zones.

  • Intervals as durations: Represent spans of time, not absolute moments.

DATE

Stores both date and time values, accurate to the second. This is the most basic and commonly used temporal type in Oracle.

  • Internally stored as 7 bytes:

    • Century, Year, Month, Day, Hour, Minute, Second

  • Default format: DD-MON-YY (can be changed via NLS_DATE_FORMAT)

  • Does not support fractional seconds or time zones.

DATE '2024-06-05'
TO_DATE('2024-06-05 14:30:00', 'YYYY-MM-DD HH24:MI:SS')

TIMESTAMP

Extends DATE by including fractional seconds (up to 9 digits of precision). Used where higher accuracy is required.

  • Default fractional precision is 6 digits.

  • Internally stored as 11 bytes.

  • No time zone support.

Syntax:

TIMESTAMP [(fractional_seconds_precision)]
TIMESTAMP '2024-06-05 14:30:00.123456'

TIMESTAMP WITH TIME ZONE (abbreviated: TIMESTAMP WITH TZ)

Adds time zone offset information to a timestamp, making it suitable for storing absolute moments in time globally.

  • Stores time in UTC and retains the time zone offset.

  • Time zone can be expressed as an offset (e.g., +05:30) or region name (e.g., 'Asia/Kolkata').

  • Useful for distributed systems.

Syntax:

TIMESTAMP [(fractional_seconds_precision)] WITH TIME ZONE
TIMESTAMP '2024-06-05 14:30:00.123456 +05:30'

TIMESTAMP WITH LOCAL TIME ZONE (abbreviated: TIMESTAMP WITH LTZ)

Stores the timestamp in UTC internally, but displays it in the user's session time zone. Useful for applications with users across time zones.

  • Time zone information is not stored, but inferred from session.

  • Automatically adjusted during storage and retrieval.

  • Ideal for user-facing logs or event timestamps.

Syntax:

TIMESTAMP [(fractional_seconds_precision)] WITH LOCAL TIME ZONE
TIMESTAMP '2024-06-05 14:30:00.123456' AT LOCAL

INTERVAL YEAR TO MONTH

Represents a duration (not a point in time) in terms of years and months.

  • Used to add/subtract months or years to/from a date.

  • Cannot include days, hours, or minutes.

  • Useful in business date arithmetic (e.g., contract terms).

INTERVAL YEAR [(precision)] TO MONTH
INTERVAL '2-3' YEAR TO MONTH   -- 2 years, 3 months

INTERVAL DAY TO SECOND

Represents a duration in days, hours, minutes, seconds, and fractional seconds.

  • Supports up to 9 digits of fractional second precision.

  • Used for time spans, e.g., tracking elapsed time.

Syntax:

INTERVAL DAY [(day_precision)] TO SECOND [(fractional_seconds_precision)]
INTERVAL '5 12:30:15.123456' DAY TO SECOND
-- 5 days, 12 hours, 30 minutes, 15.123456 seconds

4. Large Object (LOB) Data Types

Description

Large Object (LOB) data types in Oracle are designed to store large blocks of unstructured data, such as:

  • Large text (e.g. articles, emails, XML)

  • Binary files (e.g. images, PDFs, videos)

  • External file references (e.g. stored on the OS filesystem)

LOBs are essential for enterprise systems dealing with document management, media storage, or data lakes inside databases.

  • Can store data up to 4 GB and beyond (depending on configuration and database block size).

  • Stored separately from table rows, though the row holds a locator to the LOB data.

  • Supports streaming APIs for efficient reading/writing.

  • Supports transactional consistency (except BFILE).

  • Can be deferred-loaded (loaded only when accessed), saving memory.

LOB Types

LOB Type
Description
Use Case

CLOB (Character LOB)

Stores large character data in database character set

Text documents, HTML, XML

NCLOB (National CLOB)

Same as CLOB, but uses national character set (Unicode)

Multilingual documents

BLOB (Binary LOB)

Stores large binary data

Images, videos, PDFs, encrypted files

BFILE

Stores a pointer to a file in the OS file system (read-only)

External file referencing

Internal LOB vs External LOB

Feature

Internal LOB (BLOB, CLOB, NCLOB)

External LOB (BFILE)

Stored In

Database tablespace

OS file system

Read/Write

Fully readable and writable

Read-only from SQL

Transactional

Yes

No

Secure

Protected under Oracle security

Depends on OS permissions

Backup

Included in database backup

Must back up separately

Storage Characteristics

Oracle stores LOB data out-of-line by default (separate from table row), but:

  • If the LOB data is small (less than ~4 KB), it can be stored in-line using ENABLE STORAGE IN ROW.

  • LOBs can use basicfiles (legacy) or securefiles (modern, better performance & compression).

When to Use Which LOB Type?

Requirement
Recommended LOB

Long text documents

CLOB

Multilingual/unicode documents

NCLOB

Images, media, encrypted files

BLOB

Link to file outside database

BFILE

SecureFile LOBs vs BasicFile LOBs

Oracle 11g+ introduced SecureFile LOBs for better performance and manageability:

Feature
BasicFile
SecureFile

Compression

No

Yes

Encryption

No

Yes

Deduplication

No

Yes

Space-saving

Minimal

Significant

Performance

Lower

Higher

Enable SecureFiles like this:

CREATE TABLE image_store (
    id NUMBER,
    img BLOB
) LOB (img) STORE AS SECUREFILE (COMPRESS HIGH ENCRYPT);

Example

Step 1: Oracle Table Definition

CREATE TABLE user_photos (
    id NUMBER PRIMARY KEY,
    username VARCHAR2(100),
    photo BLOB
);

Step 2: JDBC Code – Insert Image into BLOB

import java.sql.*;
import java.io.*;

public class ImageUploader {
    public static void main(String[] args) {
        String url = "jdbc:oracle:thin:@//localhost:1521/orclpdb";
        String username = "your_username";
        String password = "your_password";
        String imagePath = "/path/to/photo.jpg";

        try (
            Connection conn = DriverManager.getConnection(url, username, password);
            PreparedStatement pstmt = conn.prepareStatement(
                "INSERT INTO user_photos (id, username, photo) VALUES (?, ?, ?)");
            FileInputStream fis = new FileInputStream(new File(imagePath))
        ) {
            pstmt.setInt(1, 101);
            pstmt.setString(2, "john_doe");
            pstmt.setBinaryStream(3, fis, fis.available()); // set BLOB as stream

            int rows = pstmt.executeUpdate();
            System.out.println("Rows inserted: " + rows);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Step 3: Retrieve Image from Oracle and Save as File

import java.sql.*;
import java.io.*;

public class ImageDownloader {
    public static void main(String[] args) {
        String url = "jdbc:oracle:thin:@//localhost:1521/orclpdb";
        String username = "your_username";
        String password = "your_password";
        String outputFile = "/path/to/output.jpg";

        try (
            Connection conn = DriverManager.getConnection(url, username, password);
            PreparedStatement pstmt = conn.prepareStatement(
                "SELECT photo FROM user_photos WHERE id = ?");
        ) {
            pstmt.setInt(1, 101);
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                InputStream input = rs.getBinaryStream("photo");
                OutputStream output = new FileOutputStream(outputFile);

                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = input.read(buffer)) != -1) {
                    output.write(buffer, 0, bytesRead);
                }

                System.out.println("Image saved to: " + outputFile);
                output.close();
                input.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Best Practices

1. Character (Text) Data Types

Practice
Recommendation

Use variable-length strings

Prefer VARCHAR2 over CHAR to save space and avoid padding overhead.

Avoid deprecated types

Do not use VARCHAR; use VARCHAR2 instead, as Oracle may redefine VARCHAR.

Enable character semantics

Use CHARACTER SET and CHARACTER LENGTH SEMANTICS wisely, especially in multilingual applications.

Use NCHAR/NVARCHAR2 for Unicode

When storing multilingual data (e.g., Chinese, Arabic), use national character types.

Set proper length

Avoid allocating the max (e.g., 4000) unless necessary; oversized columns waste memory and I/O.

Normalize case if required

Store and compare text in consistent case (e.g., all UPPER) for indexing and querying.

2. Numeric Data Types

Practice
Recommendation

Use NUMBER(p,s) for precision

Always define precision and scale to avoid unexpected rounding or overflow.

Avoid overly large precision

Don't default to NUMBER without limits; specify NUMBER(10,2) for currency, for example.

Choose integer types wisely

For whole numbers, use NUMBER(p,0) (e.g., NUMBER(5,0) for counters).

Use BINARY_FLOAT/BINARY_DOUBLE only for scientific computing

They are faster but less precise—avoid for financial or critical data.

Avoid FLOAT for exact values

It's an approximate representation—use only when precision is not critical.

Use constraints for validation

Apply CHECK constraints for acceptable numeric ranges when business rules allow.

3. Date & Time Data Types

Practice
Recommendation

Use TIMESTAMP instead of DATE when fractional seconds matter

DATE only stores up to seconds; TIMESTAMP supports micro/nanoseconds.

Prefer TIMESTAMP WITH TIME ZONE for globally relevant data

It ensures consistent time tracking across regions.

Avoid TIMESTAMP WITH LOCAL TIME ZONE unless session-based logic is needed

Its behavior depends on user sessions and can lead to confusion.

Use INTERVAL types for durations, not DATE subtraction

INTERVAL types clearly express intent and avoid conversion issues.

Normalize time zones in application logic

Ensure consistent time zone use between DB and application layer.

Avoid storing as CHAR or VARCHAR2

Store actual dates/times using native types for indexing, sorting, and formatting.

4. Large Object (LOB) Data Types

Practice
Recommendation

Prefer CLOB/BLOB over LONG/LONG RAW

The latter are deprecated and unsupported in many modern features.

Use BLOB for binary content (images, audio)

Do not store binary files as RAW or encode them as base64 in text fields.

Use CLOB for large text (documents, logs)

Enables full-text indexing and large-capacity storage.

Consider chunked access for very large LOBs

Use streaming APIs (DBMS_LOB) to read/write in pieces instead of loading full content.

Use SecureFile LOBs if available

They provide better performance and features (e.g., compression, deduplication).

Avoid unnecessary LOB indexing

Index only if you need full-text search; LOBs are heavy and slow to scan.

Store large static files outside database

Use BFILE for read-only access to large external content when database storage is not required.

PreviousOracle SpecificNextCharacter Set

Last updated 18 hours ago

Was this helpful?