Is production: true

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

1
2
3
4
5
6
7
8
-- Tables owned by the current user/schema
SELECT table_name FROM user_tables;

-- All tables accessible to the current user
SELECT owner, table_name FROM all_tables;

-- All tables in the database (requires DBA privileges)
SELECT owner, table_name FROM dba_tables;

Date Time manipulating

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
SELECT
    sysdate cur_date,                       -- current date & time (DATE type)
    localtimestamp cur_local_ts,            -- current timestamp without tz (TIMESTAMP type)
    systimestamp cur_timestamp,             -- current timestamp with fractional seconds & tz
    trunc(sysdate) today_midnight,          -- current date (time truncated to 00:00:00, still DATE type)
    trunc(sysdate-2) two_days_ago,          -- two days ago
    sysdate - INTERVAL '30' MINUTE mins_ago,-- 30 minutes ago
    sysdate + INTERVAL '2' HOUR hrs_later,  -- 2 hours later
    ADD_MONTHS(trunc(sysdate), -1) prev_mon,-- one month ago
    LAST_DAY(sysdate) end_of_month,         -- last day of current month
    EXTRACT(YEAR FROM systimestamp) cur_yr, -- extract year (or TO_NUMBER(TO_CHAR(sysdate, 'YYYY')))
    -- format date to string
    TO_CHAR(sysdate, 'YYYY-MM-DD HH24:MI:SS') formatted_date_str,
    -- datetime with tz
    TO_TIMESTAMP_TZ('2026-03-07T19:40:00 +08:00', 'YYYY-MM-DD"T"HH24:MI:SS TZH:TZM') zoned_time,
    -- convert string to timestamp / date with time
    TO_TIMESTAMP('2026-03-07 19:40:00', 'YYYY-MM-DD HH24:MI:SS') converted_timestamp,
    TO_DATE('2026-03-07 19:40:00', 'YYYY-MM-DD HH24:MI:SS') converted_date_with_time,
    -- convert string to date
    TO_DATE('2026-03-07', 'YYYY-MM-DD') converted_date
FROM DUAL;

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(...)).

  1. 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) or CURRENT_DATE (session time zone date/time).
    • Convert: TO_DATE(string, format) parses a string into a DATE object; TO_CHAR(date, format) converts it to a string.
    • Manipulate: Supports TRUNC(date) (resets time to 00:00:00 while remaining a DATE object), numeric day arithmetic (sysdate - 2), INTERVAL arithmetic, ADD_MONTHS, and LAST_DAY. (Note: For DATE values, EXTRACT only supports YEAR, MONTH, and DAY; to extract HOUR, MINUTE, or SECOND, cast to TIMESTAMP or use TO_CHAR).
  2. TIMESTAMP

    • Description: Extends DATE by adding fractional seconds (up to 9 digits of precision, default 6; 7–11 bytes), without storing a time zone.
    • Create / Current Value: LOCALTIMESTAMP returns a plain TIMESTAMP in the current session’s time zone (inserting SYSTIMESTAMP into a TIMESTAMP column also implicitly strips the time zone).
    • Convert: TO_TIMESTAMP(string, format) parses a string (including .FF fractional seconds) into a TIMESTAMP object; TO_CHAR(timestamp, format) formats it to a string.
    • Manipulate: Use INTERVAL arithmetic (e.g., timestamp_col + INTERVAL '30' MINUTE) and EXTRACT(field FROM timestamp) to preserve the TIMESTAMP type and fractional seconds. (Note: TRUNC(timestamp) and numeric addition like timestamp_col + 1 implicitly return a DATE value, 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.
  3. TIMESTAMP WITH TIME ZONE

    • Description: Extends TIMESTAMP by also storing the explicit time zone offset (e.g., +08:00) or region name (e.g., Asia/Hong_Kong; 13 bytes). (Oracle also offers TIMESTAMP 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) or CURRENT_TIMESTAMP (session timestamp + time zone).
    • Convert: TO_TIMESTAMP_TZ(string, format) parses a string with TZH:TZM or TZR into a TIMESTAMP WITH TIME ZONE object; TO_CHAR(timestamp_tz, format) formats it to a string.
    • Manipulate: Supports INTERVAL arithmetic, EXTRACT(TIMEZONE_HOUR FROM ...), and AT 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.

How to Check the Data Type of a Field or Expression

  • Check table column data types (via Data Dictionary):

    1
    2
    3
    4
    
    SELECT 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
    6
    
    SELECT
        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 / NVARCHAR2
    • Typ=12: Stored DATE column (7 bytes)
    • Typ=13: Internal / Runtime DATE evaluation (8 bytes, e.g., SYSDATE, TO_DATE(...), TRUNC(...))
    • Typ=180: TIMESTAMP
    • Typ=181: TIMESTAMP WITH TIME ZONE
    • Typ=231: TIMESTAMP WITH LOCAL TIME ZONE

    Stored DATE (Typ=12) vs. Internal / Runtime DATE (Typ=13) (Implementation Observation):
    From a SQL perspective, both represent the exact same DATE data type and behave identically. As observed via DUMP() 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 a DATE value 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:

1
2
3
4
5
6
switch (expr) {
    case search1: return result1;
    case search2: return result2;
    ...
    default:      return default; // or NULL if omitted
}

Syntax:

DECODE(expr, search1, result1, [search2, result2, ...], [default])
  • expr: The value to compare (the switch expression).
  • searchN: The value to match against expr (each case branch).
  • resultN: The value returned if expr = searchN.
  • default: (Optional) Value returned if no match is found (the default branch; returns NULL if 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:

1
2
3
SELECT name,
       DECODE(grade, 1, 'Junior', 2, 'Mid', 3, 'Senior', 'Unknown') AS grade_desc
FROM employees;

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:

1
select * from v$session;

Show locked objects

Below script helps to show the current locked objects in the database along with session and client details:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
select
   c.owner as object_owner,
   c.object_name,
   c.object_type,
   a.locked_mode,
   decode(a.locked_mode,
      0, 'None',
      1, 'Null (NULL)',
      2, 'Row Share (SS)',
      3, 'Row Exclusive (SX)',
      4, 'Share (S)',
      5, 'Share Row Exclusive (SSX)',
      6, 'Exclusive (X)',
      'Unknown'
   ) as lock_mode_desc,
   b.sid,
   b.serial#,
   b.status,
   b.username       as db_user,
   b.osuser         as client_os_user,
   b.machine        as client_machine,
   b.program        as client_program,
   b.module         as client_module,
   b.action         as client_action,
   b.port           as client_port,
   b.logon_time
from
   v$locked_object a
join
   v$session b
   on b.sid = a.session_id
join
   dba_objects c
   on a.object_id = c.object_id;

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):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
select
    s.sid,
    s.serial#,
    s.username,
    s.osuser,
    s.machine,
    s.program,
    s.status,
    s.last_call_et as running_seconds,
    s.sql_id,
    q.sql_fulltext
from
    v$session s
join
    v$sql q
    on s.sql_id = q.sql_id
   and s.sql_child_number = q.child_number
where
    s.status = 'ACTIVE'
    and s.type != 'BACKGROUND'
    and s.sid != sys_context('USERENV', 'SID');

Kill locked session

In case your session is locked due to a lost connection, you can use the following command to kill the session:

1
alter system kill session '<sid>,<serial#>' immediate;

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:

1
2
3
4
5
SELECT *
FROM xx
ORDER BY TO_NUMBER(SUBSTR(xx.defect_id, 2));
-- or: ORDER BY CAST(SUBSTR(xx.defect_id, 2) AS NUMBER);
-- or: ORDER BY CAST(SUBSTR(xx.defect_id, 2) AS INT);

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
    2
    
    SET DEFINE OFF;
    INSERT INTO departments (name) VALUES ('R&D');
    
  • Use CHR(38) concatenation (Works in any client without session settings):
    1
    
    INSERT INTO departments (name) VALUES ('R' || CHR(38) || 'D');
    
  • Set a client escape character in the session:
    1
    2
    
    SET ESCAPE '\';
    INSERT INTO departments (name) VALUES ('R\&D');
    

2. Escape ' (Single Quote — String Literal Delimiter)

  • Double the single quote (''):
    1
    
    SELECT '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
    2
    
    SELECT 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:

1
2
3
4
5
-- Find values containing literal "100%" or "USER_A"
SELECT *
FROM discounts
WHERE promo_text LIKE '%100\%%' ESCAPE '\'
   OR code_name  LIKE 'USER\_%' ESCAPE '\';

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:

1
SELECT "USER", "Order#ID" FROM "My Table";

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: