4

Is there some kind of priority ranks assigned to CTE and table name ? For instance, if I have a table called table_a in the public schema, and I create a CTE table named table_a using WITH, which table will be taken if I use table_a in the SELECT query ?

--as an example
CREATE TABLE table_a (
 id serial
);
WITH table_a AS (
 SELECT id
 FROM another_table
 )
SELECT *
FROM table_a --> which table is this ?
;
ypercubeTM
99.7k13 gold badges217 silver badges306 bronze badges
asked Apr 16, 2018 at 16:07
3
  • I think it evaluates CTE's first, before going out and searching for database tables/views - likely a question for stackoverflow, etc., though... Commented Apr 16, 2018 at 16:09
  • 2
    @DPSSpatial we exist too. ;) Commented Apr 16, 2018 at 16:43
  • 1
    @EvanCarroll who...? Commented Apr 16, 2018 at 17:13

1 Answer 1

2

PostgreSQL searches the CTE namespace with scanNameSpaceForCTE as the very first thing it does in searchRangeTableForRel

if (!relation->schemaname)
{
 cte = scanNameSpaceForCTE(pstate, refname, &ctelevelsup);
 if (!cte)
 isenr = scanNameSpaceForENR(pstate, refname);
}

If there is no schema

  1. check for a CTE
  2. check for a "Ephemeral Named Relation"

This is similar to Variable Shadowing if there is no namespace, and what the spec otherwise demands.

Everything in PostgreSQL has a namespace, if you want to address the table as compared to the CTE, consider providing (qualifying) the namespace.

CREATE TABLE foo AS VALUES (0);
WITH foo AS ( VALUES (1) )
SELECT *
FROM ( VALUES (2) ) AS foo -- inline virtual-table
UNION TABLE foo -- CTE
UNION TABLE public.foo; -- explicitly qualified the namespace;
answered Apr 16, 2018 at 16:41

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.