Skip to main content

Different SYSDATE behaviors in SQL and PL/SQL



The SYSDATE function is available in both SQL and PL/SQL. They both return the current date-time (down to nearest second) for the database, So it would be reasonable to assume that they "act" the same in both SQL statements and PL/SQL blocks.

That would, however, be a bad assumption to make, because in reality:

In SQL, SYSDATE is called just once for the entire statement.

In PL/SQL, SYSDATE is called every time it is invoked.

Wow. Mind blown. 

Let's take a look.

In the script below, I create a table and insert four rows. Then I create a package that keeps track of distinct dates added to a collection and show those dates. Finally, a function that uses the package.

CREATE TABLE tab (id INT)
/

BEGIN
   INSERT INTO tab VALUES (1);
   INSERT INTO tab VALUES (2);
   INSERT INTO tab VALUES (3);
   INSERT INTO tab VALUES (4);
   COMMIT;
END;
/

CREATE OR REPLACE PACKAGE tracker
   AUTHID DEFINER
IS
   TYPE when_t IS TABLE OF INTEGER INDEX BY VARCHAR2 (100);

   dates   when_t;

   PROCEDURE add_date (date_in IN DATE);

   FUNCTION store_and_return_date (date_in            IN DATE,
                                   call_in_plsql_in   IN VARCHAR2)
      RETURN DATE;

   PROCEDURE show_count;
END;
/

CREATE OR REPLACE PACKAGE BODY tracker
IS
   PROCEDURE add_date (date_in IN DATE)
   IS
   BEGIN
      dates (TO_CHAR (date_in, 'YYYY-MM-DD HH:MI:SS')) := 0;
   END;

   PROCEDURE show_count
   IS
      l_index   VARCHAR2 (100) := dates.FIRST;
   BEGIN
      DBMS_OUTPUT.put_line ('Date Count = ' || dates.COUNT);

      WHILE l_index IS NOT NULL
      LOOP
         DBMS_OUTPUT.put_line (l_index);
         l_index := dates.NEXT (l_index);
      END LOOP;

      dates.delete;
   END;

   FUNCTION store_and_return_date (date_in            IN DATE,
                                   call_in_plsql_in   IN VARCHAR2)
      RETURN DATE
   IS
      d   DATE;
   BEGIN
      /* This is the value for SYSDATE passed in from The SELECT */
      add_date (date_in); 

      IF call_in_plsql_in = 'YES'
      THEN
         /* Now we call SYSDATE inside PL/SQL. Will it be the same
            value as passed in for date_in, or different? The
            count in the collection will tell us */
         add_date (SYSDATE);
      END IF;

      DBMS_SESSION.sleep (1);

      RETURN date_in;
   END;
END;
/
When I call the store_and_return_date, I can specify whether or not I want SYSDATE to be called again from within the PL/SQL function - which will be invoked below inside a SELECT statement.

Notice that I use the date (converted explicitly to a string) as the index in the associative array. That makes it easy to keep track of unique timestamps added.

In the first query below, I do not call SYSDATE inside PL/SQL, only in the call to the function, which happens inside the SQL engine.

In the second query, I call SYDATE in PL/SQL in addition to the invocation in the SELECT statement.
SELECT tracker.store_and_return_date (
          SYSDATE, call_in_plsql_in => 'NO') 
  FROM tab
/

BEGIN
   tracker.show_count;
END;
/

SELECT tracker.store_and_return_date (
          SYSDATE, call_in_plsql_in => 'YES') 
  FROM tab
/

BEGIN
   tracker.show_count;
END;
/
And here's the output:
Date Count = 1
2020-09-29 01:28:58

Date Count = 4
2020-09-29 01:29:02
2020-09-29 01:29:03
2020-09-29 01:29:04
2020-09-29 01:29:05

And there you see the difference between SQL and PL/SQL engines when it comes to executing SYSDATE. There are four rows in the TAB table. But the value for SYSDATE when executed in SQL doesn't change for the duration of the query, so there is just one element in the array.

When I ask for SYSDATE to also be called in PL/SQL, it is executed and the current date-time returned - even when that function is called from within a SQL statement.

Comments

  1. Why do we have count as 4? Ideally, there is just 2 time insertion into the collection, correct?

    ReplyDelete
  2. The function is called four times. So SYSDATE is executed once in SQL and then four more times inside the PL/SQL function. With the one second delay inside the function, we are (fairly) certain that SYSDATE will return four different date-times, so there are four unique strings used as index values in the collection.

    Does that clear things up?

    ReplyDelete
    Replies
    1. I am caught in the trap here, it is still unclear to me. Sorry, I started to feel silly. When I executed in Toad it returned Count=4. But still when I read it, I don't get it how it returned 4. Can you elaborate it or can you make an other post on this please.

      In the function: store_and_return_date

      --#1. First call to insert into the Collection: dates with parameter's SYSDATE
      add_date (date_in);


      IF call_in_plsql_in = 'YES'
      THEN
      --#2.Second call to insert into the Collection: dates, with SYSDATE current
      add_date (SYSDATE);
      END IF;

      Since the table: tab has got 4 rows, what impact does it make while calling functions with parameter (call_in_plsql_in=YES/NO).

      Delete
    2. I use the parameter call_in_plsql_in to determine if SYSDATE should also be called inside the PL/SQL function. If NO, it is only called in the SQL statement, and we see that it is only actually executed once, since the value passed into the function and used as an index never changes (so the count in the collection is just 1).

      When I pass YES for this parameter, SYSDATE is also called inside the PL/SQL function. The collection then ends up with > 1 element in it, because SYSDATE is actually executed each time (with a second's delay in between).

      This demonstrates the point of the post:

      In a SQL statement, SYSDATE is executed just once and its value is used for the duration of the execution of that statement, no matter how many times SYSDATE is actually "encountered" in the processing of that statement.

      In a PL/SQL block, SYSDATE is execute every single time the PL/SQL runtime engine runs across it.

      Please don't hesitate to follow up if you need more clarification! This is tricky stuff.....

      Delete
    3. Thankyou Steven, this helps a lot. I was just lost in the call. Modifying function would explain when it would take 5 Rows into the Collection: dates. Much appreciate your posts. I'm a big fan.

      FUNCTION store_and_return_date (date_in IN DATE,
      call_in_plsql_in IN VARCHAR2)
      RETURN DATE
      IS
      d DATE;
      BEGIN
      add_date (date_in); --First call to insert into the Collection: dates with parameter's SYSDATE

      --DBMS_SESSION.sleep (1);
      DBMS_LOCK.SLEEP (1);

      IF call_in_plsql_in = 'YES'
      THEN
      add_date (SYSDATE); --Second call to insert into the Collection: dates, with SYSDATE current
      END IF;

      --DBMS_SESSION.sleep (1);
      DBMS_LOCK.SLEEP (1);

      RETURN date_in;
      END;

      Delete
    4. Great idea. I have added comments to the code.

      Delete

Post a Comment

Popular posts from this blog

Get rid of mutating table trigger errors with the compound trigger

When something mutates, it is changing. Something that is changing is hard to analyze and to quantify. A mutating table error (ORA-04091) occurs when a row-level trigger tries to examine or change a table that is already undergoing change (via an INSERT, UPDATE, or DELETE statement). In particular, this error occurs when a row-level trigger attempts to read or write the table from which the trigger was fired. Fortunately, the same restriction does not apply in statement-level triggers.

In this post, I demonstrate the kind of scenario that will result in an ORA-04091 errors. I then show the "traditional" solution, using a collection defined in a package. Then I demonstrate how to use the compound trigger, added in Oracle Database 11g Release1,  to solve the problem much more simply.

All the code shown in this example may be found in this LiveSQL script.
How to Get a Mutating Table ErrorI need to implement this rule on my employees table:
Your new salary cannot be more than 25x th…

How to Pick the Limit for BULK COLLECT

This question rolled into my In Box today:
In the case of using the LIMIT clause of BULK COLLECT, how do we decide what value to use for the limit? First I give the quick answer, then I provide support for that answer

Quick Answer
Start with 100. That's the default (and only) setting for cursor FOR loop optimizations. It offers a sweet spot of improved performance over row-by-row and not-too-much PGA memory consumption.Test to see if that's fast enough (likely will be for many cases).If not, try higher values until you reach the performance level you need - and you are not consuming too much PGA memory. Don't hard-code the limit value: make it a parameter to your subprogram or a constant in a package specification.Don't put anything in the collection you don't need. [from Giulio Dottorini]Remember: each session that runs this code will use that amount of memory.Background

When you use BULK COLLECT, you retrieve more than row with each fetch, reducing context switchi…

Quick Guide to User-Defined Types in Oracle PL/SQL

A Twitter follower recently asked for more information on user-defined types in the PL/SQL language, and I figured the best way to answer is to offer up this blog post.

PL/SQL is a strongly-typed language. Before you can work with a variable or constant, it must be declared with a type (yes, PL/SQL also supports lots of implicit conversions from one type to another, but still, everything must be declared with a type).

PL/SQL offers a wide array of pre-defined data types, both in the language natively (such as VARCHAR2, PLS_INTEGER, BOOLEAN, etc.) and in a variety of supplied packages (e.g., the NUMBER_TABLE collection type in the DBMS_SQL package).

Data types in PL/SQL can be scalars, such as strings and numbers, or composite (consisting of one or more scalars), such as record types, collection types and object types.

You can't really declare your own "user-defined" scalars, though you can define subtypes from those scalars, which can be very helpful from the perspective…