Dynamic column names in SQL query #1820
-
Hi, the following query works fine: SELECT value FROM ccvi WHERE year=${year} AND quarter=${quarter} However SELECT ${property} FROM ccvi WHERE year=${year} AND quarter=${quarter} does not seem to work. Is this a known limitation or a bug? Thanks for looking into this. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
This is a limitation of DuckDB’s prepared statements, which only apply to parameters and not to the shape of the query. You can however go around it by using the ```js
const results = await sql([`SELECT ${property} FROM ccvi WHERE year=2010 AND quarter="h2";`]);
``` however this now means that you have to escape the parameters, which is not convenient (and any error might be a security issue if you're using user input). A mix of both can work: const results = await sql([`SELECT ${JSON.stringify(property)} FROM ccvi WHERE year=`, ' AND quarter=', ';'], 2010, 'h2'); This generates the following prepared statement:
(You only have to worry about the safety of the 'property' variable, which is included as a string. You don't want user Bobby passing a property named |
Beta Was this translation helpful? Give feedback.
-
Another solution is to use a SELECT
source_id,
CASE WHEN ${column} = 'ra' THEN ra
WHEN ${column} = 'dec' THEN dec
ELSE NULL
END AS value
FROM gaia
ORDER BY phot_g_mean_mag
LIMIT 10 |
Beta Was this translation helpful? Give feedback.
-
a less hardcoded solution use:
|
Beta Was this translation helpful? Give feedback.
This is a limitation of DuckDB’s prepared statements, which only apply to parameters and not to the shape of the query.
You can however go around it by using the
sql
tagged template as a function, in a js fenced code block:however this now means that you have to escape the parameters, which is not convenient (and any error might be a security issue if you're using user input).
A mix of both can work:
This generates the following prepared statement:
SELECT "tempera…