problem with setting a value of a global variable inside a function [duplicate]

i have a problem with setting the value of a global variable inside a function so that it can be later used inside another function.

My code:

var user_id;

router.post('/add_note', function(request, response, next){
var note_title = request.body.note_title;
var note_content = request.body.note_content;

database.query(sql,function(err, result) {
  if (err) throw err;
  var results=JSON.parse(JSON.stringify(result))
  user_id=results[0].user_id;
  console.log("from inside: "+user_id);
});

var sql = `INSERT INTO notes (user_id, note_title, note_content) VALUES (${user_id}, "${note_title}", "${note_content}", NOW())`;
console.log("from outside: "+user_id);
console.log(sql);

when i submit the form it returns:

from outside: undefined
INSERT INTO notes (user_id, note_title, note_content) VALUES (undefined, "ads", "ads", NOW())
from inside: 2

why is it undefined, the variable should be global, i am going insane