How does Drupal know when to run an update script?
To store/get the version information for a module use the global functions:

drupal_set_installed_schema_version()
drupal_get_installed_schema_version()


For example set a new version for mymodule with drush:

drush ev "drupal_set_installed_schema_version('mymodule', '8123')"


Print the version with drush, in this example for the module comment:

drush ev "var_dump(drupal_get_installed_schema_version('comment'))"


The functions are defined in schema.inc. Here you can see how to access the key_value table through the keyvalue api, if you want to use your own code:

/**
 * Updates the installed version information for a module.
 *
 * @param string $module
 *   A module name.
 * @param string $version
 *   The new schema version.
 */
function drupal_set_installed_schema_version($module, $version) {
  \Drupal::keyValue('system.schema')-&gt;set($module, $version);
  // Reset the static cache of module schema versions.
  drupal_get_installed_schema_version(NULL, TRUE);
}