You are looking for dynamic SQL. Assemble your query from the system catalog automatically:
SELECT string_agg('SELECT student_name, '''
|| c.oid::regclass || ''' AS tbl, pid FROM '
|| c.oid::regclass
|| $$ WHERE student_name = 'John Doe'$$
, E'\nUNION ALL\n')
FROM pg_namespace n
JOIN pg_class c ON c.relnamespace = n.oid
WHERE n.nspname = 'public' -- schema name where your tables lie
AND c.relname LIKE 't%' -- and / or filter table names
AND EXISTS (
SELECT 1 FROM pg_attribute
WHERE attrelid = c.oid
AND attname = 'student_name' -- make sure column exists
AND NOT attisdropped -- and is alive
);
Produces the query string:
SELECT student_name, 'tbl1' AS tbl, pid FROM tbl1 WHERE student_name = 'John Doe'
UNION ALL
SELECT student_name, 'tbl2' AS tbl, pid FROM tbl2 WHERE student_name = 'John Doe'
UNION ALL
SELECT student_name, 'tbl3' AS tbl, pid FROM tbl3 WHERE student_name = 'John Doe'
...
Then run it in a second call or completely automate it with a PL/pgSQL function using EXECUTE
. Example:
Select a dynamic set of columns from a table and get the sum for each
This query produces safe code with sanitized identifiers preventing SQL injection. (Explanation for oid::regclass
here.)
There are more related answers. Use a search.
BTW, LIKE
in student_name LIKE 'John Doe'
is pointless. Without wildcards, just use =
.