Top 100 Oracle SQL Function You Must Know

Top 100 Oracle SQL Function You Must Know

Top 100 Oracle SQL Function You Must Know

Before diving into the top 100 Oracle SQL function, it’s helpful to understand the major categories these functions fall into. Each group serves a specific purpose in data handling, transformation, or querying. Here’s a brief overview:

Let’s break each one down with simple examples and real-world usage.

🔹1. Oracle SQL Function for Handling NULL Values

In Oracle SQL, NULL represents the absence of a value—meaning the data is unknown, missing, or not applicable. Unlike a zero or an empty string, NULL is a special marker used to indicate that no value has been assigned. Because of this, working with NULL values requires special care; simple comparisons (like = NULL) won’t work as expected.

Oracle provides a set of NULL-handling functions that help manage and transform these values for cleaner reporting and accurate logic in SQL queries.

#FunctionPurpose
1NVLReplace NULL with a default value
2NVL2Return one value if NOT NULL, another if NULL
3COALESCEReturn first non-NULL expression
4NULLIFReturn NULL if two expressions are equal
5LNNVLConditional evaluation of NULLs

🔹2. Oracle SQL Function for String

String functions allow you to manipulate text data—such as trimming, concatenating, replacing, or extracting substrings. These are particularly useful in data formatting, cleansing, and transformations in reports or application outputs.

#FunctionPurpose
6SUBSTRExtract substring
7INSTRFind position of substring
8LENGTHLength of string
9TRIMTrim leading/trailing characters
10LTRIMTrim leading characters
11RTRIMTrim trailing characters
12REPLACEReplace characters in string
13TRANSLATEReplace multiple characters at once
14LOWERConvert to lowercase
15UPPERConvert to uppercase
16INITCAPCapitalize first letter of each word
17CONCATConcatenate two strings
18LPADLeft pad a string
19RPADRight pad a string
20CHRReturn character from ASCII code
21ASCIIReturn ASCII code from character
22REGEXP_SUBSTRRegex-based substring search
23REGEXP_REPLACERegex-based search and replace
24REGEXP_INSTRRegex-based position search
25REGEXP_LIKERegex pattern matching

🔹 3. Oracle SQL Function for Number

Numeric functions handle operations involving numbers. These include mathematical calculations, rounding, truncating, or generating random values. They’re essential for financial, statistical, or scientific computations in SQL queries.

#FunctionPurpose
26ROUNDRound number to decimals
27TRUNCTruncate decimals
28MODGet remainder
29ABSAbsolute value
30CEILRound up
31FLOORRound down
32SIGNReturns sign of number
33POWERExponentiation
34SQRTSquare root
35EXPExponential value
36LOGNatural log
37LNLog base e
38GREATESTMax of multiple expressions
39LEASTMin of multiple expressions

🔹 4. Oracle SQL Function for Date & Time

Date functions help you process and format date and time values. You can add or subtract days, extract specific parts (like year or month), or compare and format date values in user-friendly ways.

#FunctionPurpose
40SYSDATECurrent date/time
41CURRENT_DATECurrent user session date
42SYSTIMESTAMPCurrent timestamp
43LOCALTIMESTAMPTimestamp without time zone
44ADD_MONTHSAdd/subtract months
45MONTHS_BETWEENMonths between dates
46NEXT_DAYNext specified weekday
47LAST_DAYLast day of the month
48TRUNC(date)Truncate date
49ROUND(date)Round date to nearest unit
50EXTRACTExtract date parts (year, month, etc.)

🔹 5. Oracle SQL Function for Conversion

Conversion functions convert one data type into another—like converting strings to numbers, dates to text, or binary to hex. These are crucial when dealing with mismatched data formats or when preparing data for display.

#FunctionPurpose
51TO_CHARConvert to string
52TO_DATEConvert to date
53TO_NUMBERConvert to number
54CASTGeneral type conversion
55CONVERTCharacter set conversion
56DUMPInternal representation of value
57BIN_TO_NUMBinary to number
58NUMTODSINTERVALNumber to INTERVAL DAY TO SECOND
59NUMTOYMINTERVALNumber to INTERVAL YEAR TO MONTH

🔹 6. Conditional Logic

Conditional functions evaluate conditions and return values based on logic. Functions like NVL, COALESCE, and DECODE simplify decision-making within SQL queries, often replacing complex CASE statements.

#FunctionPurpose
60DECODEConditional match
61CASEComplex condition handling
62NVL2Return value based on NULL check (again)
63NULLIFReturn NULL if values match (again)

🔹 7. Aggregate Functions

Aggregate functions perform calculations on sets of rows and return a single value. They are frequently used in GROUP BY queries to summarize data. Examples include SUM, AVG, COUNT, MIN, and MAX. These are core components in analytical reports and dashboards.

#FunctionPurpose
64SUMTotal of column values
65AVGAverage
66MAXMaximum
67MINMinimum
68COUNTCount rows
69STDDEVStandard deviation
70VARIANCEStatistical variance
71GROUPINGCheck if column is aggregated
72CUBEMultidimensional aggregations
73ROLLUPHierarchical aggregations

🔹 8. Analytic (Window) Functions

Analytical functions operate on a set of rows related to the current row and are used in advanced reporting. They don’t reduce the number of rows like aggregate functions. Examples include RANK, DENSE_RANK, ROW_NUMBER, and LEAD/LAG. These are vital for cumulative totals, moving averages, and comparative reports.

#FunctionPurpose
74RANK()Rank of row
75DENSE_RANK()Dense rank
76ROW_NUMBER()Row number
77NTILE(n)Divide rows into buckets
78LAG()Value of previous row
79LEAD()Value of next row
80FIRST_VALUE()First value in window
81LAST_VALUE()Last value in window
82NTH_VALUE()N-th value in window
83PERCENT_RANK()Percentile rank
84CUME_DIST()Cumulative distribution

🔹 9. Miscellaneous Functions

These functions return information about the session or the system, such as USER, SYSDATE, UID, and USERENV. They help identify runtime conditions, such as the logged-in user or current system date, which is useful for auditing and personalization.

#FunctionPurpose
85UIDReturn user ID
86USERReturn current user
87USERENVSession info (language, schema)
88VSIZESize in bytes
89SYS_CONTEXTSecure app context values
90ORA_HASHHash function
91SYS_GUID()Generate unique identifier
92EMPTY_BLOB()Initialize empty LOB
93EMPTY_CLOB()Initialize empty LOB

🔹 10. Advanced / Newer Functions

#FunctionPurpose
94LISTAGGAggregate rows into string
95JSON_OBJECTCreate JSON object
96JSON_VALUEExtract value from JSON
97JSON_TABLEQuery JSON as rows
98XMLAGGAggregate XML fragments
99PIVOTConvert rows to columns
100UNPIVOTConvert columns to rows

General Overview of Oracle SQL Functions

Replaces a NULL value with a specified default. It ensures that queries do not return NULL when a default is more meaningful, especially in aggregations or reports.

Financial reporting (show 0 when commission is NULL), avoiding NULL in calculations or joins.

NVL(expr1, expr2)
  • expr1: The value to evaluate.
  • expr2: The substitute if expr1 is NULL.
SQL
SELECT employee_name, NVL(commission, 0) AS actual_commission
  FROM employees;
SQL

Shows 0 in the commission column where it is NULL.

Returns one value if the first expression is NOT NULL and another if it IS NULL. It’s a more flexible version of NVL.

Status flags like ‘Has Commission’ vs ‘No Commission’; formatting output based on data presence.

NVL2(expr1, value_if_not_null, value_if_null)
SQL
SELECT employee_name, NVL2(commission, 'Has Commission', 
                      'No Commission') AS status
  FROM employees;
SQL

Outputs status based on whether commission is present.

Returns the first non-NULL expression from a list. It evaluates left to right and returns the first non-null value it encounters.

Use when checking multiple fallback columns for a valid value—e.g., primary email, then phone number, then eft_swift_code.

COALESCE(expr1, expr2, ..., expr_n)
SQL
SELECT contact_point_id, contact_point_type contact_type,     COALESCE(email_address, phone_number, eft_swift_code) AS contact_info
FROM hz_contact_points;
SQL

Returns the first available contact info.

Compares two expressions; if they are equal, returns NULL; otherwise returns the first expression. Useful in avoiding divide-by-zero or flagging identical values.

Avoid divide-by-zero by using NULLIF in denominator; suppress duplicate data in analytics.

NULLIF(expr1, expr2)
SQL
SELECT NULLIF(100, 100) FROM dual;
SQL

Returns NULL because the values are equal.

LNNVL (Logical Negation of NULL-Value Logic) is used to evaluate conditions that may involve NULL values. Unlike regular logical conditions, LNNVL helps to handle unknown (NULL) outcomes in WHERE clauses, returning a Boolean result when standard logic cannot.

It’s particularly useful when you want to apply filtering logic that gracefully handles NULL values without failing or skipping evaluations.

  • Filtering rows where a column may be NULL and you want to include them in logic-based queries.
  • Handling complex WHERE clause conditions where NULL should be treated as FALSE.
  • Alternative to NVL(condition, FALSE) for pure logical conditions.
LNNVL(condition)

Condition: A logical expression that may return TRUE, FALSE, or UNKNOWN (NULL).

🧪 Example 1: Basic Use
Return employees whose salary is not greater than 10000 or salary is NULL:

SQL
SELECT employee_name, salary
  FROM employees
 WHERE LNNVL(salary > 10000);
SQL

This will return:

  • Employees with salary less than or equal to 10000.
  • Employees with NULL salary (which would be skipped in a regular salary > 10000 condition).

🧪 Example 2: Safer NULL Handling in Conditions

SQL
SELECT * 
  FROM orders 
 WHERE LNNVL(discount > 0.05);
SQL

This query returns:

  • Orders with discount <= 0.05
  • Orders where discount is NULL

LNNVL is only allowed in the WHERE clause.

It is useful for improving the completeness of logical expressions without having to write complex CASE or NVL logic.

Extracts a substring from a given string, starting from a position and for a specified length.

Extracting product codes, initials, date parts from strings.

SUBSTR(string, start_position [, length])
SQL
SELECT SUBSTR('PROD_1234_XYZ', 6, 4) AS item_code 
  FROM dual;
SQL

Returns ‘1234’, the substring starting at position 6 and length of 4 characters.

Returns the position of a substring within a string. It’s useful for locating patterns or delimiters in text.

Extracting domain from email; parsing CSV or delimited strings.
Syntax:

INSTR(string, substring [, start_position [, occurrence]])
SQL
SELECT INSTR('Oracle SQL Guide', 'SQL') AS position 
  FROM dual;
SQL

Returns 8, the position where ‘SQL’ starts.

Returns the number of characters in a string. Useful for validation, truncation logic, or conditional formatting.

Checking length before storing user input; validating codes.

LENGTH(string)
SQL
SELECT LENGTH('Oracle') AS str_length 
  FROM dual;
SQL

Returns 6, the length of string “Oracle”

Removes specified characters (or whitespace by default) from the beginning and/or end of a string.

Cleaning up user input, ensuring consistent formatting before comparison.

TRIM([LEADING | TRAILING | BOTH] trim_character FROM string)
SQL
SELECT TRIM(' ' FROM ' Oracle ') AS cleaned 
  FROM dual;
SQL

Returns ‘Oracle’.

Removes leading characters (defaults to space) from a string.

Left-aligned formatting; parsing file names or strings with leading symbols.

LTRIM(string [, trim_characters])
SQL
SELECT LTRIM('***Oracle', '*') AS result FROM dual;
SQL

Returns ‘Oracle’.

Removes trailing characters (defaults to space) from a string.

Similar to LTRIM but for right-end cleanup. Useful in legacy file parsing.

RTRIM(string [, trim_characters])
SQL
SELECT RTRIM('Oracle***', '*') AS result FROM dual;
SQL

Returns ‘Oracle’.

Substitutes occurrences of a substring with another string. Helps in data cleansing and formatting.

Removing special characters, converting codes, or adjusting formats.

REPLACE(string, search_string, replacement_string)

SQL
SELECT REPLACE('2024-06-30', '-', '/') AS formatted_date 
  FROM dua
SQL

TRANSLATE is a character-level substitution function in Oracle SQL. It replaces each character in a source string with a corresponding character from a replacement string, character by character and positionally mapped. Unlike REPLACE, which works on substrings, TRANSLATE works at the single-character level, making it highly efficient for tasks like character filtering, encoding, or sanitization.

  • Data cleansing: Remove or substitute unwanted characters (e.g., symbols, punctuation).
  • Character masking: Replace specific characters for privacy or formatting.
  • Encoding: Convert characters into a mapped representation (e.g., internal encoding).
  • Replacing multiple characters in one go, unlike using multiple nested REPLACE() calls.
  • Removing characters: Map to an empty position by omitting characters in the replacement string.
TRANSLATE(source_string, from_string, to_string)
  • source_string: The string to modify.
  • from_string: Characters to find in source_string.
  • to_string: Characters to substitute for each character found in from_string. If shorter, characters are removed.

🧪 Example 1: SQL Function Replace characters

Replace 1, 2, and 3 with A, B and C respectively:

SQL
SELECT TRANSLATE('Order123', '123', 'ABC') AS translated_value
FROM dual;
SQL
Output: OrderABC

🧪 Example 2: SQL FunctionRemove unwanted characters

Remove hyphens, slashes, and periods from a string:

SQL
SELECT TRANSLATE('2024-06/19.', '-/.', '') AS cleaned_value
FROM dual;
-- Output: 20240619
SQL

Note: Characters in from_string with no matching position in to_string are removed.

🧪 Example 3: Simplified character encoding

Convert vowels to numbers:

SQL
SELECT TRANSLATE('DATABASE', 'AEIOU', '12345') AS encoded
FROM dual;
-- Output: D1T1B1S2
SQL

✅ Notes:

  • If from_string is longer than to_string, characters without a replacement are deleted.
  • It is case-sensitive.
  • Works best for character substitution—not suitable for pattern-based replacements (use REGEXP_REPLACE for that).

Converts all characters in a string to lowercase.

Normalizing data for comparisons, filtering, or storage.

LOWER(string)
SQL
SELECT LOWER('Oracle SQL') AS lower_text FROM dual;
SQL

Returns ‘oracle sql’.

Converts all characters in a string to uppercase. Useful for standardizing text data before comparison.

Ensuring case-insensitive searches; formatting user inputs or reference data.

UPPER(string
SQL
SELECT UPPER('oracle sql') AS upper_text FROM dual;
SQL

Returns ‘ORACLE SQL’.

Capitalizes the first letter of each word in a string and converts the rest to lowercase.

Formatting names, titles, or addresses in reports.

INITCAP(string)REGEXP
SQL
SELECT INITCAP('welcome to oracle sql') AS title_case FROM dual;
SQL

Returns ‘Welcome To Oracle Sql’.

Joins two strings together into one. Equivalent to using ||, but limited to two strings.

Concatenating names, codes, or building messages.

CONCAT(string1, string2)
SQL
SELECT CONCAT('Oracle', ' SQL') AS result FROM dual;
SQL

Returns ‘Oracle SQL’.

LPAD (Left Pad) adds characters to the left side of a string to make it a specific length. If the string is shorter than the specified length, padding characters are added; if longer, the string is truncated.

  • ✅ Formatting report columns to align text or numbers.
  • ✅ Creating fixed-width file exports.
  • ✅ Prefixing numeric codes with leading zeros or special characters.
LPAD(source_string, total_length, pad_char)
  • source_string: The original string to be padded.
  • total_length: Desired length of the output string.
  • pad_char: The character used for padding (default is space if omitted).
SQL
SELECT LPAD('123', 6, '0') AS padded_code
FROM dual;
-- Output: 000123
SQL
SQL
SELECT LPAD('Cat', 10, '.') AS padded_text
FROM dual;
-- Output: .......Cat
SQL

RPAD (Right Pad) works like LPAD, but it adds characters to the right of the original string to match the desired length.

  • ✅ Aligning text in reports and UIs.
  • ✅ Creating text-based barcodes or pseudo-formatting.
  • ✅ Constructing fixed-length record layouts.
RPAD(source_string, total_length, pad_char)
SQL
SELECT RPAD('Sam', 8) AS result
FROM dual;
-- Output: 'Sam     '
SQL
SQL
SELECT RPAD('A1', 5, '-') AS padded
FROM dual;
-- Output: A1---
SQL

CHR returns the character associated with a given ASCII (or Unicode) numeric code. It’s useful for adding non-printing characters like line feeds, tabs, or specific symbols in queries.

  • ✅ Insert control characters (like newline CHR(10) or tab CHR(9)).
  • ✅ Dynamically generate special character content.
  • ✅ ASCII-based character manipulations or encoding.
CHR(n)
  • n: The ASCII or Unicode code to convert.
SQL
SELECT 'Line1' || CHR(10) || 'Line2' AS result
FROM dual;
SQL
SQL
SELECT CHR(65) AS letter
FROM dual;
-- Output: A
SQL

ASCII does the opposite of CHR—it returns the numeric ASCII code for the first character in a string.

  • ✅ Determine character encoding.
  • ✅ Compare characters numerically.
  • ✅ Validate or filter special characters.
ASCII(char)

char: A single character or string; only the first character is evaluated.

SQL
SELECT ASCII('A') AS code
FROM dual;
-- Output: 65
SQL
SQL
SELECT ASCII(' ') AS code
FROM dual;
-- Output: 32
SQL

Returns the substring that matches a regular expression pattern.

Extracting specific patterns like IDs, codes, or keywords from text.

REGEXP_SUBSTR(source_string, pattern [, position [, occurrence [, match_param]]])
SQL
SELECT REGEXP_SUBSTR('ID-9876543-XYZ', '[0-9]+') AS extracted_id 
  FROM dual;
SQL

Returns ‘9876543’.

Replaces all or part of a string that matches a regular expression pattern.

Data cleansing (removing special characters, correcting formats).

REGEXP_REPLACE(source_string, pattern, replacement [, position [, occurrence [, match_param]]])
SQL
SELECT REGEXP_REPLACE('abc123xyz', '[0-9]', '') AS cleaned 
  FROM dual;
SQL

Returns ‘abcxyz’ (removes digits).

Returns the position of a pattern match using regular expressions.

Finding position of substrings with complex rules.

REGEXP_INSTR(string, pattern [, start_pos [, occurrence [, return_option [, match_param]]]])
SQL
SELECT REGEXP_INSTR('Oracle123SQL', '[0-9]+') AS number_pos 
  FROM dual;
SQL

Returns position of first digit in the string.

Performs regular expression matching, like LIKE, but with more power and flexibility.

Validating formats like email, phone numbers, codes.

REGEXP_LIKE(string, pattern)
SQL
SELECT email 
  FROM users 
 WHERE REGEXP_LIKE(email, '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$');
SQL

Filters rows with valid email format.

Returns the number of times a pattern appears in a string.

Counting delimiters, matches, tokens, or specific patterns.

REGEXP_COUNT(source_string, pattern [, position [, match_param]])
SQL
SELECT REGEXP_COUNT('aa12bb34cc56', '[0-9]+') AS count_numbers 
  FROM dual;
SQL

Returns 3.

Rounds a number to a specified number of decimal places.

Rounding currency or scores in finance and billing applications.

ROUND(number [, decimal_places])
SQL
SELECT ROUND(123.4567, 2) AS rounded_val FROM dual;
SQL

Returns 123.46.

Truncates a number (or date) to a specified number of decimal places or date unit.

Removing time from datetime; truncating prices or values to integer form.

TRUNC(number [, decimal_places])
TRUNC(date [, format])
SQL
SELECT TRUNC(123.456, 2) AS trunc_val FROM dual;
SQL

Returns 123.45

SQL
SELECT TRUNC(SYSDATE) AS trunc_date FROM dual;
SQL

Returns current date with time set to midnight.

Returns the remainder of a division operation.

Identifying even/odd numbers; cyclic checks in inventory or scheduling.

MOD(number1, number2)
SQL
SELECT MOD(10, 3) AS remainder FROM dual;
SQL

Returns 1.

Returns the absolute (non-negative) value of a number.

Removing sign from results in variance or deviation calculations.

ABS(number)
SQL
SELECT ABS(-150) AS abs_val FROM dual;
SQL

Returns 150.

Returns the smallest integer greater than or equal to a number.

Estimating packaging requirements, invoice rounding, or rounding up transaction amounts.

CEIL(number)
SQL
SELECT CEIL(15.2) AS ceil_val 
  FROM dual;
SQL

Returns 16.

Returns the largest integer less than or equal to a given number.

Rounding down prices, discounts, or number-based groupings in billing systems.

FLOOR(number)
SQL
SELECT FLOOR(15.78) AS floor_val 
  FROM dual;
SQL

Returns 15.

Returns -1, 0, or 1 depending on the sign of the number.

Used in algorithms that rely on the direction of a change (positive, negative, or neutral).

SIGN(number)
SQL
SELECT SIGN(-45) AS sign_val FROM dual;
SQL

Returns -1.

Raises a number to the power of an exponent.

Financial projections, scientific calculations.

POWER(base, exponent)
SQL
SELECT POWER(2, 3) AS result FROM dual;
SQL

Returns 8.

Returns the square root of a number.

Statistical analysis; distance or geometric calculations.

SQRT(number)
SQL
SELECT SQRT(49) AS result FROM dual;
SQL

Returns 7.

Returns the exponential value of a number (e to the power of x).

Scientific calculations, growth modeling, exponential scoring.

EXP(number)
SQL
SELECT EXP(1) AS e_val FROM dual;
SQL

Returns 2.718… (Euler’s number).

Returns the logarithm of a number for a specified base.

When you need log values to custom bases (e.g., base 10, base 2) for analytics or data compression.

LOG(base, number)
SQL
SELECT LOG(10, 1000) AS log_val FROM dual;
SQL

Returns 3.

Returns the natural logarithm (base e) of a number.

Logarithmic scales, financial growth models, and data transformations.

LN(number)
SQL
SELECT LN(10) AS log_result FROM dual;
SQL

Returns natural log of 10.

The GREATEST function returns the largest (maximum) value from a list of expressions. It compares two or more values of the same data type and returns the highest one. If any of the values is NULL, the result will be NULL (unless NULL is explicitly handled).

✅ Find the maximum of multiple column values for a single row.
✅ Determine the latest date among several columns.
✅ Compare user inputs or calculations and select the best/highest value.

GREATEST(expr1, expr2, ..., exprN)
  • Each expr must be of a comparable data type (e.g., all numbers or all dates).
Find highest salary or bonus
SELECT employee_name,
       GREATEST(salary, bonus) AS max_payment
FROM employees;
Find highest salary or bonus
Get latest of three dates
SELECT GREATEST(hire_date, review_date, sysdate) AS latest_event
FROM employee_reviews;
Find latest of three dates

🔍 Note:
If any input is NULL, the result is NULL unless you wrap values with NVL() or COALESCE() to avoid this behavior.

The LEAST function returns the smallest (minimum) value from a list of expressions. It is the counterpart to GREATEST and is used to identify the lowest value from multiple columns or expressions.

  • ✅ Identify the lowest of several numeric scores or thresholds.
  • ✅ Determine the earliest date among multiple columns.
  • ✅ Apply constraints or limits based on minimal values.
LEAST(expr1, expr2, ..., exprN)
Find smaller of two amounts
SELECT customer_id, LEAST(max_credit_limit, current_balance) AS risk_threshold
  FROM accounts;
Find smaller of two amounts
Get earliest date
SELECT LEAST(start_date, deadline_date, sysdate) AS earliest_date
FROM project_schedule;
Find earliest date

🔍 Note:
Like GREATEST, LEAST returns NULL if any argument is NULL unless handled explicitly.

Returns the current system date and time.

Timestamping records, calculating durations, or filtering records based on current date.

SYSDATE
SQL
SELECT SYSDATE FROM dual;
SQL

Returns current date and time from the database server.

Returns the current date in the session’s time zone. Unlike SYSDATE, which uses the database server’s time zone, this reflects the user’s time zone.

Applications with global users needing local timestamps.

CURRENT_DATE
SQL
SELECT CURRENT_DATE FROM dual;
SQL

Returns the current date and time for the user session.

Returns the system’s current timestamp with time zone and fractional seconds.

Auditing, system-level logs, precise time records.

SYSTIMESTAMP
SQL
SELECT SYSTIMESTAMP FROM dual;
SQL

Returns: ‘2025-06-19 22:45:30.123456 +05:30’.

Returns the current timestamp without the time zone.

When timezone context is not needed, but time precision is.

LOCALTIMESTAMP
SQL
SELECT LOCALTIMESTAMP AS local_time FROM dual;
SQL

Shows timestamp based on local session setting.

Adds or subtracts a number of months to/from a date.

Calculating future billing dates, policy expiry, subscription renewal.

ADD_MONTHS(date, number_of_months)
SQL
SELECT ADD_MONTHS(SYSDATE, 3) AS expiry_date FROM dual;
SQL

Returns date 3 months from today.

Returns the number of months between two dates, including fractional months.

Age calculations, financial interest duration.

MONTHS_BETWEEN(date1, date2)
SQL
SELECT MONTHS_BETWEEN(SYSDATE, TO_DATE('2024-06-01', 'YYYY-MM-DD')) AS months_diff FROM dual;
SQL

Returns the number of months between two dates.

Returns the next specified weekday after a given date.

Scheduling tasks for the next Monday, Friday, etc.

NEXT_DAY(date, 'DAY_OF_WEEK')
SQL
SELECT NEXT_DAY(SYSDATE, 'MONDAY') AS next_monday FROM dual;
SQL

Returns the date of the upcoming Monday.

Returns the last day of the month for a given date.

End-of-month reports, salary payment scheduling.

LAST_DAY(date)
SQL
ELECT LAST_DAY(SYSDATE) AS eom_date FROM dual;
SQL

Returns the last day of the current month.

Truncates the time portion of a date or rounds it to the start of a specified unit (like month or year).

Comparing dates without time; grouping by month/year.

TRUNC(date [, format])
SQL
SELECT TRUNC(SYSDATE, 'MM') AS month_start FROM dual;
SQL

Returns the first day of the current month.

Rounds a date to the nearest day, month, or specified unit.

Rounding invoice dates, adjusting for nearest reporting periods.

ROUND(date [, format])
SQL
SELECT ROUND(TO_DATE('2025-06-19 12:00:00', 'YYYY-MM-DD HH24:MI:SS')) FROM dual;
SQL

Returns 2025-06-20 (rounded up at noon).

Extracts a specific part (year, month, day, etc.) from a date or timestamp.

Creating year-wise reports, filtering by quarter/month.

EXTRACT(part FROM date)
SQL
SELECT EXTRACT(YEAR FROM SYSDATE) AS current_year FROM dual;
SQL

Returns current year as a number.

Converts date or number values into string format with optional formatting.

Displaying formatted dates, currency, or numeric results.

TO_CHAR(date, 'format')
SQL
SELECT TO_CHAR(SYSDATE, 'YYYY-MM-DD') AS today FROM dual;
SQL

Returns the current date as ‘2025-06-19’.

Converts a string into a date, using a specified format.

Converting user input or file input into valid Oracle dates.

TO_DATE(string, 'format')
SQL
SELECT TO_DATE('2025-06-30', 'YYYY-MM-DD') AS valid_date FROM dual;
SQL

Converts string to a DATE value.

Converts a string into a number using a specified format.

Parsing numeric input from string-based sources like forms or logs.

TO_NUMBER(string [, 'format'])
SQL
SELECT TO_NUMBER('1,500.75', '9,999.99') AS numeric_val FROM dual;
SQL

Returns 1500.75.

Converts one data type to another (standard SQL-compliant). Works for number, date, varchar, etc.

When writing portable SQL; converting values in views or subqueries.

CAST(expression AS target_type)
SQL
SELECT CAST(123 AS VARCHAR2(10)) AS text_val FROM dual;
SQL

Returns ‘123’ as a string.

The CONVERT function in Oracle SQL is used to convert a string from one character set to another. This is particularly useful in multilingual applications, data migrations, or when exchanging data between Oracle databases configured with different character sets.

✅ Convert legacy data (e.g., from WE8ISO8859P1) to a modern character set (e.g., AL32UTF8).
✅ Prevent mojibake (garbled characters) when exporting/importing multi-language content.
✅ Cleanse strings received from third-party systems with non-standard encoding.

CONVERT(string, to_charset [, from_charset])
SQL
SELECT CONVERT('München', 'AL32UTF8', 'WE8ISO8859P1') AS utf8_name
FROM dual;
SQL

This ensures characters like ü are correctly interpreted and stored in UTF-8.

Returns a VARCHAR2 value with datatype code, length in bytes, and internal representation.

Debugging encoding or datatype issues.

DUMP(expr [, return_format [, start_position [, length]]])
SQL
SELECT DUMP('Oracle') AS dump_info FROM dual;
SQL

Returns internal binary details of the string.

BIN_TO_NUM is a numeric function in Oracle SQL that converts a set of binary flags (0s and 1s) into a decimal (base-10) number. Each argument represents a binary digit (bit), and the function calculates the equivalent decimal number as if those digits were a binary number.

This is useful for bitmask operations, flag processing, and storing multiple yes/no options compactly in a single numeric value.

✅ Convert binary flag values (e.g., user permissions, feature toggles) into a single number for storage.
✅ Reverse bitmask logic by reconstructing a number from bitwise flags.
✅ Simulate binary representation in analytics or system-level reporting.

BIN_TO_NUM(bit1, bit2, ..., bitN)
SQL
SELECT BIN_TO_NUM(1, 0, 1, 1) AS result
FROM dual;
SQL

— Output: 11

1x8 + 0x4 + 1x2 + 1x1 = 11

Converts a number to an interval of days, hours, minutes, or seconds.

Adding time intervals dynamically to dates.

NUMTODSINTERVAL(n, 'interval_unit')
SQL
SELECT SYSDATE + NUMTODSINTERVAL(2, 'DAY') AS future_date FROM dual;
SQL

Adds 2 days to the current date.

Converts a number to an interval of years or months.

Working with duration in years or months when adjusting dates.

NUMTOYMINTERVAL(n, 'interval_unit')
SQL
SELECT SYSDATE + NUMTOYMINTERVAL(1, 'YEAR') AS next_year FROM dual;
SQL

Adds 1 year to today’s date.

Acts like a simple IF-ELSE logic by comparing an expression to multiple values and returning matching results.

Mapping department IDs to department names; converting status codes to readable strings.

DECODE(expr, search1, result1 [, search2, result2, ...] [, default_result])
SQL
SELECT DECODE(department_id, 10, 'Accounting', 20, 'HR', 30, 'IT', 'Other') AS dept_name
FROM employees;
SQL

Maps department IDs to readable department names.

Provides conditional logic in SQL queries, similar to IF-ELSE structures.

Classifying data, implementing custom business logic in SELECT or WHERE clauses.

CASE 
  WHEN condition1 THEN result1
  WHEN condition2 THEN result2
  ...
  ELSE default_result
END
SQL
SELECT employee_name,
       CASE 
         WHEN salary > 10000 THEN 'High'
         WHEN salary BETWEEN 5000 AND 10000 THEN 'Medium'
         ELSE 'Low'
       END AS salary_band
FROM employees;
SQL

Categorizes employees based on salary.

The SUM function adds up numbers in a column. It ignores any NULL values.

  • Calculate total sales
  • Get total salary paid to employees
  • Add up invoice amounts
  • Syntax of Oracle SQL Function
SUM(column_name)
SQL
SELECT SUM(salary) AS total_salary
FROM employees;
SQL

✅ This query returns the total salary of all employees.

The AVG function calculates the average of values in a column. NULLs are skipped.

  • Average employee salary
  • Average product price
  • Average transaction value
AVG(column_name)
SQL
SELECT AVG(salary) AS avg_salary
  FROM employees;
SQL

✅ This gives the average salary across all employees.

The MAX function finds the largest value in a column. It works on numbers, dates, and text.

  • Get the highest salary
  • Show the most recent transaction
  • Find the longest name
MAX(column_name)
SQL
SELECT MAX(salary) AS highest_salary
  FROM employees;
SQL

✅ This query returns the highest salary.

The MIN function finds the smallest value in a column. It works with numbers, dates, and text.

  • Find the earliest hire date
  • Get the lowest salary
  • Pick the first product alphabetically
MIN(column_name)
SQL
SELECT MIN(hire_date) AS earliest_hire
  FROM employees;
SQL

✅ This shows the first hire date from the employees table.

The COUNT function returns the number of rows. It can count all rows or only non-null values in a column.

  • Count total employees
  • Count how many records have a value
  • Count distinct customers
COUNT(*)
COUNT(1)
COUNT(column_name)
✅ This gives the total number of employees.
SELECT COUNT(*) AS total_employees
FROM employees;
This gives the total number of employees.
SQL
SELECT COUNT(commission_pct) AS with_commission
FROM employees;
SQL

✅ This counts employees who have a commission value.

The STDDEV function returns the standard deviation of numeric values. It shows how much data varies from the average.

  • Measure sales consistency
  • Analyze variation in salaries
  • Monitor price fluctuation
STDDEV(column_name)
SQL
SELECT STDDEV(salary) AS salary_deviation
FROM employees;
SQL

✅ This shows how much the salary differs from the average.

The VARIANCE function measures the spread of numbers. It returns the statistical variance of numeric values.

  • Financial data analysis
  • Salary spread in departments
  • Variance in product pricing
VARIANCE(column_name)
SQL
SELECT VARIANCE(salary) AS salary_variance
  FROM employees;
SQL

✅ This shows how salaries are spread out in the organization.

Distinguishes NULLs caused by grouping (i.e., summary rows in GROUP BY CUBE or ROLLUP).

  • Add labels like ‘Total’ in summary reports
  • Distinguish between grouped data and subtotals when using ROLLUP or CUBE
GROUPING(column)
SQL
SELECT department_id, job_id, SUM(salary),
       GROUPING(department_id) AS dept_group
FROM employees
GROUP BY ROLLUP(department_id, job_id);
SQL

Identifies subtotal or grand total rows.

Generates all possible subtotals and grand total combinations for specified columns.

Multidimensional data summarization (e.g., sales by year, product, and region).

GROUP BY CUBE(column1, column2, ...)
SQL
SELECT department_id, job_id, SUM(salary)
FROM employees
GROUP BY CUBE(department_id, job_id);
SQL

Includes all combinations of subtotals and grand total.

Produces group subtotals and grand totals by adding extra rows to a GROUP BY.

Reporting sales totals by region, with overall summary.

GROUP BY ROLLUP(column1, column2, ...)
SQL
SELECT department_id, job_id, SUM(salary)
FROM employees
GROUP BY ROLLUP(department_id, job_id);
SQL

Adds subtotals per department and grand total.

Assigns a rank to each row in a result set with possible gaps in ranking for ties.

Leaderboards, sales rankings, top performers.

RANK() OVER (ORDER BY column)
SQL
SELECT employee_name, salary, RANK() OVER (ORDER BY salary DESC) AS rank
FROM employees;
SQL

Employees with the same salary receive the same rank, next ranks are skipped.

Similar to RANK(), but does not skip ranks if there are ties.

Creating compact ranking lists where rank gaps are not desirable.

DENSE_RANK() OVER (ORDER BY column)
SQL
SELECT employee_name, salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rank
FROM employees;
SQL

No gaps in ranking even with duplicate values.

Assigns a unique number to each row based on specified sort criteria, regardless of duplicates.

Paginated queries, fetching top-N rows per group.

ROW_NUMBER() OVER (ORDER BY column)
SQL
SELECT employee_name, salary, ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_num
FROM employees;
SQL

Returns unique row numbers starting from 1.

Divides a result set into a specified number of buckets (tiles), assigning each row a bucket number.

Quartile-based reports (top 25%, mid-range, etc.), percentile distribution.

NTILE(n) OVER (ORDER BY column)
SQL
SELECT employee_name, salary, NTILE(4) OVER (ORDER BY salary DESC) AS salary_quartile
FROM employees;
SQL

Divides employees into 4 salary-based groups.

Accesses data from a previous row (offset) without self-joins.

Comparing current vs. previous values (e.g., monthly sales difference).

LAG(column [, offset, default]) OVER (ORDER BY column)
SQL
SELECT month, sales, LAG(sales, 1, 0) OVER (ORDER BY month) AS prev_month_sales
FROM sales_data;
SQL

Shows previous month’s sales next to current.

Accesses data from a following row (offset).

Forecasting next period values, detecting changes

LEAD(column [, offset, default]) OVER (ORDER BY column)
SQL
SELECT month, sales, LEAD(sales, 1, 0) OVER (ORDER BY month) AS next_month_sales
FROM sales_data;
SQL

Shows next month’s sales beside the current.

Returns the first value in an ordered partition of rows.

Show the first sale of each region, or initial status.

FIRST_VALUE(column) OVER (ORDER BY column)
SQL
SELECT department_id, employee_name, salary,
       FIRST_VALUE(salary) OVER (PARTITION BY department_id ORDER BY salary DESC) AS top_salary
FROM employees;
SQL

Shows top salary per department.

Returns the last value in an ordered window.

Reporting trailing values, final status, last sale.

LAST_VALUE(column) OVER (ORDER BY column ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
SQL
SELECT department_id, employee_name, salary,
       LAST_VALUE(salary) OVER (PARTITION BY department_id ORDER BY salary DESC 
       ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS lowest_salary
FROM employees;
SQL

Shows lowest salary per department.

The NTH_VALUE() function returns the nth value from a result set based on a specified sort order within a window or partition.

  • Show the second or third highest salary
  • Get the first and third products sold in each region
  • Return the nth order date per customer
NTH_VALUE(column_name, n) 
OVER ([PARTITION BY expr] ORDER BY sort_expr [ROWS BETWEEN ...])
SQL
SELECT employee_id,
       department_id,
       salary,
       NTH_VALUE(salary, 2) OVER (PARTITION BY department_id ORDER BY salary DESC) AS second_highest_salary
FROM employees;
SQL

✅ This returns each employee’s salary and shows the second highest salary in their department.

Returns the relative rank of a row as a percentage (0 to 1).

Percentile comparisons in academic, statistical, or business data.

PERCENT_RANK() OVER (ORDER BY column)
SQL
SELECT student_id, score, PERCENT_RANK() OVER (ORDER BY score DESC) AS score_percentile
FROM test_results;
SQL

Calculates percentile rank for each score.

Returns cumulative distribution (percent of rows ≤ current row).

Benchmarking, percentile grouping, and progress thresholds.

CUME_DIST() OVER (ORDER BY column)
SQL
SELECT employee_id, salary, CUME_DIST() OVER (ORDER BY salary) AS salary_percent
FROM employees;
SQL

Returns the proportion of salaries less than or equal to the current one.

Returns the numeric ID of the currently logged-in user.

System-level logging, internal references.

UID
SQL
SELECT UID FROM dual;
SQL

Returns an internal numeric ID of the session user.

Returns the name of the currently connected Oracle user.

Session tracking, auditing, multi-user reporting.

USER
SQL
SELECT USER FROM dual;
SQL

Returns the schema or username.

Returns information about the current session environment (like language, host, terminal).

Conditional logic based on user session, audits, and debugging.

USERENV
SQL
SELECT USERENV('LANGUAGE') AS session_language FROM dual;
SQL

Returns something like ‘AMERICAN_AMERICA.AL32UTF8’.

Returns the number of bytes used by an expression (in memory).

Storage analysis, space optimization.

VSIZE(expr)
SQL
SELECT VSIZE('Oracle') AS size_bytes FROM dual;
SQL

Returns 6.

Retrieves session-related information from a specified namespace.

Tracking IP, client details, application name during session.

SYS_CONTEXT('namespace', 'parameter')
SQL
SELECT SYS_CONTEXT('USERENV', 'IP_ADDRESS') AS client_ip FROM dual;
SQL

Returns the client IP address if available.

ORA_HASH generates a hash value for a given input, typically used to distribute, group, or partition data efficiently. It’s a deterministic hash function — the same input always yields the same output — and is commonly used for:

  • Load balancing across partitions.
  • Fast equality comparisons.
  • Simulating hash joins or hash buckets.

It works on many data types, including strings, numbers, and dates.

  • ✅ Distribute rows uniformly across hash partitions or parallel processes.
  • ✅ Create fast lookup structures (like hash buckets) for comparison operations.
  • ✅ Group large volumes of data without scanning entire values.
  • ✅ Simulate consistent hashing logic for ETL or data warehousing.
ORA_HASH(expr [, max_bucket [, seed_value]])
  • expr: The expression to hash (string, number, etc.).
  • max_bucket (optional): Highest hash bucket value. Result will be between 0 and this number.
  • seed_value (optional): Number to initialize the hash calculation for custom behavior.
SQL
SELECT employee_id, ORA_HASH(employee_id, 9) AS bucket
FROM employees;
-- Returns value between 0 and 9
SQL
  • ORA_HASH is non-cryptographic. It is not meant for data security or password hashing.
  • It’s fast and lightweight, suitable for large-scale grouping and comparisons.
  • Returns NULL if expr is NULL.

Generates a globally unique identifier in RAW(16) format.

Creating primary keys, tracking unique events across systems.

SYS_GUID()
SQL
SELECT SYS_GUID() AS unique_id FROM dual;
SQL

Returns a unique RAW value for each row.

JSON_OBJECT constructs a well-formed JSON object from column values or expressions. It’s used to generate JSON directly from SQL queries, useful in APIs, reports, or when storing structured data as JSON.

  • ✅ Generate JSON output from relational rows.
  • ✅ Build JSON-based APIs directly from SQL.
  • ✅ Insert structured JSON into CLOB or BLOB columns.
JSON_OBJECT(key1 VALUE expr1 [, key2 VALUE expr2, ...])
Create a JSON object of employee data
SELECT JSON_OBJECT('name' VALUE first_name, 'salary' VALUE salary)
FROM employees
WHERE employee_id = 101;
Create a JSON object of employee data
{"name":"John","salary":6000}

JSON_VALUE extracts a scalar value (string, number, Boolean, etc.) from a JSON-formatted string stored in a column or expression.

  • ✅ Query a specific value from stored JSON.
  • ✅ Use JSON fields in WHERE or SELECT.
  • ✅ Filter data based on JSON attributes.
JSON_VALUE(json_column, '$.path')
Get the employee city from a JSON column
SELECT JSON_VALUE(employee_data, '$.address.city') AS city
FROM employee_json
WHERE department_id = 10;
Get the employee city from a JSON column

JSON_TABLE maps JSON data into relational rows and columns. It acts like a virtual table derived from a JSON document, enabling joins and aggregation.

  • ✅ Flatten nested JSON for reporting.
  • ✅ Query JSON as if it were a table.
  • ✅ Join JSON data with relational tables.
JSON_TABLE(json_column, '$.path'
  COLUMNS (
    column1 PATH '$.key1',
    column2 PATH '$.key2'
  )
)
Parse an array of employees from a JSON column
SELECT jt.*
FROM departments d,
     JSON_TABLE(d.employee_json, '$.employees[*]'
       COLUMNS (
         emp_name VARCHAR2(50) PATH '$.name',
         emp_role VARCHAR2(50) PATH '$.role'
       )
     ) jt;
Parse an array of employees from a JSON column

XMLAGG aggregates XML fragments into a single XML document. It is used to concatenate XML-formatted rows, commonly in XML reports or legacy integrations.

  • ✅ Concatenate multiple XML rows into one.
  • ✅ Generate XML documents from query output.
  • ✅ Use with XMLELEMENT for structured XML output.
XMLAGG(XMLELEMENT("tag", column)) [ORDER BY clause]
Generate a list of employee names in XML
SELECT XMLAGG(XMLELEMENT("employee", first_name) ORDER BY first_name) AS xml_result
FROM employees;
Generate a list of employee names in XML

PIVOT transforms rows into columns, allowing you to rotate data for better readability or matrix-style analysis. It is especially useful in reports.

  • ✅ Convert row data into columnar summaries.
  • ✅ Create cross-tab reports (e.g., monthly totals).
  • ✅ Summarize values across categories.
SELECT * FROM (
  SELECT column1, column2, value
  FROM your_table
)
PIVOT (
  AGG_FUNCTION(value)
  FOR column2 IN ('VAL1' AS col1, 'VAL2' AS col2)
);
Parse an array of employees from a JSON column
SELECT *
FROM (
  SELECT dept_id, month, salary
  FROM payroll
)
PIVOT (
  SUM(salary)
  FOR month IN ('JAN' AS Jan, 'FEB' AS Feb, 'MAR' AS Mar)
);
Parse an array of employees from a JSON column

UNPIVOT rotates columns into rows, essentially reversing the effect of PIVOT. It is used to normalize denormalized data for querying or storage.

  • ✅ Reshape wide tables into vertical formats.
  • ✅ Prepare data for analytics or ETL.
  • ✅ Convert columnar time-series data into rows.
SELECT * FROM your_table
UNPIVOT (
  value FOR column_name IN (col1 AS 'VAL1', col2 AS 'VAL2')
);
UNPIVOT
SELECT *
FROM monthly_salaries
UNPIVOT (
  salary FOR month IN (jan AS 'JAN', feb AS 'FEB', mar AS 'MAR')
);
UNPIVOT

Final Thoughts

This extensive list provides a powerful toolkit for anyone working with SQL. By understanding and effectively utilizing these 100 functions, you can significantly enhance your ability to query, transform, analyze, and manage data efficiently across various database platforms. Remember that while many functions are standardized, some have database-specific implementations or variations, so always consult your database’s official documentation for precise syntax and behavior. Practice these functions regularly to unlock the full potential of your SQL queries and become a more proficient data professional.

This Post Has 2 Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.