Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

237
Vistas
How to use variable in view definition in Postgres/plpgsql

I am using plpgsql with Postgres 10.6. I have a function that declares and gives value to a variable. That function also defines a view, and I would like to use the variable within the definition.

  create view myview as
    select
      some_columns
    from
      mytable
    where      
      id = _id     /*_id is declared earlier in function */
  ;

In this case, the function can be defined, but when it is run it gives an error: UndefinedColumn: column "_id" does not exist

Is such a thing possible in Postgres? Can views include variables as part of their definition?

I do see here that in BigQuery (which I have never used), what I am asking is not possible, which makes me think it may also not be possible in plpgsql.

It is not a big deal, but I am curious. A workaround - and probably the recommended solution - is to pass the _id when I select from the view (e.g. select * from myview where id = 3). Or, if I really want to keep the select call simple (which I do, because my actual implementation is more complicated and has multiple variables), I could define the view as a string and use execute within the function (this is all internal stuff used in building up and creating a db, not in a situation where the various risks inherent to dynamic sql are a concern).

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

No, you can not pass a variable to a view. But you can do this with a function:

create function my_view_function(p_id integer)
  returns table (id int, column_1 int, column2 text)
as
$$
  select id, column_1, column_2
  from my_table
  where id = p_id;
$$
language sql
stable;

Then use it like this

select *
from my_view_function(42);
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda