4

I'm having trouble understanding the following example from the PostgreSQL documentation:

-- set returning function WITH ORDINALITY
SELECT * FROM pg_ls_dir('.') WITH ORDINALITY AS t(ls,n);
       ls        | n
-----------------+----
 pg_serial       |  1
 pg_twophase     |  2
 postmaster.opts |  3
 pg_notify       |  4
...

The things inside the parentheses of the t(...) become the column names, but what is the t itself? I'm asking here because the docs don't explain it, and a single-letter function is ungoogleable. In fact, the docs don't even explain what is supposed to come after AS; the only thing we get is this one example.

It seems I can replace t by any other identifier, and it still works.

Thomas
  • 174,939
  • 50
  • 355
  • 478

2 Answers2

4

The syntax you're looking for is:

function_call [WITH ORDINALITY] [[AS] table_alias [(column_alias [, ... ])]]

https://www.postgresql.org/docs/10/static/queries-table-expressions.html#QUERIES-TABLEFUNCTIONS

t is an arbitrary table alias; you can give it any valid name you want.

Community
  • 1
  • 1
deceze
  • 510,633
  • 85
  • 743
  • 889
1

it's alias for a set, to be able to reference it in column list, eg:

SELECT t.*,pg_database .datname 
FROM pg_ls_dir('.') WITH ORDINALITY AS t(ls,n) 
join pg_database on true where datname = 'postgres'
          ls          | n  | datname
----------------------+----+----------
 pg_dynshmem          |  1 | postgres
 postmaster.pid       |  2 | postgres
 PG_VERSION           |  3 | postgres
 base                 |  4 | postgres
Vao Tsun
  • 47,234
  • 13
  • 100
  • 132