Help with database query
Try this out.
get_all_nodes_not_referenced_by_article('page'); 




use Drupal\Core\Database\Database;
/**
 * @param $type
 *
 * @return mixed
 */
function get_all_nodes_not_referenced_by_article($type){

  $connection = Database::getConnection();

  //- Step one get all referenced nids
  $query = $connection->select('node_field_data', 'nfd')
                      ->condition('nfd.type', 'article')
                      ->fields('nfd', ['nid']);
  $query->leftJoin('node__field_ref', 'nfr', 'nfd.nid = nfr.entity_id');
  $result = $query->execute()->fetchAll(PDO::FETCH_ASSOC);

  $referenced_nids = [];
  foreach ($result as $key => $value) {
    $referenced_nids[] = $value['nid'];
  }

  /**
   * Check if $referenced_nids to avoid
   * Drupal\Core\Database\InvalidQueryException: Query condition 'nfd.nid NOT IN ()' cannot be empty.
   * */
  if (!empty($referenced_nids)) {
    return $connection->select('node_field_data', 'nfd')
                      ->condition('nfd.type', $type)
                      ->condition('nfd.nid', $referenced_nids, 'NOT IN')
                      ->fields('nfd', ['nid', 'title'])
                      ->execute()
                      ->fetchAll(PDO::FETCH_ASSOC);
  }
  else {
    return $connection->select('node_field_data', 'nfd')
                      ->condition('nfd.type', $type)
                      ->fields('nfd', ['nid', 'title'])
                      ->execute()
                      ->fetchAll(PDO::FETCH_ASSOC);
  }
}
?>