Use string concatenation:
-- Demo table structure
CREATE TABLE dummy ( id integer primary key, blah integer not null);
INSERT INTO dummy(id, blah) VALUES (1,1);
-- Single-valued query
SELECT id FROM dummy WHERE blah = 1;
-- Formatted with string concatenation
SELECT 'result_'||(id::text)||'_table' FROM dummy WHERE blah = 1;
-- Formatted using the `format` function
SELECT format('result_%s_table', id) FROM dummy WHERE blah = 1;
Combine into string using subquery if you're collecting other information
SELECT 'result_'||(SELECT id FROM dummy WHERE blah = 1)||'_table'
FROM .... WHERE ...
or use a join.
Your edit suggests you want to then use that as a table name. This probably means your design is bad. Instead of:
CREATE TABLE sometable_1 ( id integer primary key, ...);
CREATE TABLE sometable_2 ( id integer primary key, ...);
CREATE TABLE sometable_3 ( id integer primary key, ...);
...
CREATE TABLE sometable_n ( id integer primary key, ...);
you're almost always better off with:
CREATE TABLE sometable(
id integer not null,
discriminator integer not null,
primary key (id, discriminator),
...
);
or per-schema tables. If for some reason you're stuck with this approach you can use PL/PgSQL's EXECUTE
statement to run dynamic SQL, like:
EXECUTE format('SELECT * FROM sometable_%s WHERE blah = ?',
quote_ident((SELECT id FROM dummy WHERE blah = 1))
)
USING 2;
to query "sometable_1" for rows where "blah = 2". More info in the manual, see EXECUTE ... USING
.
It is simply not possible to do this in regular SQL for PostgreSQL. Do it in the application, or in PL/PgSQL. A PL/PgSQL DO
block can be used, but performance will be awful if you're relying on that for everything.
Fix your design now, before it's too late.