Fanciful illustration of a conveyor belt with a blade cutting up a string of colourful text characters.

Truncating a string to N bytes using SUBSTRB

A VARCHAR2 variable or database column is declared with a certain maximum size, expressed as a number of characters or bytes; a VARCHAR2(100 CHAR) allows any string up to 100 characters, whereas a VARCHAR2(100 BYTE) allows any string that can fit within 100 bytes.

Both of these will accept single- and multi-byte characters; however they differ in how long a string they will accept.

We can create a simple test case – construct a string with 3,999 single-byte characters, followed by a multi-byte character. We can examine the length of the string using LENGTH (to get the number of characters) and LENGTHB (to get the size in bytes):

declare
    l_string varchar2(4000 char);
begin
    l_string := lpad('a',3999,'a') || '€';
    dbms_output.put_line('characters: ' || LENGTH(l_string));
    dbms_output.put_line('bytes: '      || LENGTHB(l_string));
end;
/

characters: 4000
bytes: 4002

From this test case we can see that our final character (“€”) requires 3 bytes to store it.

A common scenario is a table column declared as VARCHAR2(4000); unless extended strings are enabled, the database will limit this to 4000 bytes. A PL/SQL string declared as VARCHAR2(4000 char) will allow up to 4000 characters; if there are some multi-byte characters in there, it will fail with ORA-12899: value too large for column if we try to insert that into the table:

create table t (a varchar2(4000 byte));

declare
    l_string varchar2(4000 char);
begin
    l_string := lpad('a',3999,'a') || '€';
    insert into t (a) values (l_string);
end;
/

ORA-12899: value too large for column "DEMO"."T"."A" (actual: 4002, maximum: 4000)

Let’s say you don’t care if some multi-byte characters at the end of a long string are lost, you just want to store as much as possible within the 4000-byte limit but you don’t want to corrupt or split up any multi-byte characters. The obvious choice might be to use SUBSTR to truncate the string:

declare
    l_string varchar2(4000 char);
begin
    l_string := lpad('a',3999,'a') || '€';
    insert into t (a) values ( SUBSTR(l_string, 1, 4000) );
end;
/

ORA-12899: value too large for column "DEMO"."T"."A" (actual: 4002, maximum: 4000)

That didn’t work, because SUBSTR uses character-length semantics; it effectively returned the same string of exactly 4000 characters. If we reduce the size, e.g. trim it to an arbitrarily smaller length of 2000 or 1000 characters, it should fit in most cases. However, we’re now losing a lot more data, and there may be some strings with many multi-byte characters (e.g. a message using many Japanese or Chinese characters, or supplementary characters) that might still not fit and fail to be inserted even after selecting a much smaller number of characters.

We need to use its byte-length variant, SUBSTRB. This returns a substring starting from a given character offset (the 1st character, in this example), and only returns a string that will fit within the given maximum number of bytes (4000, in this example):

declare
    l_string varchar2(4000 char);
begin
    l_string := lpad('a',3999,'a') || '€';
    insert into t (a) values ( SUBSTRB(l_string, 1, 4000) );
end;
/

PL/SQL procedure successfully completed.

Let’s look at the result:

select length(a), lengthb(a) from t;

 LENGTH(A) LENGTHB(A)
---------- ----------
      4000       4000

We know that that final character requires 3 bytes to store, so what has SUBSTRB done with it? Let’s examine what’s actually been stored at that location. We’ll take a substring starting from the last 'a' just before the last character in the string, and use the DUMP function to find out exactly what has been stored there.

select
    '[...' || substr(a, 3999) || ']' a,
    DUMP(substr(a, 3999)) b
from t;

A       B
------- ------------------
[...a ] Typ=1 Len=2: 97,32

As expected, there is a character 'a' (ascii 97) at offset 3999. However, at offset 4000 we see a simple space character (ascii 32). We weren’t expecting our Euro character, because it cannot be squashed into a single byte, but we weren’t expecting SUBSTRB to replace it with anything.

From this we can divine that whenever SUBSTRB can’t fit a multi-byte character into the requested maximum number of bytes, it will drop the trailing character(s) and pad the result with spaces. This specific behaviour is not documented – in fact, the documentation for SUBSTRB leaves this behaviour undefined. In most cases, however, this is not a big issue.

Alternative Approaches

I’ve been informed that the preferred behaviour would be that multi-byte characters that cannot fit should be simply omitted from the result and not replaced with any padding. This would then return a string that may be shorter than the requested number of bytes.

Oracle has not implemented this preferred behaviour of SUBSTRB (in the default case) mainly due to a need to maintain backwards compatibility with existing code that currently expects the padding.

If you don’t want the spaces, there are a few approaches with varying results:

Option 1. Use RTRIM to drop the trailing space(s)

declare
    l_string varchar2(4000 char);
begin
    l_string := lpad('a',3999,'a') || '€';
    insert into t (a) values ( RTRIM(substrb(l_string, 1, 4000)) );
end;
/

PL/SQL procedure successfully completed.

select
    '[...' || substr(a, 3999) || ']' a,
    dump(substr(a, 3999)) b
from t;

A       B
------- ---------------
[...a]  Typ=1 Len=1: 97

This works fine, but it’s a bit heavy-handed. What if the original string was composed of some ordinary spaces at the end and you wanted those to be retained? They will be silently removed by the call to RTRIM. If that’s not a concern, however, this method works fine.

Option 2. Use the NO_SUBSTRB_PAD hint (SQL only)

If you’re querying a table that has long strings, potentially containing multi-byte characters, and you want to limit the size of the result, and you don’t want to use the RTRIM method, this is a potential solution. I’ve been informed the NO_SUBSTRB_PAD hint invokes the preferred behaviour of SUBSTRB which is to drop multi-byte characters that cannot fit.

with src as (
    select 'aaa€' as a
    from dual
)
select /*+ NO_SUBSTRB_PAD */
    '[' || substrb(a, 1, 4) || ']' a,
    dump(substrb(a, 1, 4)) b
from src;

A     B
----- ---------------------
[aaa] Typ=1 Len=3: 97,97,97

This hint is not documented but has been mentioned elsewhere. It affects all references to the SUBSTRB function within the query.

Option 3. Use a custom function

The following function removes trailing characters from the end of the string so that the result is guaranteed to fit within the given number of bytes:

create function truncate_bytes (
    p_text      in varchar2,
    p_max_bytes in pls_integer
) return varchar2 deterministic
is
--
-- TRUNCATE_BYTES returns a string guaranteed to fit
-- within p_max_bytes bytes, containing the maximum
-- number of full characters (whether multibyte or
-- otherwise) from the start of p_text. The result
-- may have fewer than p_max_bytes bytes.
--
    l_low  pls_integer := 0;
    l_high pls_integer;
    l_mid  pls_integer;
begin
    if p_max_bytes is null or p_max_bytes < 0 then
        raise value_error;
    elsif p_text is null or p_max_bytes = 0 then
        return null;
    elsif lengthb(p_text) <= p_max_bytes then
        return p_text;
    end if;
    l_high := least(lengthc(p_text), p_max_bytes);
    while l_low < l_high loop
        l_mid := l_low + trunc((l_high - l_low + 1) / 2);
        if lengthb(substrc(p_text, 1, l_mid)) <= p_max_bytes then
            l_low := l_mid;
        else
            l_high := l_mid - 1;
        end if;
    end loop;
    return substrc(p_text, 1, l_low);
end;
declare
    l_string varchar2(4000 char);
begin
    l_string := lpad('a',3999,'a') || '€';
    l_string := TRUNCATE_BYTES(l_string, 4000);
    insert into t (a) values ( l_string );
end;
/

PL/SQL procedure successfully completed.

select
    '[...' || substr(a, 3999) || ']' a,
    dump(substr(a, 3999)) b
from t;

A       B
------- ---------------
[...a]  Typ=1 Len=1: 97

The downsides to this approach are that it requires compiling a function in your schema, and it will not perform as well as native database functions. Benchmark it before calling it from a SQL query across a large data set.

Note that the function uses LENGTHC and SUBSTRC when determining how many characters to lop off the end of the string. These variants treat each supplementary Unicode character as one complete character, even when the database character set would otherwise count its surrogate pair as two units. Supplementary characters include many emoji, some mathematical and musical symbols, additional Chinese/Japanese/Korean ideographs, and characters from writing systems such as Egyptian hieroglyphs.

Option 4. Modify the database session (undocumented)

Setting event 10943 at level 524288 will invoke the alternative behaviour of all calls to SUBSTRB, whether in SQL or PL/SQL. However, as this is undocumented, make sure you raise an SR and get written approval from Oracle Support before using it.

alter session set events '10943 trace name context forever, level 524288';

declare
    l_string varchar2(4000 char);
begin
    l_string := lpad('a',3999,'a') || '€';
    dbms_output.put_line('[' || substrb(l_string, 3999, 2) || ']');
end;
/

[a]

Huge thanks to Connor McDonald for valuable discussions and for digging up some details I’ve shamelessly reproduced in this post. If there are any errors in this article, however, they are almost certainly mine!

Related:


Truncate the middle of a long string

This is a little tip you might find handy.

Every typical database stores important strings like place names that are then displayed in reports and charts. Most of the time these strings are relatively short (e.g. 30-40 characters) and the reports and charts look fine, but occasionally some records happen to require a much longer string (e.g. 500+ characters) and these strings might cause the reports and charts to become a bit less visually pleasing. In some cases you can get rendering errors where the title or some attribute in a chart is just too long.

Most of the time, the most important information in such a long name is at the start and/or the end of the string; to compromise and show as much as we can fit on the page, we can truncate the middle of the string and replace it with “..” to show that some text has been removed.

The simplest way to do this without a complex expression involving some combination of LENGTH, CASE and SUBSTR is with a single REGEXP_REPLACE using backreferences to retain the start and end of the string:

select REGEXP_REPLACE(
    'My very very very long string abcdefghijklmnopqrstuvwxyz hello world wow this string is really very very very long.',
    '^(.{50}).{3,}(.{50})$', -- get the first and last 50 characters
    '\1..\2',                -- replace the middle with ".."
    1, 1, 'n'                -- treat entire string including newlines
) from dual;

I’ve chosen to keep the first 50 and the last 50 characters in this example. The result:

My very very very long string abcdefghijklmnopqrst..rld wow this string is really very very very long.

If you want to use this trick, you can adjust the length of the resulting string to whatever maximum length you want: choose how many characters to take from the start of the string and the end of the string by changing the two numbers (e.g. 50) in the regular expression.

Testing with a shorter string, we expect it to return the string unmodified:

select REGEXP_REPLACE(
    'This is a nice shorter string with <= 102 characters; the entire string should be returned unmodified.',
    '^(.{50}).{3,}(.{50})$', '\1..\2', 1, 1, 'n'
) from dual;
This is a nice shorter string with <= 102 characters; the entire string should be returned unmodified.

If the incoming string is already 102 characters or shorter, no replacement is done. In every case, we have guaranteed the resulting string will never be longer than 102 characters.


APEX App Object Dependencies

  • Got a lot of APEX applications, and/or a schema with lots of objects?
  • Not sure exactly what database objects are used by which application?
  • Not sure dropping a particular schema object might break something in your application?
  • Not sure if all the SQL and PL/SQL in every page of your application still runs without error?

If your answer to any of the above is “Yes”, you may be interested in a new API that has been added in APEX 24.1 and updated in 24.2.

Photograph of clouds lit by sunset over eucalyptus trees.

You can use this API to scan your application for any references to any schema objects, whether it refers to objects in a region, SQL queries, PL/SQL processes, and even plugins. Run this in your workspace, giving it the ID of an application you want to scan:

begin
  apex_app_object_dependency.scan(p_application_id => :app_id);
end;

This scans through the whole application by generating a small temporary procedure that tests each schema object name, SQL, or PL/SQL. As it goes, it checks that the code compiles without error, and if it compiles, it saves a list of dependencies detected by the database including tables, views, stored functions and procedures, packages, and synonyms. It drops the temporary procedure at the end.

Depending on how big your application is, the scan may take some time to complete (e.g. 30 to 60 seconds) due to the time required to compile and analyze each temporary procedure. If you find it gets stopped prematurely due to a timeout error, you can run it in the background (for example, I like to use an “Execution Chain” process in an APEX application with “Run in Background” enabled).

Note that none of your application code is actually executed, so there should be no side effects of running the scan. However, if your database has any DDL triggers, they may fire as the temporary procedure is created and dropped.

Viewing the Scan Results

Once the scan is complete, you can query the results at your leisure by querying these views:

  • APEX_USED_DB_OBJECTS
  • APEX_USED_DB_OBJECT_COMP_PROPS
  • APEX_USED_DB_OBJ_DEPENDENCIES

APEX_USED_DB_OBJECTS

This lists each schema object that is used at least once in your application.

select
    referenced_type, referenced_owner,
    referenced_name, referenced_sub_name,
    usage_count
from apex_used_db_objects
where application_id = :app_id;
Table of REFERENCED_TYPE, REFERENCED_OWNER, REFERENCED_NAME, REFERENCED_SUB_NAME, and USAGE_COUNT.
Results include Columns, a Method, a Package, a Schema, and some Synonyms.

Note that “USAGE_COUNT” is the number of distinct component properties that refer to the schema object; if a single component (e.g. a Process) refers to an object multiple times, it will only count as one usage.

If your database package is compiled with PL/Scope enabled, the dependency analysis will also report fine-grained dependencies on the functions, procedures, and other components within the database package.

APEX_USED_DB_OBJECT_COMP_PROPS

This lists each component property in your application that references at least one schema object.

select
    page_id,
    component_type_name, component_display_name,
    property_group_name, property_name
from apex_used_db_object_comp_props
where application_id = :app_id;
Table of PAGE_ID, COMPONENT_TYPE_NAME, COMPONENT_DISPLAY_NAME, PROPERTY_GROUP_NAME, PROPERTY_NAME.
Results include various pages in an application with Regions, Processes, and a Series.

You can also include the column CODE_FRAGMENT to show the object name, SQL or PL/SQL that was analyzed.

If a component property cannot be analyzed due to a compile error (e.g. if an expected database object is missing) the same view will tell you what the compile error was, which may help you to determine what’s gone wrong.

select
    page_id,
    component_type_name, component_display_name,
    property_group_name, property_name,
    code_fragment, error_message
from apex_used_db_object_comp_props
where application_id = :app_id
and error_message is not null;

APEX_USED_DB_OBJ_DEPENDENCIES

This is the complete report showing for each component property, all the database objects it refers to.

select
    page_id,
    component_type_name, component_display_name,
    property_group_name, property_name,
    code_fragment,
    referenced_type, referenced_owner,
    referenced_name, referenced_sub_name
from apex_used_db_obj_dependencies
where application_id = :app_id;
Table of PAGE_ID, COMPONENT_TYPE_NAME, COMPONENT_DISPLAY_NAME, CODE_FRAGMENT, REFERENCED_TYPE, REFERENCED_OWNER, REFERENCED_NAME, REFERENCED_SUB_NAME.
Results include some Regions, an Item, some Validations, and a Process.
Results indicate dependencies on database Tables, a Synonym, some Packages, and a Method.
(some columns were removed from this screenshot)

Using the API

The results of a scan will be retained until the application is re-scanned. You can scan any number of applications in your workspace and analyze the results all together if you need. If an application is modified, you can re-scan it to refresh the report.

You may find it useful, so I encourage you to give it a try. If you do, please note a few caveats:

  • The documentation for this API is not yet available, but is being worked on. Documentation now available.
  • When APEX is upgraded to a new version, all report results are wiped. You can then re-scan your applications to get up-to-date results.
  • The reports do not include recursive dependencies – e.g. if your application refers to a view, the report will not list the underlying tables of the view.
  • If the application includes any plugins, the dependencies report will include references to some internal plugin-related APIs even if your code doesn’t directly reference them.
  • If your application executes any dynamic SQL or PL/SQL (e.g. using “execute immediate”), any dependencies arising from the dynamic code will not be reported.
  • There are some component properties that are not included in the scan, such as the column names in a report (however, the data source for the region is scanned). UPDATE: coverage has been greatly improved in APEX 24.2.

In spite of the caveats, I’m sure there are quite a few ways this new API will prove useful. We expect it will be further improved in future releases, including being integrated into the APEX Application Builder.


Export CLOB as a SQL Script #JoelKallmanDay

Quite often I will need to export some data from one system, such as system setup metadata, preferences, etc. that need to be included in a repository and imported when the application is installed elsewhere.

I might export the data in JSON or CSV or some other text format as a CLOB (character large object) variable. I then need to wrap this in suitable commands so that it will execute as a SQL script when installed in the target system. To do this I use a simple script that takes advantage of the APEX_STRING API to split the CLOB into chunks and generate a SQL script that will re-assemble those chunks back into a CLOB on the target database, then call a procedure that will process the data (e.g. it might parse the JSON and insert metadata into the target tables).

This will work even if the incoming CLOB has lines that exceed 32K in length, e.g. a JSON document that includes embedded image data encoded in base 64, or documents with multibyte characters.

This is clob_to_sql_script:

function clob_to_sql_script (
    p_clob           in varchar2,
    p_procedure_name in varchar2,
    p_chunk_size     in integer := 8191
) return clob is

-- Takes a CLOB, returns a SQL script that will call the given procedure
-- with that clob as its parameter.

    l_strings apex_t_varchar2;
    l_chunk   varchar2(32767);
    l_offset  integer;        

begin

    apex_string.push(
        l_strings,
        q'[
declare
l_strings apex_t_varchar2;
procedure p (p_string in varchar2) is
begin
    apex_string.push(l_strings, p_string);
end p;
begin
]');
    
    while apex_string.next_chunk (
        p_str    => p_clob,
        p_chunk  => l_chunk,
        p_offset => l_offset,
        p_amount => p_chunk_size )
    loop
        apex_string.push(
            l_strings,
            q'[p(q'~]'
            || l_chunk
            || q'[~');]');
    end loop;    

    apex_string.push(
        l_strings,
        replace(q'[
    #PROC#(apex_string.join_clob(l_strings));
end;
]',
            '#PROC#', p_procedure_name)
        || '/');

    return apex_string.join_clob(l_strings);
end clob_to_sql_script;

Note that the default chunk size is 8,191 characters which is the safe limit for multi-byte characters. You can choose a smaller chunk size if you want, although if the incoming CLOB is very large, the smaller the chunk size the bigger the expanded SQL script will be.

A simple test case will demonstrate what it will do:

declare
    l_input  clob;
    l_output clob;
begin
    l_input := q'[
{
    "data": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
}
]';
    l_output := clob_to_sql_script(
        p_clob           => l_input,
        p_procedure_name => 'mypackage.import',
        p_chunk_size     => 60 );
    dbms_output.put_line( l_output );
end;
/

The above script would output this:

declare
l_strings apex_t_varchar2;
procedure p (p_string in varchar2) is
begin
    apex_string.push(l_strings, p_string);
end p;
begin

p(q'~
{
    "data": "Lorem ipsum dolor sit amet, consectetur adip~');
p(q'~iscing elit, sed do eiusmod tempor incididunt ut labore et d~');
p(q'~olore magna aliqua. Ut enim ad minim veniam, quis nostrud ex~');
p(q'~ercitation ullamco laboris nisi ut aliquip ex ea commodo con~');
p(q'~sequat. Duis aute irure dolor in reprehenderit in voluptate ~');
p(q'~velit esse cillum dolore eu fugiat nulla pariatur. Excepteur~');
p(q'~ sint occaecat cupidatat non proident, sunt in culpa qui off~');
p(q'~icia deserunt mollit anim id est laborum."
}
~');

    mypackage.import(apex_string.join_clob(l_strings));
end;
/

The source can be downloaded from here: clob_to_sql_script.sql


Oracle’s Numbers

You are probably familiar with some of the data types supported by the Oracle Database for storing numeric values, but you might not be aware of the full range of types that it provides.

Some types (such as NUMBER, INTEGER) are provided for general use in SQL and PL/SQL, whereas others are only supported in PL/SQL (such as BINARY_INTEGER).

There are others (such as DECIMAL, REAL) that are provided to adhere to the SQL standard and for greater interoperability with other databases that expect these types.

Most of the numeric data types are designed for storing decimal numbers without loss of precision; whereas the binary data types (e.g. BINARY_FLOAT, BINARY_DOUBLE) are provided to conform to the IEEE754 standard for binary floating-point arithmetic. These binary types cannot store all decimal numbers exactly, but they do support some special values like “infinity” and “NaN”.

In PL/SQL you can define your own subtypes that further constrain the values that may be assigned to them, e.g. by specifying the minimum and maximum range of values, and/or by specifying that variables must be Not Null.

What do I prefer?

In my data models, I will usually use NUMBER to store numeric values, e.g. for quantities and measurements; for counts and IDs (e.g. for surrogate keys) I would use INTEGER (with the exception of IDs generated using sys_guid, these must use NUMBER).

In PL/SQL, if I need an index for an array, I will use BINARY_INTEGER (although if I’m maintaining a codebase that already uses its synonym PLS_INTEGER, I would use that for consistency). In other cases I will use INTEGER or NUMBER depending on whether I need to store integers or non-integers.

I don’t remember any occasion where I’ve needed to use FLOAT, or the binary types; and of the subtypes of BINARY_INTEGER, I’ve only used SIGNTYPE maybe once or twice. Of course, there’s nothing wrong with these types, it’s just that I haven’t encountered the need for them (yet).

What about Performance?

There are some differences in performance between these data types, but most of the time this difference will not be significant compared to other work your code is doing – see, for example, Connor on Choosing the Best Data Type. Choosing a data type that doesn’t use more storage than is required for your purpose can make a difference when the volume of data is large and when large sets of record are being processed and transmitted.

Reference Chart: Numeric Data Types

This diagram shows all the numeric data types supplied by Oracle SQL and PL/SQL, and how they relate to each other:

This work is licensed under a Creative Commons Attribution 4.0 International License.
PDF version

Storing BIG Integers

From smallest to largest – the maximum finite integer that can be stored by these data types is listed here. It’s interesting to see that BINARY_FLOAT can store bigger integers than INTEGER, but NUMBER can beat both of them:

BINARY_INTEGER2.147483647 x 109
INTEGER9.9999999999999999999999999999999999999 x 1037
BINARY_FLOAT3.40282347 x 1038
NUMBER9.999999999999999999999999999999999999999 x 10125
BINARY_DOUBLE1.7976931348623157 x 10308

To put that into perspective:

Storing SMALL Numbers

The smallest non-zero numeric value (excluding subnormal numbers) that can be stored by these data types is listed here.

BINARY_FLOAT1.17549435 x 10-38
NUMBER1.0 x 10-130
BINARY_DOUBLE2.2250738585072014 x 10-308

These are VERY small quantities. For example:

  • The size of a Quark, the smallest known particle, is less than 10-19 metres and can easily be represented by any of these types.
  • You can store numbers as small as the Planck Length (1.616 × 10-35 metres) in a BINARY_FLOAT.
  • But to store a number like the Planck Time (5.4 × 10-44 seconds), you need a NUMBER – unless you change the units to nanoseconds, in which case it can also be stored in a BINARY_FLOAT.
  • I’m not aware of any specifically named numbers so small that they require a BINARY_DOUBLE; however, there are certainly use cases (e.g. scientific measurements) that need the kind of precision that this type provides.

Further Reading


Pretty Print JSON in PL/SQL

I have been working with some code that uses JSON, sometimes fairly large documents of the stuff, and it’s often necessary to send this to the debug log (e.g. DBMS_OUTPUT) for debugging; however, the builtin functions that convert a JSON object to a string (or clob) return the JSON document in one big long line, like this:

{"surname":"Jones","name":"Bob","age":42,"alive":true,"children":[{"name":"Sally","age":10},{"name":"Terrance","age":8},{"name":"Ulyses","age":6}]}

To show this formatted, I added the following function using JSON_SERIALIZE with the “PRETTY” option, to my utility package:

function format_json (p_clob in clob) return clob is
    l_clob clob;
begin
    select JSON_SERIALIZE(p_clob returning clob PRETTY) into l_clob from dual;
    return l_clob;
end format_json;

Note that my function takes a CLOB, not a JSON object, because sometimes I receive the data already as a CLOB and I don’t want to require conversion to JSON before passing it to my formatting function.

Now, when I call this function:

declare
    l_json     json_object_t := json_object_t();
    l_children json_array_t := json_array_t();
    l_clob     clob;
begin
    l_json.put('surname','Jones');
    l_json.put('name','Bob');
    l_json.put('age',42);
    l_json.put('alive',true);
    l_children.append(json_object_t('{"name":"Sally","age":10}'));
    l_children.append(json_object_t('{"name":"Terrance","age":8}'));
    l_children.append(json_object_t('{"name":"Ulyses","age":6}'));
    l_json.put('children',l_children);
    l_clob := l_json.to_clob;
    l_clob := utility_pkg.format_json(l_clob);
end;

I get the following result:

{
  "surname" : "Jones",
  "name" : "Bob",
  "age" : 42,
  "alive" : true,
  "children" :
  [
    {
      "name" : "Sally",
      "age" : 10
    },
    {
      "name" : "Terrance",
      "age" : 8
    },
    {
      "name" : "Ulyses",
      "age" : 6
    }
  ]
}

EDIT 28/10/2025: the initial version of this article included code that would convert the clob to a blob to pass to the json_serialize function. I don’t recall why I did this, assuming it might have been a workaround for a bug in an early version of 19c I might have encountered when passing a clob directly.
In my testing it seems to work find on current versions of the database so I’ve removed the unnecessary conversion.


Some collection methods I’d like to see added to PL/SQL

In building a code generator I found the need to write a number of helper methods for doing basic modifications of arrays that are indexed by integer – such as appending one array onto another, inserting, and shifting. These arrays represent an ordered sequence of strings (e.g. lines of source code).

I think these would be a useful addition to the language if they were made native – e.g. (new commands in UPPERCASE):

declare
    type str_array_type is table of varchar2(32767)
        index by binary_integer;
    l_lines str_array_type;
    l_new str_array_type;
    l_idx binary_integer;
begin
    .. (some code to fill the arrays here) ..

    -- get a subset of lines
    l_new := l_lines.SLICE(50, 59);

    -- extend l_lines with l_new at the end:
    l_lines.APPEND(l_new);

    -- shift l_lines forwards and insert l_new
    -- at the beginning:
    l_lines.PREPEND(l_new);

    -- insert l_new into l_lines at the given index;
    -- shift any existing lines at that location
    -- forward:
    l_lines.INSERT(l_new, at_idx => 21);

    -- remove the given range of indices from
    -- l_lines, replace with whatever is in l_new:
    l_lines.UPDATE(l_new,
        from_idx => 120,
        to_idx   => 149);

    -- apply the given substitution on each line
    l_lines.REPLACE_ALL(
        old_val => 'foo',
        new_val => 'bar');

    -- shift the given range of lines by the given
    -- offset (raise exception if existing data
    -- would get overwritten):
    l_lines.SHIFT(
        from_idx => 20,
        to_idx   => 29,
        offset   => 1000);

    -- shift and renumber all indices in the array
    -- with the given starting index and increment:
    l_lines.RENUMBER(start_idx => 10, increment => 10);

    -- make the array contiguous (i.e. remove gaps):
    l_lines.RENUMBER;

    -- loop over every line in the array that contains
    -- the given string:
    l_idx := l_lines.FIND_NEXT(contains => 'hello');
    loop
        exit when l_idx is null;
        .. do something with l_lines(l_idx) ..
        l_idx := l_lines.FIND_NEXT(contains => 'hello',
            from_idx => l_idx);
    end loop;
end;

I’ve illustrated these with a little sample package that may be viewed here:

https://github.com/jeffreykemp/sample/tree/master/str_array_pkg

What do you think?


Short circuit evaluation and the great Unknown

One of the nice things about PL/SQL is that it implements short circuit evaluation, a performance enhancement which takes advantage of the fact that an expression using logical AND or OR does not necessarily to evaluate both operands to determine the overall result.

For an expression using AND, if the first operand is not TRUE, the overall expression cannot be TRUE; for one using OR, if the first operand is TRUE, the overall expression must be TRUE. In the case of AND, what if the first operand is Unknown? It seems to depend on how the expression is used.

In my examples below, I have an expression that looks up an array. When an array is accessed with a key that is null, it will raise an exception. If short circuit evaluation is applied, the array is never accessed so the exception is not raised.

In the first example below, the PL/SQL engine never evaluates the second expression since the first expression ('abc' = p_param) is not TRUE:

declare
    p_param varchar2(10);
    l_result boolean := false;
    l_arr apex_t_varchar2;
begin
    if 'abc' = p_param and l_arr(p_param) = 'bla' then
        l_result := true;
    end if;
end;

This does not apply if the expression is being assigned to a variable. In the second example below, the exception ORA-06502: PL/SQL: numeric or value error: NULL index table key value is raised:

declare
    p_param varchar2(10);
    l_result boolean;
    l_arr apex_t_varchar2;
begin
    l_result := 'abc' = p_param and l_arr(p_param) = 'bla';
end;

If the first expression were to result in FALSE, it runs without error. If the first expression is Unknown (NULL), the second operand must be evaluated to determine whether to assign FALSE or NULL to the result.

A workaround is to use an IF statement to make the evaluation order explicit:

declare
    p_param varchar2(10);
    l_result boolean := false;
    l_arr apex_t_varchar2;
begin
    if 'abc' = p_param then
        l_result := l_arr(p_param) = 'bla';
    end if;
end;

Thanks to Connor for clearing up my understanding for this one.

8/10/2020 updated with better example code – instead of comparing to a literal null (which is never right), we compare to a variable which may or may not be null at runtime.


DBMS_MVIEW.explain_mview with no MV_CAPABILITIES_TABLE

Need to run DBMS_MVIEW.explain_mview in APEX SQL Workshop, but don’t have the MV_CAPABILITIES_TABLE? You’ll get this error:

ORA-30377: table ORDS_PUBLIC_USER.MV_CAPABILITIES_TABLE not found

You don’t need to create this table. You could create this table by running admin/utlxmv.sql (if you have it). Instead, you can get the output in an array and do whatever you want with its contents, e.g.:

declare
    a sys.ExplainMVArrayType;
begin
    dbms_mview.explain_mview('MY_MV',a);
    dbms_output.put_line('Explain MV '
        || a(1).mvowner || '.' || a(1).mvname);
    for i in 1..a.count loop
        dbms_output.put_line(
            rpad(a(i).capability_name, 30)
            || ' [' || case a(i).possible
                       when 'T' then 'TRUE'
                       when 'F' then 'FALSE'
                       else a(i).possible
                       end || ']'
            || case when a(i).related_num != 0 then
                   ' ' || a(i).related_text
                   || ' (' || a(i).related_num || ')'
               end
            || case when a(i).msgno != 0 then
                   ' ' || a(i).msgtxt
                   || ' (' || a(i).msgno || ')'
               end
        );
    end loop;
end;

The result will be something like this:

Now, the challenge is merely how to resolve some of those “FALSEs” …


Send SMS, MMS and Voice messages from Oracle PL/SQL

testing receipt of sms and mms

If you need to send almost any message to almost any phone from your Oracle database, and you want to use straight PL/SQL, you may want to consider using my Clicksend API.

  • SMS (Short Message Service)
  • MMS (Multimedia Message Service)
  • Text to Voice

I have released the first beta version of my Oracle PL/SQL API for Clicksend. Read the installation instructions, API reference and download the release from here:

http://jeffreykemp.github.io/clicksend-plsql-api/

Sending an SMS is as simple as adding this anywhere in your code:

begin
  clicksend_pkg.send_sms
    (p_sender  => 'TheDatabase'
    ,p_mobile  => '+61411111111'
    ,p_message => 'G''day, this is your database!'
    );
  clicksend_pkg.push_queue;
  commit;
end;

All you need to do is signup for a Clicksend account. You’ll only be charged for messages actually sent, but they do require you to pay in advance – e.g. $20 gets you about 300 messages (Australian numbers). You can get test settings so that you can try it out for free.

I’ve been using Clicksend for years now, and have been satisfied with their service and the speed and reliability of getting messages to people’s mobiles. When I encountered any issues, a chat with their support quickly resolved them, and they were quick to offer free credits when things weren’t working out as expected.

If you want to send a photo to someone’s phone via MMS (although I’m not sure what the use-case for this might be), you need to first upload the image somewhere online, because the API only accepts a URL. In my case, I would use the Amazon S3 API from the Alexandria PL/SQL Library, then pass the generated URL to the clicksend API. There is a file upload feature that ClickSend provides, I plan to add an API call to take advantage of this which will make this seamless – and provide some file conversion capabilities as well.

begin
  clicksend_pkg.send_mms
    (p_sender  => 'TheDatabase'
    ,p_mobile  => '+61411111111'
    ,p_subject => 'G''Day!'
    ,p_message => 'This is an MMS from your database!'
    ,p_media_file_url =>
'http://s3-ap-southeast-2.amazonaws.com/jk64/jk64logo.jpg'
    );
  clicksend_pkg.push_queue;
  commit;
end;

You can send a voice message to someone (e.g. if they don’t have a mobile phone) using the Text to Voice API.

begin
  clicksend_pkg.send_voice
    (p_phone_no     => '+61411111111'
    ,p_message      => 'Hello. This message was sent from your database. '
                    || 'Have a nice day.'
    ,p_voice_lang   => 'en-gb' -- British English
    ,p_voice_gender => 'male'
    ,p_schedule_dt  => sysdate + interval '2' minute
    );
  clicksend_pkg.push_queue;
  commit;
end;

You have to tell the API what language the message is in. For a number of languages, you can specify the accent/dialect (e.g. American English, British English, or Aussie) and gender (male or female). You can see the full list here.

All calls to the send_sms, send_mms and send_voice procedures use Oracle AQ to make the messages transactional. It’s up to you to either COMMIT or ROLLBACK, which determines whether the message is actually sent or not. All messages go into a single queue.

You can have a message be scheduled at a particular point in time by setting the p_schedule_dt parameter.

The default installation creates a job that runs every 5 minutes to push the queue. You can also call push_queue directly in your code after calling a send_xxx procedure. This creates a job to push the queue as well, so it won’t interfere with your transaction.

All messages get logged in a table, clicksend_msg_log. The log includes a column clicksend_cost which allows you to monitor your costs. To check your account balance, call get_credit_balance.

Please try it out if you can and let me know of any issues or suggestions for improvement.

Link: http://jeffreykemp.github.io/clicksend-plsql-api/