-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Proper syntax for "WHERE column IN [ArrayOfValues]"? #82
Comments
So far as I know, The |
The way I have done it, which is a bit hackish, is something like this: var values = [providor_string].concat(array_of_ids);
var params = array_of_ids.reduce(function (a, b, idx) {
if (idx === 0) return '$' + (idx + 2);
else return a + ', $' + (idx + 2);
}, '');
this.db.query({
text: "SELECT * FROM users "
+ "WHERE remote_id IN (" + params + ") "
+ "AND provider = $1",
values: values
}, cb); |
Yeah, in support of what @chowey said...I believe the correct syntax for sending parameters in a "in list" query clause would be to match each parameter of the in-list to a different parameter placeholder. If google & other sites are failing to provide a defnintive answer, you could also ask on freenode in the #posgres chat room |
Thanks @chowey! Your solution works really well - just had to fix two minor bugs. |
Oops, sorry about that. I sort of just wrote the code without testing/debugging it first. I fixed my solution in case someone else gets tripped up by it. |
Since node-postgres already correctly renders JavaScript client.query({
text: "SELECT * FROM users"
+ " WHERE remote_id = ANY($1)"
+ " AND provider = $2",
values: [
[1, 3, 4], // remote_id values
'Facebook', // provider
],
}, callback); There is a full example in this gist: https://gist.github.com/whitelynx/5686162 I'm not sure what the performance considerations are of doing this instead of doing an actual It might be a good idea to add this to the answers for the FAQ question on this topic. |
@whitelynx, perfect solution! |
@whitelynx I've updated the FAQ entry for this to reflect what you've said above. As I do not actually use node-postgres myself (I'm a PostgreSQL dev / Stack Overflow helper / PgJDBC contributor) I'd appreciate it if you could sanity-check the change and, if possible, add links to any node-postgres documentation that might exist to explain array parameters. |
I have an array of user ids, and would like to select all the users at once.
This query:
Gives the error
error: syntax error at or near "$1"
What's the correct syntax for this? Couldn't find it in the documentation or via google.
Thanks.
The text was updated successfully, but these errors were encountered: