Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass In "WHERE" parameters to PostgreSQL View?

I have a rather complicated query on my PostgreSQL database spanning 4 tables via a series of nested subqueries. However, despite the slightly tricky looking appearance and setup, ultimately it will return two columns (from the same table, if that helps the situation) based on that matching of two external parameters (two strings need to match with fields in different tables). I'm fairly new to database design in PostgreSQL, so I know that this seemingly magical thing called Views exist, and that seems like it could help me here, but perhaps not.

Is there some way I can move my complex query inside a view and somehow just pass it the two values I need to match? That would greatly simplify my code on the front-end (by shifting the complexities to the database structure). I can create a view that wraps my static example query, and that works just fine, however that only works for one pair of string values. I need to be able to use it with a variety of different values.

Thus my question is: is it possible to pass parameters into an otherwise static View and have it become "dynamic"? Or perhaps a View is not the right way to approach it. If there's something else that would work better, I'm all ears!

*Edit: * As requested in comments, here's my query as it stands now:

SELECT   param_label, param_graphics_label   FROM   parameters  WHERE   param_id IN           (SELECT param_id              FROM parameter_links            WHERE region_id =                   (SELECT region_id                     FROM regions                    WHERE region_label = '%PARAMETER 1%' AND model_id =                          (SELECT model_id FROM models WHERE model_label = '%PARAMETER 2%')                  )          ) AND active = 'TRUE' ORDER BY param_graphics_label; 

Parameters are set off by percent symbols above.

like image 486
Devin Avatar asked Jul 09 '12 19:07

Devin


People also ask

Can you pass parameters to a view?

No, in SQL Server, we cannot pass parameters to a view. And it can be considered as one main limitation of using a view in SQL Server. Moreover, even if we try to pass parameters to a view, the SQL Server will return an error.

How do you pass parameters in PostgreSQL query?

The get_sum() function accepts two parameters: a, and b, and returns a numeric. The data types of the two parameters are NUMERIC. By default, the parameter's type of any parameter in PostgreSQL is IN parameter. You can pass the IN parameters to the function but you cannot get them back as a part of the result.

Can we pass parameter in SQL view?

You cannot pass parameters to SQL Server views.

How do you call a view in PostgreSQL?

Creating PostgreSQL Views Here is the syntax for this statement: CREATE [OR REPLACE] VIEW view-name AS SELECT column(s) FROM table(s) [WHERE condition(s)]; The OR REPLACE parameter will replace the view if it already exists.


2 Answers

You could use a set returning function:

create or replace function label_params(parm1 text, parm2 text)   returns table (param_label text, param_graphics_label text) as $body$   select ...   WHERE region_label = $1       AND model_id = (SELECT model_id FROM models WHERE model_label = $2)   .... $body$ language sql; 

Then you can do:

select * from label_params('foo', 'bar') 

Btw: are you sure you want:

AND model_id = (SELECT model_id FROM models WHERE model_label = $2) 

if model_label is not unique (or the primary key) then this will throw an error eventually. You probably want:

AND model_id IN (SELECT model_id FROM models WHERE model_label = $2) 
like image 125
a_horse_with_no_name Avatar answered Sep 20 '22 09:09

a_horse_with_no_name


In addition to what @a_horse already cleared up, you could simplify your SQL by using JOIN syntax instead of nested subqueries. Performance will be similar, but the syntax is much shorter and easier to manage.

CREATE OR REPLACE FUNCTION param_labels(_region_label text, _model_label text)   RETURNS TABLE (param_label text, param_graphics_label text) AS $func$     SELECT p.param_label, p.param_graphics_label     FROM   parameters      p      JOIN   parameter_links l USING (param_id)     JOIN   regions         r USING (region_id)     JOIN   models          m USING (model_id)     WHERE  p.active     AND    r.region_label = $1      AND    m.model_label = $2     ORDER  BY p.param_graphics_label; $func$ LANGUAGE sql; 
  • If model_label is not unique or something else in the query produces duplicate rows, you may want to make that SELECT DISTINCT p.param_graphics_label, p.param_label - with a matching ORDER BY clause for best performance. Or use a GROUP BY clause.

  • Since Postgres 9.2 you can use the declared parameter names in place of $1 and $2 in SQL functions. (Has been possible for PL/pgSQL functions for a long time).

  • Care must be taken to avoid naming conflicts. That's why I make it a habit to prefix parameter names in the declaration (those are visible most everywhere inside the function) and table-qualify column names in the body.

  • I simplified WHERE p.active = 'TRUE' to WHERE p.active, because the column active should most probably be of type boolean, not text.

  • USING only works if the column names are unambiguous across all tables to the left of the JOIN. Else you have to use the more explicit syntax:
    ON l.param_id = p.param_id

like image 44
Erwin Brandstetter Avatar answered Sep 22 '22 09:09

Erwin Brandstetter