Skip to content

Dynamic column names in SQL query #1820

Answered by Fil
MoritzStefaner asked this question in Q&A
Discussion options

You must be logged in to vote

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:

```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:

SELECT "tempera…

Replies: 3 comments 2 replies

Comment options

You must be logged in to vote
1 reply
@MoritzStefaner
Comment options

Answer selected by MoritzStefaner
Comment options

You must be logged in to vote
1 reply
@MoritzStefaner
Comment options

Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
4 participants
Converted from issue

This discussion was converted from issue #1819 on November 14, 2024 19:01.