Oracle Specific

String Manipulation Functions

REPLACE

Description

The REPLACE function in Oracle is used to replace occurrences of a specified substring within a string with another substring. It is a string manipulation function that can be used to modify parts of a string based on specific criteria. It is case-sensitive.

Syntax

REPLACE(string, search_string, replacement_string)

Parameters

  • string: The original string in which the search and replace operation will be performed.

  • search_string: The substring that we want to find within the original string.

  • replacement_string: The substring that will replace every occurrence of the search_string. If replacement_string is omitted, all occurrences of search_string are removed.

Return Value

The function returns a new string where all occurrences of search_string are replaced with replacement_string.

Examples

SELECT REPLACE('Hello World', 'World', 'Oracle') AS replaced_string
FROM DUAL;
-- Output -> Hello Oracle

SELECT REPLACE('Hello World', 'World') AS replaced_string
FROM DUAL;
-- Output -> Hello

SELECT REPLACE('banana', 'a', 'o') AS replaced_string
FROM DUAL;
-- Output -> bonono

SELECT FIRST_NAME, REPLACE(FIRST_NAME, 'a', 'o') AS new_name
FROM employees;

TRANSLATE

Description

The TRANSLATE function in Oracle is used to replace characters in a string with other characters based on a given mapping. Unlike REPLACE, which operates on substrings, TRANSLATE operates on individual characters and can simultaneously replace multiple characters with different characters.

Parameters

  • string: The original string in which the replacement will take place.

  • from_string: A string containing characters to be replaced.

  • to_string: A string containing characters that will replace the characters in from_string.

Return Value

The function returns a new string where each character in the from_string is replaced with the corresponding character in the to_string.

  • The from_string and to_string should have the same length. If to_string is shorter, extra characters in from_string are removed from the string.

  • Each character in from_string is mapped to the character in the same position in to_string.

  • If any character in from_string does not have a corresponding character in to_string, that character is removed from the string.

  • Character-by-Character Replacement i.e. each character in from_string is replaced by the character at the same position in to_string.

  • Works for character-by-character translation and requires non-empty mapping strings.

Examples

How TRANSLATE differs from REPLACE?

Feature
REPLACE
TRANSLATE

Purpose

Replace occurrences of a substring

Replace occurrences of individual characters

Syntax

REPLACE(string, search_string, replacement_string)

TRANSLATE(string, from_string, to_string)

Operation

Works on substrings

Works on individual characters

Case Sensitivity

Case-sensitive

Case-sensitive

Character Mapping

One-to-one mapping for the entire substring

One-to-one character mapping

Use Case Example

Replace all occurrences of "cat" with "dog"

Replace all occurrences of 'a' with 'b', 'e' with 'i'

When search_string or from_string is not found

No change

No change

Handling of NULLs

If any argument is NULL, returns NULL

If any argument is NULL, returns NULL

Performance

Generally used for fewer, more complex replacements

Generally faster for character replacements

Removing Characters

Cannot directly remove a substring without replacing

Can remove characters by providing an empty to_string. If we want to remove multiple characters using TRANSLATE, we need to ensure that the to_string parameter is not empty but contains a character that will be mapped to the characters in the from_string

Example 1

REPLACE('Hello World', 'World', 'Oracle') returns Hello Oracle

TRANSLATE('Hello', 'Hlo', 'Bri') returns Berro

Example 2

REPLACE('banana', 'a', 'o') returns bonono

TRANSLATE('banana', 'an', 'om') returns bomomo

Use in Columns

SELECT REPLACE(column_name, 'old', 'new') FROM table

SELECT TRANSLATE(column_name, 'from_chars', 'to_chars') FROM table

LENGTH

Description

The LENGTH function in Oracle is used to return the number of characters in a string.

Syntax

Parameters

  • string: The string expression whose length you want to determine. This can be a column name, a literal string, or any expression that evaluates to a string.

Return Value

The function returns an integer representing the number of characters in the specified string. If the string is NULL, the function returns NULL.

Examples

TRIM

Description

The TRIM function in Oracle is used to remove leading and trailing spaces or other specified characters from a string. It is particularly useful for cleaning up data by removing unnecessary whitespace or specific unwanted characters from the beginning and end of strings.

Syntax

Parameters

  • LEADING | TRAILING | BOTH: Specifies which side(s) of the string to trim. The default is BOTH.

    • LEADING: Trims characters from the beginning of the string.

    • TRAILING: Trims characters from the end of the string.

    • BOTH: Trims characters from both the beginning and the end of the string.

  • trim_character: The character to be trimmed from the string. If not specified, spaces are trimmed by default.

  • string: The string expression from which the characters are to be trimmed.

Return Value

The function returns a new string with the specified characters removed from the specified side(s).

Examples

LOWER

Description

The LOWER function converts all characters in a string to lowercase.

Syntax

Parameters

  • string: The input string to be converted to lowercase.

Return Value

The function returns a new string with all characters converted to lowercase.

Examples

UPPER

Description

The UPPER function converts all characters in a string to uppercase.

Syntax

Parameters

  • string: The input string to be converted to uppercase.

Return Value

The function returns a new string with all characters converted to uppercase.

Examples

RPAD

Description

The RPAD function pads the right side of a string with a specified character to a specified length.

Syntax

Parameters

  • string: The input string to be padded.

  • length: The total length of the resulting string after padding.

  • pad_string (optional): The string to pad with. If not specified, spaces are used.

Return Value

The function returns a new string of the specified length, padded with the specified character (or spaces) on the right side.

Examples

LPAD

Description

The LPAD function pads the left side of a string with a specified character to a specified length.

Syntax

Parameters

  • string: The input string to be padded.

  • length: The total length of the resulting string after padding.

  • pad_string (optional): The string to pad with. If not specified, spaces are used.

Return Value

The function returns a new string of the specified length, padded with the specified character (or spaces) on the left side.

Examples

SUBSTR

Description

The SUBSTR function in Oracle extracts a substring from a string, starting from a specified position and optionally for a specified length.

Syntax

Parameters

  • string: The input string from which the substring will be extracted.

  • start_position: The position at which the extraction starts. This is a 1-based index.

    • If start_position is positive, it starts from the beginning of the string.

    • If start_position is negative, it starts from the end of the string and counts backwards.

  • length (optional): The number of characters to extract. If omitted, the function returns the substring from start_position to the end of the string.

Positive Start Position: Starts extracting from the beginning of the string.

Negative Start Position: Starts extracting from the end of the string.

Length: If not specified, extraction goes to the end of the string.

Return Value: Returns NULL if start_position is beyond the string length or if length is less than or equal to 0

Return Value

The function returns a substring of the specified length starting from the specified position. If start_position is beyond the length of the string, the function returns NULL. If length is less than or equal to 0, the function returns NULL.

Examples

INSTR

Description

The INSTR function in Oracle is used to search for a substring within a string and return the position at which the substring is found. If the substring is not found, it returns 0. This function is useful for string manipulation and searching within text data.

Syntax

Parameters

  • string: The string to be searched.

  • substring: The substring to search for.

  • start_position (optional): The position in the string to start the search. The default is 1.

  • nth_appearance (optional): Specifies which occurrence of the substring to search for. The default is 1.

Return Value

The function returns the position of the first character of the nth occurrence of the substring in the string. If the substring is not found, it returns 0.

Examples

REGEXP_LIKE

Description

The REGEXP_LIKE function in Oracle is used to perform regular expression matching. It is a powerful function for pattern matching and is particularly useful for complex search conditions. It allows to search for a string that matches a regular expression pattern.

Syntax

Parameters

  • source_string: The string to be searched.

  • pattern: The regular expression pattern to search for.

  • match_parameter (optional): A string that can include one or more of the following modifiers:

    • 'i': Case-insensitive matching.

    • 'c': Case-sensitive matching (default).

    • 'n': The period . does not match the newline character.

    • 'm': The string is treated as multiple lines. The ^ and $ match the start and end of any line within the source string.

Common regular expression symbols

Symbol
Description

^

Matches the start of a string.

$

Matches the end of a string.

.

Matches any single character except newline.

[]

Matches any single character within the brackets.

[^]

Matches any single character not within the brackets.

*

Matches 0 or more occurrences of the preceding element.

+

Matches 1 or more occurrences of the preceding element.

?

Matches 0 or 1 occurrence of the preceding element.

{n}

Matches exactly n occurrences of the preceding element.

{n,}

Matches n or more occurrences of the preceding element.

{n,m}

Matches at least n and at most m occurrences of the preceding element.

\d

Matches any digit (equivalent to [0-9]).

\D

Matches any non-digit.

\w

Matches any word character (alphanumeric plus underscore).

\W

Matches any non-word character.

\s

Matches any whitespace character (space, tab, newline).

\S

Matches any non-whitespace character.

\b

Matches a word boundary.

\B

Matches a non-word boundary.

()

Groups expressions and captures the matched text.

(?:...)

Groups expressions without capturing the matched text.

(?=...)

Positive lookahead; matches if the expression within the parentheses can be matched.

(?!...)

Negative lookahead; matches if the expression within the parentheses cannot be matched.

(?<=...)

Positive lookbehind; matches if the preceding text matches the expression within the parentheses.

(?<!...)

Negative lookbehind; matches if the preceding text does not match the expression within the parentheses.

\

Escapes a special character to match it literally.

Examples

REGEXP_REPLACE

The REGEXP_REPLACE function in Oracle is used to search a string for a regular expression pattern and replace it with another string. It is useful for advanced string manipulation where patterns and replacements can be specified with regular expressions.

Syntax

Parameters

  • source_string: The string to search within.

  • pattern: The regular expression pattern to search for.

  • replace_string: The string to replace the matched pattern with.

  • position (optional): The position in the source string to start the search. The default is 1.

  • occurrence (optional): The occurrence of the pattern to be replaced. The default is 0, meaning all occurrences.

  • match_parameter (optional): A string that can include one or more of the following modifiers:

    • 'i': Case-insensitive matching.

    • 'c': Case-sensitive matching (default).

    • 'n': The period . does not match the newline character.

    • 'm': The string is treated as multiple lines. The ^ and $ match the start and end of any line within the source string.

Examples

Datatype Conversion

CAST

Description

The CAST function in Oracle is used to convert one data type to another. It is a versatile function that allows to change the data type of an expression to a different data type, which is particularly useful when dealing with different types of data in queries.

Syntax

Parameters

  • expression: The value or column that you want to convert.

  • target_data_type: The data type to which you want to convert the expression.

Supported Data Types

The CAST function supports conversion to and from a wide range of data types like

  • VARCHAR2, CHAR

  • NUMBER, INTEGER, FLOAT

  • DATE, TIMESTAMP

  • BLOB, CLOB

Examples

NULL Handling: If the expression is NULL, the CAST function returns NULL of the target data type.

Hierarchical Function

SYS_CONNECT_BY_PATH

Description

The SYS_CONNECT_BY_PATH function in Oracle is used in hierarchical queries to return the path of a column value from the root to the current row in a tree-structured format. It is particularly useful for displaying hierarchical relationships in a readable format.

Syntax

Parameters

  • column: The column for which the path is to be constructed.

  • delimiter: The character or string that separates the levels in the hierarchy.

Return Value

The function returns a string that represents the path from the root node to the current node, with each level separated by the specified delimiter.

Usage Context

The SYS_CONNECT_BY_PATH function is used in the context of hierarchical queries, which are queries that use the CONNECT BY clause to define parent-child relationships within the data.

If the column used in SYS_CONNECT_BY_PATH is NULL, it includes the NULL values in the path.

Examples

  1. Employee Manager Hierarchy

We have an employees table with columns EMPLOYEE_ID, MANAGER_ID, and FIRST_NAME. We need to display the hierarchical path of employee names with the help of SYS_CONNECT_BY_PATH

Sample Output

  1. Create sequence or generate data

Sample Output

Null Handling Functions

NVL

Description

The NVL function in Oracle is used to replace NULL values with a specified value. This function is particularly useful when dealing with potential NULL values in your data and you want to ensure that your results are complete and meaningful.

Syntax

Parameters

  • expression1: The expression to be checked for NULL.

  • expression2: The value to be returned if expression1 is NULL.

Return Value

The function returns expression2 if expression1 is NULL. If expression1 is not NULL, it returns expression1.

Examples

COALESCE

Description

The COALESCE function in Oracle is used to return the first non-null expression among its arguments. It's a more versatile and flexible alternative to the NVL function, as it can handle multiple expressions and return the first one that is not NULL.

Syntax

Parameters

  • expr1, expr2, ..., exprn: The expressions to be evaluated in the order they are provided. The function returns the first non-null expression.

COALESCE stops evaluating expressions once it finds the first non-null expression, potentially improving performance.

Return Value

The function returns the first non-null expression among its arguments. If all arguments are NULL, it returns NULL.

Examples

Arithmetic Functions

AVG

The AVG function calculates the average value of a numeric column.

Syntax

MIN

The MIN function returns the smallest value in a set.

Syntax

MAX

The MAX function returns the largest value in a set.

Syntax

COUNT

The COUNT function returns the number of rows that match a specified condition.

Syntax

SUM

The SUM function returns the total sum of a numeric column.

Syntax

When we do COUNT(*), counting is rows (regardless of actual value, which is why rows containing NULL and non-NULL values are counted). But when we do COUNT a column, we are counting the number of non-NULL values in that column.

EXP

The EXP function returns e raised to the power of a given number. The constant e is approximately equal to 2.71828.

Syntax

LN

The LN function returns the natural logarithm (base e) of a given number.

Syntax

LOG

The LOG function returns the logarithm of a given number with a specified base.

Syntax

POWER

The POWER function returns a number raised to the power of another number.

Syntax

SQRT

The SQRT function returns the square root of a given number.

Syntax

ROUND

The ROUND function returns a number rounded to a specified number of decimal places.

Syntax

Example

Round 123.4567 to two decimal places:

TRUNC

The TRUNC function truncates a number to a specified number of decimal places, effectively removing the fractional part beyond the specified decimal places.

Syntax

Example

Truncate 123.4567 to two decimal places:

MOD

The MOD function returns the remainder of a division operation.

Syntax

Example

Calculate the remainder of 10 divided by 3:

CEIL

The CEIL function returns the smallest integer greater than or equal to a given number.

Syntax

Example

Calculate the ceiling of 123.456:

FLOOR

The FLOOR function returns the largest integer less than or equal to a given number.

Syntax

Example

Calculate the floor of 123.456:

ABS

The ABS function returns the absolute value of a number.

Syntax

Example

Calculate the absolute value of -123.456:

MEDIAN

The MEDIAN function computes the median of a set of values. The median is the value separating the higher half from the lower half of a data sample.

Syntax

Example

Assume we have a table employees with a salary column. To calculate the median salary for the entire table:

PERCENTILE_CONT

The PERCENTILE_CONT function is an inverse distribution function that returns the value corresponding to the specified percentile in a group of values.

Syntax

  • percentile: A numeric value between 0 and 1. For example, 0.5 represents the 50th percentile (median).

  • value_expression: The column or expression on which the percentile calculation is performed.

Example

Calculate the median (50th percentile) salary for the entire table:

Calculate the 90th percentile salary for each department:

Window functions

Window functions in SQL, also known as analytic functions, allows to perform calculations across a set of table rows that are somehow related to the current row. This is similar to aggregate functions but unlike aggregate functions, window functions do not cause rows to become grouped into a single output row—the rows retain their separate identities.

LAG

The LAG function provides access to a row at a given physical offset prior to the current row within the partition.

Syntax

  • value_expression: The column or expression to evaluate.

  • offset: The number of rows back from the current row from which to obtain the value (default is 1).

  • default: The value to return if the offset goes out of the bounds of the partition.

Example

LEAD

The LEAD function provides access to a row at a given physical offset following the current row within the partition.

Syntax

  • value_expression: The column or expression to evaluate.

  • offset: The number of rows back from the current row from which to obtain the value (default is 1).

  • default: The value to return if the offset goes out of the bounds of the partition.

Example

ROW_NUMBER

The ROW_NUMBER function assigns a unique number to each row to which it is applied, starting from 1.

Syntax

Example

RANK

The RANK function provides the rank of a row within the partition of a result set. The rank of a row is one plus the number of ranks that come before it.

Syntax

Example

DENSE_RANK

The DENSE_RANK function is similar to RANK, but it does not skip rank values if there are ties.

Syntax

Example

NTILE

The NTILE function distributes the rows in an ordered partition into a specified number of groups, and assigns a number to each row indicating the group to which it belongs.

Syntax

Example

Date Functions

ADD_MONTHS

The ADD_MONTHS function adds a specified number of months to a date.

Syntax

  • date: The starting date.

  • number_of_months: The number of months to add (can be positive or negative).

Example

TO_CHAR (with Date Formatting)

The TO_CHAR function converts a date or number to a string using a specified format.

Syntax

  • date: The date value to be converted.

  • format_model: The format in which the date should be returned. Common format models include:

    • 'YYYY': Four-digit year.

    • 'MM': Two-digit month.

    • 'DD': Two-digit day.

    • 'DY': Three-character day of the week (e.g., MON, TUE).

    • 'HH24': Hour of the day in 24-hour format.

    • 'MI': Minutes.

    • 'SS': Seconds.

Example

TO_DATE

The TO_DATE function converts a string to a date using a specified format.

Syntax

  • string: The string to be converted to a date.

  • format_model: The format in which the string is provided. The format model should match the string format.

Example

MONTHS_BETWEEN

The MONTHS_BETWEEN function returns the number of months between two dates. The result can include a fractional part if the dates are not exactly a whole number of months apart.

Syntax

  • date1: The later date.

  • date2: The earlier date.

Example

TRUNC

The TRUNC function truncates a date to the specified unit of measure. This function is often used to remove the time portion of a date or to truncate the date to a specific level (e.g., year, month).

Syntax

  • date: The date to be truncated.

  • format: The unit of measure to truncate the date to (optional). Common format models include:

    • 'YYYY': Truncate to the first day of the year.

    • 'MM': Truncate to the first day of the month.

    • 'DD': Truncate to midnight of the current day (default if format is not specified).

Example

LAST_DAY

The LAST_DAY function returns the last day of the month that contains the specified date.

Syntax

  • date: The date from which to determine the last day of the month.

Example

NEXT_DAY

The NEXT_DAY function returns the date of the first specified weekday that is later than the given date.

Syntax

  • date: The starting date.

  • day_of_week: The name of the weekday (in English). It can be abbreviated (e.g., 'MON' for Monday).

Example

EXTRACT

The EXTRACT function extracts a specific part of a date (such as year, month, day, hour, minute, second) or an interval.

Syntax

  • part: The part of the date to extract. Common parts include YEAR, MONTH, DAY, HOUR, MINUTE, SECOND.

  • date: The date from which to extract the part.

Example

Conditional Functions

DECODE

The DECODE function provides functionality similar to a CASE statement. It allows to perform conditional querying and can transform data within a query based on specific conditions.

Syntax

  • expression: The value to be evaluated.

  • search1, search2, ...: The values to compare against the expression.

  • result1, result2, ...: The results to return if the corresponding search value matches the expression.

  • default: The default result to return if no match is found (optional).

Example

Suppose we have an employees table with an employee_id and a department_id, and want to translate department IDs into department names.

CASE

The CASE statement in Oracle SQL is a versatile conditional expression that allows to implement conditional logic directly in your SQL queries. It is similar to the DECODE function but more powerful and flexible because it can handle complex conditions and multiple data types.

Syntax

There are two types of CASE statements: the simple CASE statement and the searched CASE statement.

Simple CASE Statement

The simple CASE statement compares an expression to a set of simple expressions to determine the result.

Searched CASE Statement

The searched CASE statement evaluates a set of Boolean expressions to determine the result.

Examples

Example 1: Simple CASE Statement

Suppose we have an employees table with columns employee_id, first_name, last_name, and department_id, and want to translate department IDs into department names.

Example 2: Searched CASE Statement

Suppose we want to classify employees based on their salary ranges.

Example 3: Combining CASE with Other SQL Features

You can combine the CASE statement with other SQL clauses such as ORDER BY and FETCH FIRST.

Advanced Aggregation Function

GROUPING Function

The GROUPING function is used to distinguish between a detail row and an aggregate row created by a ROLLUP or CUBE operation. It returns 1 for a row created by ROLLUP or CUBE and 0 for a regular row.

Syntax

Example 1

  • is_product_total is 1 when the row is a product subtotal.

  • is_region_total is 1 when the row is a region subtotal.

  • Both are 1 when the row is the grand total.

Example 2

ROLLUP Function

The ROLLUP function is an extension to the GROUP BY clause that creates subtotals and a grand total. It allows you to create aggregate values at multiple levels of a hierarchy.

Syntax

ROLLUP vs CUBE

Feature
CUBE
ROLLUP

Purpose

Generates subtotals for all possible combinations of a set of dimensions.

Generates subtotals and grand totals for a hierarchical set of dimensions.

Hierarchical Levels

Covers all combinations of the specified columns, resulting in a full cross-tabulation of subtotals.

Covers a hierarchy of the specified columns, resulting in subtotal rows at each level of the hierarchy and a grand total.

Number of Groupings

2^n (where n is the number of columns). For example, for 3 columns, it generates 8 groupings.

n+1 (where n is the number of columns). For example, for 3 columns, it generates 4 groupings.

Subtotals

Includes subtotals for all possible combinations, including combinations of 1, 2, up to n-1 columns.

Includes subtotals for each column and progressively fewer columns until only the grand total is left.

Grand Total

Included as one of the combinations where all specified columns are set to NULL.

Included as the final grouping where all specified columns are set to NULL.

Use Case

Useful for comprehensive data analysis with all possible dimension combinations.

Useful for hierarchical data analysis where subtotals are needed at each level of the hierarchy.

Example Syntax

GROUP BY CUBE (col1, col2, col3)

GROUP BY ROLLUP (col1, col2, col3)

Example 1

  • Rows where region_id is NULL are subtotals for each product_id.

  • The row where both product_id and region_id are NULL is the grand total.

Example 2

CUBE

The CUBE function in Oracle SQL is an extension of the GROUP BY clause that generates subtotals for all possible combinations of a given set of dimensions. It is useful for producing a cross-tabulation of data and can create a comprehensive result set that includes subtotals and a grand total for multi-dimensional data analysis.

Syntax

Example 1

  • Rows where region_id is NULL are subtotals for each product_id.

  • Rows where product_id is NULL are subtotals for each region_id.

  • The row where both product_id and region_id are NULL is the grand total.

Example 2

Last updated