Richard's reply is right where he talks abut how you should use the database API. However, to get the data you want, you also need to know the database schema.
$categories = $DB->get_records('question_categories', ['contextid' => context_course::instance($courseid)]);
will get the all the question categories in each course.
$questions = $DB->get_records('question', ['category' => $category->id]);
will get you the questions in a category.
Or, if you want to go back to SQL, you could get them all in one query with a join.