Infrastructure at your Service

Daniel Westermann

Can I do it with PostgreSQL? – 2 – Dual

In the first post of this series we talked about restore points. Another question that pops up from time to time is how you can do things in PostgreSQL that would require the dual table in Oracle. Lets go …

The question is: When do you need the dual table in Oracle? Well, everything time you have nothing to select from, meaning no table you could provide in the from clause and you need exactly one row. This could be the case when you want to do math:

SQL> select 1+2+3*4/2 from dual;

 1+2+3*4/2
----------
	 9

This can be the case when you want to generate test data:

SQL> select 'a' from dual connect by level <= 5;

'
-
a
a
a
a
a

This can be the case when you want to select from a PL/SQL function, such as:

SQL> create table ta (a number);

Table created.

SQL> select dbms_metadata.get_ddl('TABLE','TA',USER) from dual;

DBMS_METADATA.GET_DDL('TABLE','TA',USER)
--------------------------------------------------------------------------------

  CREATE TABLE "SYS"."TA"
   (	"A" NUMBER
   ) PCTFREE 10 PCTUSED 40 INITRANS

… any many more.

The easy answer to the question if you can do it in PostgreSQL is: You don’t need to. Why? Because you can do things like this:

([email protected][local]:5439) [postgres] > select 'Time for a beer';
    ?column?     
-----------------
 Time for a beer
(1 row)

… or this:

([email protected][local]:5439) [postgres] > select 1+2+3*4/2;
 ?column? 
----------
        9
(1 row)

The same is true for getting the results of a function:

([email protected][local]:5439) [postgres] > create function f1 (integer,integer) returns integer
as 'select $1 * $2;'
language sql;
CREATE FUNCTION
Time: 249.499 ms
([email protected][local]:5439) [postgres] > select f1(5,5);
 f1 
----
 25
(1 row)

PostgreSQL does not force you to provide a table to select from. You can completely skip this. Looks strange when you are used to work with Oracle, I know, but hey: This is much more easy: Why provide a from clause when it is not necessary?

If you really, really can’t live without dual:

([email protected][local]:5439) [postgres] > create table dual (dummy varchar(1));
CREATE TABLE
([email protected][local]:5439) [postgres] > insert into dual (dummy) values ('a');
INSERT 0 1
([email protected][local]:5439) [postgres] > select 'I can not live without dual' from dual;
          ?column?           
-----------------------------
 I can not live without dual
(1 row)
([email protected][local]:5439) [postgres] > select 1+2+3*4/2 from dual;
 ?column? 
----------
        9
(1 row)

And here you go …

Leave a Reply

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

Daniel Westermann
Daniel Westermann

Principal Consultant & Technology Leader Open Infrastructure