Using function in subquery in where statement : WHERE « Select Query « PostgreSQL






Using function in subquery in where statement


postgres=# CREATE TABLE myTable (
postgres(#          id int,
postgres(#          sid int,
postgres(#          name text);
CREATE TABLE
postgres=#
postgres=# insert into myTable values(1,2,'a');
INSERT 0 1
postgres=# insert into myTable values(2,3,'b');
INSERT 0 1
postgres=#
postgres=# select * from myTable;
 id | sid | name
----+-----+------
  1 |   2 | a
  2 |   3 | b
(2 rows)

postgres=#
postgres=#
postgres=# CREATE FUNCTION getData(int) RETURNS SETOF myTable AS $$
postgres$#    SELECT * FROM myTable WHERE id = $1;
postgres$# $$ LANGUAGE SQL;
CREATE FUNCTION
postgres=#
postgres=# SELECT * FROM myTable
postgres-#    WHERE sid IN (select sid from getData(myTable.id) z
postgres(#                           where z.id = myTable.id);
 id | sid | name
----+-----+------
  1 |   2 | a
  2 |   3 | b
(2 rows)

postgres=#
postgres=# drop function getData(int);
DROP FUNCTION
postgres=# drop table myTable;
DROP TABLE
postgres=#
           
       








Related examples in the same category

1.A simple WHERE clause
2.Combining conditions in the WHERE clause
3.Grouping WHERE conditions with parentheses
4.WHERE clause contains a Boolean (truth value) expression
5.Use subquery in where statement