sqloracle-databasecommon-table-expression

Will the CTE reflect changes in the data?


Lets say you create a CTE in Oracle, then manipulate some of the data in the tables its pulling from. Once you select the values from the CTE will the values changed be reflected in the result set? I guess a better question is when does the select statement inside the CTE run? Is it immediately or when you select from the CTE? Here's an example of what I mean.

WITH TEMP AS (
   select
      ,first_name
      ,last_name
      ,birthday
   from table
)

insert into table (first_name, last_name, birthday)
   values('Jess', 'Smith', '1999-01-01')

select * from TEMP

In this example will the CTE "TEMP" have the newly inserted person?


Solution

  • A CTE is an ad-hoc view and always part of a query. The syntax would be

    WITH temp AS (SELECT first_name, last_name, birthday FROM t)
    SELECT * FROM temp;
    

    You cannot write WITH temp AS (select first_name, last_name, birthday FROM t) and not add a query like SELECT * FROM temp.

    If you want a separate view, then you must create a view with

    CREATE VIEW temp AS 
      SELECT first_name, last_name, birthday FROM t;
    

    instead.

    As to this view: yes, it will show the current data. If you insert something into the table, the view will show that data. It is always up-to-date.

    Demo: https://dbfiddle.uk/ucm-2FuT