Oracle Database
Oracle Database, developed by Oracle Corporation, is one of the world’s most popular and powerful relational database management systems (RDBMS). It is widely used in enterprise environments for its scalability, reliability, and advanced features.
Oracle Database stands out due to:
- High Availability: Features like Real Application Clusters (RAC) and Data Guard provide robust solutions for minimizing downtime and ensuring business continuity.
- Scalability: Supports massive data volumes and concurrent users, making it suitable for large-scale enterprise applications.
- Advanced Security: Offers comprehensive security features including encryption, auditing, and fine-grained access control.
- Comprehensive Tooling: Includes tools for backup, recovery, monitoring, and performance tuning.
- PL/SQL Support: Oracle’s procedural extension to SQL enables complex business logic within the database.
- Multi-Model Database: Supports relational, JSON, XML, spatial, and graph data models.
- Cloud Integration: Oracle Database is available both on-premises and as a cloud service (Oracle Cloud Infrastructure).
- Strong Community & Support: Backed by extensive documentation, a large user community, and professional support.
Oracle Database continues to evolve with regular updates, new features, and cloud-native capabilities, maintaining its position as a leading choice for mission-critical data management.
Web Site
Tools
- SQL*Plus
- Oracle SQL Developer
- Oracle Enterprise Manager
- Data Pump (expdp/impdp)
- RMAN (Recovery Manager)
- Oracle APEX
Basic
show all oracle table
|
|
Date Time manipulating
|
|
Date/Time Data Types & Functions in Oracle
Oracle handles date and time values differently from some other databases (such as MySQL or SQL Server). Notably, Oracle does not have a DATETIME data type or a TO_DATETIME() function—its DATE type natively includes both date and time components. All date/time types are stored as structured binary objects rather than strings (their display format in a SQL client is determined by session settings like NLS_DATE_FORMAT, or explicitly formatted into a VARCHAR2 string via TO_CHAR(...)).
-
DATE- Description: Stores both date and time down to seconds (Year, Month, Day, Hour, Minute, Second; 7 bytes). It does not store fractional seconds or time zones.
- Create / Current Value:
SYSDATE(database server date/time) orCURRENT_DATE(session time zone date/time). - Convert:
TO_DATE(string, format)parses a string into aDATEobject;TO_CHAR(date, format)converts it to a string. - Manipulate: Supports
TRUNC(date)(resets time to00:00:00while remaining aDATEobject), numeric day arithmetic (sysdate - 2),INTERVALarithmetic,ADD_MONTHS, andLAST_DAY. (Note: ForDATEvalues,EXTRACTonly supportsYEAR,MONTH, andDAY; to extractHOUR,MINUTE, orSECOND, cast toTIMESTAMPor useTO_CHAR).
-
TIMESTAMP- Description: Extends
DATEby adding fractional seconds (up to 9 digits of precision, default 6; 7–11 bytes), without storing a time zone. - Create / Current Value:
LOCALTIMESTAMPreturns a plainTIMESTAMPin the current session’s time zone (insertingSYSTIMESTAMPinto aTIMESTAMPcolumn also implicitly strips the time zone). - Convert:
TO_TIMESTAMP(string, format)parses a string (including.FFfractional seconds) into aTIMESTAMPobject;TO_CHAR(timestamp, format)formats it to a string. - Manipulate: Use
INTERVALarithmetic (e.g.,timestamp_col + INTERVAL '30' MINUTE) andEXTRACT(field FROM timestamp)to preserve theTIMESTAMPtype and fractional seconds. (Note:TRUNC(timestamp)and numeric addition liketimestamp_col + 1implicitly return aDATEvalue, losing fractional-second precision). - When & Why to Use (vs.
TIMESTAMP WITH TIME ZONE):- Single-timezone / UTC-standardized systems: Ideal when all servers and applications already standardize on one time zone (e.g., UTC) and you need millisecond/microsecond precision for audit logs or event ordering.
- Storage & Index Efficiency: Uses 7–11 bytes instead of 13 bytes, saving disk and index space on large tables.
- Timezone-agnostic wall-clock times: Best for local schedules or events that should not shift across time zones.
- Description: Extends
-
TIMESTAMP WITH TIME ZONE- Description: Extends
TIMESTAMPby also storing the explicit time zone offset (e.g.,+08:00) or region name (e.g.,Asia/Hong_Kong; 13 bytes). (Oracle also offersTIMESTAMP WITH LOCAL TIME ZONE, which normalizes values to the database time zone on storage and converts them to the session time zone on retrieval). - Create / Current Value:
SYSTIMESTAMP(database server timestamp + time zone) orCURRENT_TIMESTAMP(session timestamp + time zone). - Convert:
TO_TIMESTAMP_TZ(string, format)parses a string withTZH:TZMorTZRinto aTIMESTAMP WITH TIME ZONEobject;TO_CHAR(timestamp_tz, format)formats it to a string. - Manipulate: Supports
INTERVALarithmetic,EXTRACT(TIMEZONE_HOUR FROM ...), andAT TIME ZONE '<tz>'(e.g.,systimestamp AT TIME ZONE 'UTC') to convert between time zones. - When & Why to Use:
- Global / Multi-region applications: Essential when transactions originate from different time zones and you need to preserve both the exact point in time and the originating local time zone offset for auditing, compliance, or user-local display.
- Description: Extends
How to Check the Data Type of a Field or Expression
-
Check table column data types (via Data Dictionary):
1 2 3 4SELECT column_name, data_type, data_length, data_scale FROM all_tab_columns WHERE table_name = 'YOUR_TABLE_NAME' AND owner = 'YOUR_SCHEMA'; -- or query user_tab_columns for current schema(In SQL*Plus, SQLcl, or SQL Developer, you can also run
DESC your_table_name;) -
Check the internal data type of any expression or column value (via
DUMP):1 2 3 4 5 6SELECT DUMP(sysdate) AS date_dump, -- Typ=13 (internal expression) or Typ=12 (stored DATE column) DUMP(localtimestamp) AS ts_dump, -- Typ=180 (TIMESTAMP) DUMP(systimestamp) AS tstz_dump, -- Typ=181 (TIMESTAMP WITH TIME ZONE) DUMP(TO_CHAR(sysdate, 'YYYY-MM-DD')) AS str_dump -- Typ=1 (VARCHAR2) FROM DUAL;Common Oracle internal type codes (
Typ=):Typ=1:VARCHAR2/NVARCHAR2Typ=12: StoredDATEcolumn (7 bytes)Typ=13: Internal / RuntimeDATEevaluation (8 bytes, e.g.,SYSDATE,TO_DATE(...),TRUNC(...))Typ=180:TIMESTAMPTyp=181:TIMESTAMP WITH TIME ZONETyp=231:TIMESTAMP WITH LOCAL TIME ZONE
Stored
DATE(Typ=12) vs. Internal / RuntimeDATE(Typ=13) (Implementation Observation):
From a SQL perspective, both represent the exact sameDATEdata type and behave identically. As observed viaDUMP()output:- Runtime / In-Memory (
Typ=13, 8 bytes): Returned when Oracle evaluates built-in date functions or arithmetic in memory (SYSDATE,TO_DATE(...),TRUNC(...),date_col + 1). - Stored on Disk (
Typ=12, 7 bytes): Used when aDATEvalue is persisted in a table column ([Century+100, Year+100, Month, Day, Hour+1, Min+1, Sec+1]). - Oracle handles the representation automatically when reading from or writing to a table, so the distinction only appears when inspecting raw values with
DUMP().
Common Date/Time Format Models (Placeholders)
| Element | Description | Example |
|---|---|---|
YYYY |
4-digit year | 2026 |
MM |
Month (01–12) | 03 |
MON |
Abbreviated month name | MAR |
DD |
Day of month (01–31) | 07 |
DY |
Abbreviated day of week | SAT |
HH24 |
Hour of day (00–23) | 19 |
HH / HH12 |
Hour of day (01–12) | 07 |
MI |
Minute (00–59) — note: do not use MM for minutes |
40 |
SS |
Second (00–59) | 00 |
FF / FF3 |
Fractional seconds (e.g., FF3 for milliseconds, FF6 for microseconds) |
123 |
AM / PM |
Meridian indicator | PM |
TZH |
Time zone hour offset | +08 |
TZM |
Time zone minute offset | 00 |
TZR |
Time zone region name | Asia/Hong_Kong |
"text" |
Quoted literal text inside format mask | "T" |
References:
DECODE (Switch-Case Expression)
The DECODE function in Oracle SQL works like a switch (or if-else-if) statement in programming languages (and is equivalent to a simple CASE expression in SQL). It evaluates an expression against a list of search values one by one and returns the corresponding result for the first match, or a default value if no match is found.
How it maps to a switch statement:
|
|
Syntax:
DECODE(expr, search1, result1, [search2, result2, ...], [default])
expr: The value to compare (theswitchexpression).searchN: The value to match againstexpr(eachcasebranch).resultN: The value returned ifexpr = searchN.default: (Optional) Value returned if no match is found (thedefaultbranch; returnsNULLif omitted).
Example:
Suppose you have a table employees with a column grade:
| grade | name |
|---|---|
| 1 | Alice |
| 2 | Bob |
| 3 | Carol |
You can use DECODE to map grades to descriptions:
|
|
This returns ‘Junior’ for grade 1, ‘Mid’ for grade 2, ‘Senior’ for grade 3, and ‘Unknown’ for any other value.
Note: For more complex conditions, consider using the CASE expression, which is more flexible and ANSI SQL compliant.
Oracle Monitor and Manipulation
Show active sessions
Below query shows current sessions in the database:
|
|
Show locked objects
Below script helps to show the current locked objects in the database along with session and client details:
|
|
Show currently running SQL statements
Below query helps to show the currently running SQL statements along with session and client details (you can also join against v$sqlarea or v$sqlstats instead of v$sql to avoid duplicate rows across multiple child cursors):
|
|
Kill locked session
In case your session is locked due to a lost connection, you can use the following command to kill the session:
|
|
Quick & Dirty Script
Sort string-based ID column numerically
When a column stores alphanumeric IDs with a prefix (e.g., D1, D2, …, D10, D11, D12), a standard ORDER BY sorts them lexicographically (D1, D10, D11, D2). You can strip the prefix with SUBSTR and convert the remaining digits to a number for numeric sorting:
|
|
Escape Special Characters in SQL Statements
In Oracle SQL and client tools (such as SQL*Plus, SQLcl, and SQL Developer), several characters have special meanings (string delimiters, substitution variables, or pattern-matching wildcards) and require specific escaping techniques.
1. Escape & (Ampersand — Client Substitution Variable)
In SQL*Plus, SQLcl, and SQL Developer, & is treated as a substitution variable prompt by default, which causes INSERT or UPDATE statements containing & (e.g., 'R&D' or URL query parameters) to prompt for input or fail:
- Disable substitution variables in the session (Recommended for scripts):
1 2SET DEFINE OFF; INSERT INTO departments (name) VALUES ('R&D'); - Use
CHR(38)concatenation (Works in any client without session settings):1INSERT INTO departments (name) VALUES ('R' || CHR(38) || 'D'); - Set a client escape character in the session:
1 2SET ESCAPE '\'; INSERT INTO departments (name) VALUES ('R\&D');
2. Escape ' (Single Quote — String Literal Delimiter)
- Double the single quote (
''):1SELECT 'It''s Xeth''s blog' AS text FROM DUAL; - Use the
q'[...]'Alternative Quoting Mechanism (Recommended for strings with many quotes): You can choose[],{},<>,(), or any single character (such as!,#,~) as the quote delimiter:1 2SELECT q'[It's Xeth's 'Oracle' note]' AS text FROM DUAL; SELECT q'{It's Xeth's 'Oracle' note}' AS text FROM DUAL;
3. Escape % and _ (Wildcards in LIKE Queries)
In LIKE conditions, % matches any sequence of characters and _ matches any single character. Declare an ESCAPE character explicitly in the query to match them literally:
|
|
4. Escape Reserved Identifiers with " (Double Quotes)
If a table or column name contains spaces, special characters, is case-sensitive, or matches an Oracle reserved word (e.g., USER, DATE, COMMENT), wrap the identifier in double quotes:
|
|
Common Special Characters & CHR() Reference
| Character | Name / Meaning in Oracle | CHR(n) |
How to Escape / Insert Literally |
|---|---|---|---|
' |
String literal delimiter | CHR(39) |
Double it ('') or use q'[...]' |
& |
Client substitution variable (SQL*Plus / SQL Developer) |
CHR(38) |
SET DEFINE OFF;, 'a' || CHR(38) || 'b', or SET ESCAPE '\' |
% |
Multi-character wildcard in LIKE |
CHR(37) |
LIKE '%\%%' ESCAPE '\' |
_ |
Single-character wildcard in LIKE |
CHR(95) |
LIKE '%\_%' ESCAPE '\' |
" |
Quoted identifier delimiter | CHR(34) |
Allowed directly inside '...' string literals |
\n (LF) |
Line feed / Newline | CHR(10) |
'Line 1' || CHR(10) || 'Line 2' |
\r (CR) |
Carriage return | CHR(13) |
'Line 1' || CHR(13) || CHR(10) || 'Line 2' |
\t (Tab) |
Horizontal tab | CHR(9) |
'Col1' || CHR(9) || 'Col2' |
| Unicode | Unicode code point (\xxxx) |
UNISTR() |
UNISTR('Price: \20AC100') (e.g., €) |
References: