0

I am trying to call javascript variables from within the mySQL query. The lines are executed with node.js environment, using syntax [node (filename)]. I understand that I could potentially do this query in 2 steps, by first query the value of min_value, and then query the max_value.

Can the request be executed in one mySQL query?

Preferably I would like to keep the code structure with vanilla js and mySQL, without adding node.js-specific commands, nor needing to load extra packages.

Javascript variables:

let min_value = 100;
let max_value = 300;

This works:

sql = `
 SELECT
   acronym,
   salaries
 FROM 
   employees
 WHERE
   salaries BETWEEN 100 and 300
ORDER BY acronym;
`;

This does not works:

sql = `
 SELECT
   acronym,
   salaries
 FROM 
   employees
 WHERE
   salaries BETWEEN ($min_value) and ($max_value)
ORDER BY acronym;
`;

1 Answer 1

3

Try using Template Literals, with the ${variable} placeholder syntax:

let min_value = 100;
let max_value = 300;
let sql1 = `
 SELECT
   acronym,
   salaries
 FROM 
   employees
 WHERE
   salaries BETWEEN (${min_value}) and (${max_value})
ORDER BY acronym;
`;

let sql2 = `
 SELECT
   acronym,
   salaries
 FROM 
   employees
 WHERE
   salaries BETWEEN ${min_value} and ${max_value}
ORDER BY acronym;
`;

console.log(sql1);
console.log(sql2);

Sign up to request clarification or add additional context in comments.

1 Comment

@henetik: Your answer works with both (${min_value}) and ${min_value}. I assume if one would want to follow exact syntax in scenario of having value instead of variables, I would go without the parenthesis. If you could please update the answer with both variation (without and with parenthesis), I'll go ahead and accept the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.