{
 "cells": [
  {
   "cell_type": "raw",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "source": [
    "---\n",
    "title: \"Basic queries\"\n",
    "teaching: 3000\n",
    "exercises: 0\n",
    "questions:\n",
    "- \"How can we select and download the data we want from the Gaia server?\"\n",
    "\n",
    "objectives:\n",
    "- \"Compose a basic query in ADQL/SQL.\"\n",
    "- \"Use queries to explore a database and its tables.\"\n",
    "- \"Use queries to download data.\"\n",
    "- \"Develop, test, and debug a query incrementally.\"\n",
    "keypoints:\n",
    "- \"If you can't download an entire dataset (or it's not practical) use queries to select the data you need.\"\n",
    "\n",
    "- \"Read the metadata and the documentation to make sure you understand the tables, their columns, and what they mean.\"\n",
    "\n",
    "- \"Develop queries incrementally: start with something simple, test it, and add a little bit at a time.\"\n",
    "\n",
    "- \"Use ADQL features like `TOP` and `COUNT` to test before you run a query that might return a lot of data.\"\n",
    "\n",
    "- \"If you know your query will return fewer than 3000 rows, you can \n",
    "run it synchronously, which might complete faster (but it doesn't seem to make much difference).  If it might return more than 3000 rows, you should run it asynchronously.\"\n",
    "\n",
    "- \"ADQL and SQL are not case-sensitive, so you don't have to \n",
    "capitalize the keywords, but you should.\"\n",
    "\n",
    "- \"ADQL and SQL don't require you to break a query into multiple \n",
    "lines, but you should.\"\n",
    "\n",
    "---\n",
    "\n",
    "{% include links.md %}\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Queries"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Outline\n",
    "\n",
    "This lesson demonstrates the steps for selecting and downloading data from the Gaia Database:\n",
    "\n",
    "1. First we'll make a connection to the Gaia server,\n",
    "\n",
    "2. We will explore information about the database and the tables it contains,\n",
    "\n",
    "3. We will write a query and send it to the server, and finally\n",
    "\n",
    "4. We will download the response from the server.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Query Language\n",
    "\n",
    "In order to select data from a database, you have to compose a query, which is a program written in a \"query language\".\n",
    "The query language we'll use is ADQL, which stands for \"Astronomical Data Query Language\".\n",
    "\n",
    "ADQL is a dialect of [SQL](https://en.wikipedia.org/wiki/SQL) (Structured Query Language), which is by far the most commonly used query language.  Almost everything you will learn about ADQL also works in SQL.\n",
    "\n",
    "[The reference manual for ADQL is here](http://www.ivoa.net/documents/ADQL/20180112/PR-ADQL-2.1-20180112.html).\n",
    "But you might find it easier to learn from [this ADQL Cookbook](https://www.gaia.ac.uk/data/gaia-data-release-1/adql-cookbook)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Using Jupyter\n",
    "\n",
    "If you have not worked with Jupyter notebooks before, you might start with [the tutorial on from Jupyter.org called \"Try Classic Notebook\"](https://jupyter.org/try), or [this tutorial from DataQuest](https://www.dataquest.io/blog/jupyter-notebook-tutorial/).\n",
    "\n",
    "There are two environments you can use to write and run notebooks: \n",
    "\n",
    "* \"Jupyter Notebook\" is the original, and\n",
    "\n",
    "* \"Jupyter Lab\" is a newer environment with more features.\n",
    "\n",
    "For these lessons, you can use either one."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you are too impatient for the tutorials, here's are the most important things to know:\n",
    "\n",
    "1. Notebooks are made up of code cells and text cells (and a few other less common kinds).  Code cells contain code; text cells, like this one, contain explanatory text written in [Markdown](https://www.markdownguide.org/).\n",
    "\n",
    "2. To run a code cell, click the cell to select it and press Shift-Enter.  The output of the code should appear below the cell.\n",
    "\n",
    "3. In general, notebooks only run correctly if you run every code cell in order from top to bottom.  If you run cells out of order, you are likely to get errors.\n",
    "\n",
    "4. You can modify existing cells, but then you have to run them again to see the effect.\n",
    "\n",
    "5. You can add new cells, but again, you might have to be careful about the order you run them in.\n",
    "\n",
    "6. If you have added or modified cells and the behavior of the notebook seems strange, you can restart the \"kernel\", which clears all of the variables and functions you have defined, and run the cells again from the beginning.\n",
    "\n",
    "* If you are using Jupyter notebook, open the Kernel menu and select \"Restart and Run All\".\n",
    "\n",
    "* In Jupyter Lab...\n",
    "\n",
    "* In Colab, open the Runtime menu and select \"Restart and run all\"\n",
    "\n",
    "Before you go on, you might want to explore the other menus and the toolbar to see what else you can do."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "source": [
    "## Installing libraries\n",
    "\n",
    "If you are running this notebook on Colab, you can run the following cell to install the libraries we'll need.\n",
    "\n",
    "If you are running this notebook on your own computer, you might have to install these libraries yourself.  See the instructions in the preface."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "# If we're running on Colab, install libraries\n",
    "\n",
    "import sys\n",
    "IN_COLAB = 'google.colab' in sys.modules\n",
    "\n",
    "if IN_COLAB:\n",
    "    !pip install astroquery"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Connecting to Gaia\n",
    "\n",
    "The library we'll use to get Gaia data is [Astroquery](https://astroquery.readthedocs.io/en/latest/).\n",
    "Astroquery provides `Gaia`, which is an [object that represents a connection to the Gaia database](https://astroquery.readthedocs.io/en/latest/gaia/gaia.html).\n",
    "\n",
    "We can connect to the Gaia database like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Created TAP+ (v1.2.1) - Connection:\n",
      "\tHost: gea.esac.esa.int\n",
      "\tUse HTTPS: True\n",
      "\tPort: 443\n",
      "\tSSL Port: 443\n",
      "Created TAP+ (v1.2.1) - Connection:\n",
      "\tHost: geadata.esac.esa.int\n",
      "\tUse HTTPS: True\n",
      "\tPort: 443\n",
      "\tSSL Port: 443\n"
     ]
    }
   ],
   "source": [
    "from astroquery.gaia import Gaia"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Running this import statement has the effect of creating a [TAP+](http://www.ivoa.net/documents/TAP/) connection; TAP stands for \"Table Access Protocol\", which is a network protocol for sending queries to the database and getting back the results.  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Databases and Tables\n",
    "\n",
    "What is a database, anyway?  Most generally, it can be any collection of data, but when we are talking about ADQL or SQL:\n",
    "\n",
    "* A database is a collection of one or more named tables.\n",
    "\n",
    "* Each table is a 2-D array with one or more named columns of data.\n",
    "\n",
    "We can use `Gaia.load_tables` to get the names of the tables in the Gaia database.  With the option `only_names=True`, it loads information about the tables, called \"metadata\", not the data itself."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO: Retrieving tables... [astroquery.utils.tap.core]\n",
      "INFO: Parsing tables... [astroquery.utils.tap.core]\n",
      "INFO: Done. [astroquery.utils.tap.core]\n"
     ]
    }
   ],
   "source": [
    "tables = Gaia.load_tables(only_names=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "tags": [
     "hide-output",
     "truncate-output"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "external.apassdr9\n",
      "external.gaiadr2_geometric_distance\n",
      "external.galex_ais\n",
      "external.ravedr5_com\n",
      "external.ravedr5_dr5\n",
      "external.ravedr5_gra\n",
      "external.ravedr5_on\n",
      "external.sdssdr13_photoprimary\n",
      "external.skymapperdr1_master\n",
      "external.skymapperdr2_master\n",
      "external.tmass_xsc\n",
      "public.hipparcos\n",
      "public.hipparcos_newreduction\n",
      "public.hubble_sc\n",
      "public.igsl_source\n",
      "public.igsl_source_catalog_ids\n",
      "public.tycho2\n",
      "public.dual\n",
      "tap_config.coord_sys\n",
      "tap_config.properties\n",
      "tap_schema.columns\n",
      "tap_schema.key_columns\n",
      "tap_schema.keys\n",
      "tap_schema.schemas\n",
      "tap_schema.tables\n",
      "gaiaedr3.gaia_source\n",
      "gaiaedr3.agn_cross_id\n",
      "gaiaedr3.commanded_scan_law\n",
      "gaiaedr3.dr2_neighbourhood\n",
      "gaiaedr3.frame_rotator_source\n",
      "gaiaedr3.hipparcos2_best_neighbour\n",
      "gaiaedr3.hipparcos2_neighbourhood\n",
      "gaiaedr3.panstarrs1_best_neighbour\n",
      "gaiaedr3.panstarrs1_join\n",
      "gaiaedr3.panstarrs1_neighbourhood\n",
      "gaiaedr3.sdssdr13_best_neighbour\n",
      "gaiaedr3.sdssdr13_join\n",
      "gaiaedr3.sdssdr13_neighbourhood\n",
      "gaiaedr3.skymapperdr2_best_neighbour\n",
      "gaiaedr3.skymapperdr2_join\n",
      "gaiaedr3.skymapperdr2_neighbourhood\n",
      "gaiaedr3.tycho2tdsc_merge_best_neighbour\n",
      "gaiaedr3.tycho2tdsc_merge_neighbourhood\n",
      "gaiaedr3.urat1_best_neighbour\n",
      "gaiaedr3.urat1_neighbourhood\n",
      "gaiaedr3.gaia_source_simulation\n",
      "gaiaedr3.gaia_universe_model\n",
      "gaiaedr3.tycho2tdsc_merge\n",
      "gaiadr1.aux_qso_icrf2_match\n",
      "gaiadr1.ext_phot_zero_point\n",
      "gaiadr1.allwise_best_neighbour\n",
      "gaiadr1.allwise_neighbourhood\n",
      "gaiadr1.gsc23_best_neighbour\n",
      "gaiadr1.gsc23_neighbourhood\n",
      "gaiadr1.ppmxl_best_neighbour\n",
      "gaiadr1.ppmxl_neighbourhood\n",
      "gaiadr1.sdss_dr9_best_neighbour\n",
      "gaiadr1.sdss_dr9_neighbourhood\n",
      "gaiadr1.tmass_best_neighbour\n",
      "gaiadr1.tmass_neighbourhood\n",
      "gaiadr1.ucac4_best_neighbour\n",
      "gaiadr1.ucac4_neighbourhood\n",
      "gaiadr1.urat1_best_neighbour\n",
      "gaiadr1.urat1_neighbourhood\n",
      "gaiadr1.cepheid\n",
      "gaiadr1.phot_variable_time_series_gfov\n",
      "gaiadr1.phot_variable_time_series_gfov_statistical_parameters\n",
      "gaiadr1.rrlyrae\n",
      "gaiadr1.variable_summary\n",
      "gaiadr1.allwise_original_valid\n",
      "gaiadr1.gsc23_original_valid\n",
      "gaiadr1.ppmxl_original_valid\n",
      "gaiadr1.sdssdr9_original_valid\n",
      "gaiadr1.tmass_original_valid\n",
      "gaiadr1.ucac4_original_valid\n",
      "gaiadr1.urat1_original_valid\n",
      "gaiadr1.gaia_source\n",
      "gaiadr1.tgas_source\n",
      "gaiadr2.aux_allwise_agn_gdr2_cross_id\n",
      "gaiadr2.aux_iers_gdr2_cross_id\n",
      "gaiadr2.aux_sso_orbit_residuals\n",
      "gaiadr2.aux_sso_orbits\n",
      "gaiadr2.dr1_neighbourhood\n",
      "gaiadr2.allwise_best_neighbour\n",
      "gaiadr2.allwise_neighbourhood\n",
      "gaiadr2.apassdr9_best_neighbour\n",
      "gaiadr2.apassdr9_neighbourhood\n",
      "gaiadr2.gsc23_best_neighbour\n",
      "gaiadr2.gsc23_neighbourhood\n",
      "gaiadr2.hipparcos2_best_neighbour\n",
      "gaiadr2.hipparcos2_neighbourhood\n",
      "gaiadr2.panstarrs1_best_neighbour\n",
      "gaiadr2.panstarrs1_neighbourhood\n",
      "gaiadr2.ppmxl_best_neighbour\n",
      "gaiadr2.ppmxl_neighbourhood\n",
      "gaiadr2.ravedr5_best_neighbour\n",
      "gaiadr2.ravedr5_neighbourhood\n",
      "gaiadr2.sdssdr9_best_neighbour\n",
      "gaiadr2.sdssdr9_neighbourhood\n",
      "gaiadr2.tmass_best_neighbour\n",
      "gaiadr2.tmass_neighbourhood\n",
      "gaiadr2.tycho2_best_neighbour\n",
      "gaiadr2.tycho2_neighbourhood\n",
      "gaiadr2.urat1_best_neighbour\n",
      "gaiadr2.urat1_neighbourhood\n",
      "gaiadr2.sso_observation\n",
      "gaiadr2.sso_source\n",
      "gaiadr2.vari_cepheid\n",
      "gaiadr2.vari_classifier_class_definition\n",
      "gaiadr2.vari_classifier_definition\n",
      "gaiadr2.vari_classifier_result\n",
      "gaiadr2.vari_long_period_variable\n",
      "gaiadr2.vari_rotation_modulation\n",
      "gaiadr2.vari_rrlyrae\n",
      "gaiadr2.vari_short_timescale\n",
      "gaiadr2.vari_time_series_statistics\n",
      "gaiadr2.panstarrs1_original_valid\n",
      "gaiadr2.gaia_source\n",
      "gaiadr2.ruwe\n"
     ]
    }
   ],
   "source": [
    "for table in tables:\n",
    "    print(table.name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So that's a lot of tables.  The ones we'll use are:\n",
    "\n",
    "* `gaiadr2.gaia_source`, which contains Gaia data from [data release 2](https://www.cosmos.esa.int/web/gaia/data-release-2),\n",
    "\n",
    "* `gaiadr2.panstarrs1_original_valid`, which contains the photometry data we'll use from PanSTARRS, and\n",
    "\n",
    "* `gaiadr2.panstarrs1_best_neighbour`, which we'll use to cross-match each star observed by Gaia with the same star observed by PanSTARRS.\n",
    "\n",
    "We can use `load_table` (not `load_tables`) to get the metadata for a single table.  The name of this function is misleading, because it only downloads metadata, not the contents of the table."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Retrieving table 'gaiadr2.gaia_source'\n",
      "Parsing table 'gaiadr2.gaia_source'...\n",
      "Done.\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<astroquery.utils.tap.model.taptable.TapTableMeta at 0x7f2e23f089d0>"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "meta = Gaia.load_table('gaiadr2.gaia_source')\n",
    "meta"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Jupyter shows that the result is an object of type `TapTableMeta`, but it does not display the contents.\n",
    "\n",
    "To see the metadata, we have to print the object."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "TAP Table name: gaiadr2.gaiadr2.gaia_source\n",
      "Description: This table has an entry for every Gaia observed source as listed in the\n",
      "Main Database accumulating catalogue version from which the catalogue\n",
      "release has been generated. It contains the basic source parameters,\n",
      "that is only final data (no epoch data) and no spectra (neither final\n",
      "nor epoch).\n",
      "Num. columns: 96\n"
     ]
    }
   ],
   "source": [
    "print(meta)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Columns\n",
    "\n",
    "The following loop prints the names of the columns in the table."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "tags": [
     "hide-output",
     "truncate-output"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "solution_id\n",
      "designation\n",
      "source_id\n",
      "random_index\n",
      "ref_epoch\n",
      "ra\n",
      "ra_error\n",
      "dec\n",
      "dec_error\n",
      "parallax\n",
      "parallax_error\n",
      "parallax_over_error\n",
      "pmra\n",
      "pmra_error\n",
      "pmdec\n",
      "pmdec_error\n",
      "ra_dec_corr\n",
      "ra_parallax_corr\n",
      "ra_pmra_corr\n",
      "ra_pmdec_corr\n",
      "dec_parallax_corr\n",
      "dec_pmra_corr\n",
      "dec_pmdec_corr\n",
      "parallax_pmra_corr\n",
      "parallax_pmdec_corr\n",
      "pmra_pmdec_corr\n",
      "astrometric_n_obs_al\n",
      "astrometric_n_obs_ac\n",
      "astrometric_n_good_obs_al\n",
      "astrometric_n_bad_obs_al\n",
      "astrometric_gof_al\n",
      "astrometric_chi2_al\n",
      "astrometric_excess_noise\n",
      "astrometric_excess_noise_sig\n",
      "astrometric_params_solved\n",
      "astrometric_primary_flag\n",
      "astrometric_weight_al\n",
      "astrometric_pseudo_colour\n",
      "astrometric_pseudo_colour_error\n",
      "mean_varpi_factor_al\n",
      "astrometric_matched_observations\n",
      "visibility_periods_used\n",
      "astrometric_sigma5d_max\n",
      "frame_rotator_object_type\n",
      "matched_observations\n",
      "duplicated_source\n",
      "phot_g_n_obs\n",
      "phot_g_mean_flux\n",
      "phot_g_mean_flux_error\n",
      "phot_g_mean_flux_over_error\n",
      "phot_g_mean_mag\n",
      "phot_bp_n_obs\n",
      "phot_bp_mean_flux\n",
      "phot_bp_mean_flux_error\n",
      "phot_bp_mean_flux_over_error\n",
      "phot_bp_mean_mag\n",
      "phot_rp_n_obs\n",
      "phot_rp_mean_flux\n",
      "phot_rp_mean_flux_error\n",
      "phot_rp_mean_flux_over_error\n",
      "phot_rp_mean_mag\n",
      "phot_bp_rp_excess_factor\n",
      "phot_proc_mode\n",
      "bp_rp\n",
      "bp_g\n",
      "g_rp\n",
      "radial_velocity\n",
      "radial_velocity_error\n",
      "rv_nb_transits\n",
      "rv_template_teff\n",
      "rv_template_logg\n",
      "rv_template_fe_h\n",
      "phot_variable_flag\n",
      "l\n",
      "b\n",
      "ecl_lon\n",
      "ecl_lat\n",
      "priam_flags\n",
      "teff_val\n",
      "teff_percentile_lower\n",
      "teff_percentile_upper\n",
      "a_g_val\n",
      "a_g_percentile_lower\n",
      "a_g_percentile_upper\n",
      "e_bp_min_rp_val\n",
      "e_bp_min_rp_percentile_lower\n",
      "e_bp_min_rp_percentile_upper\n",
      "flame_flags\n",
      "radius_val\n",
      "radius_percentile_lower\n",
      "radius_percentile_upper\n",
      "lum_val\n",
      "lum_percentile_lower\n",
      "lum_percentile_upper\n",
      "datalink_url\n",
      "epoch_photometry_url\n"
     ]
    }
   ],
   "source": [
    "for column in meta.columns:\n",
    "    print(column.name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can probably guess what many of these columns are by looking at the names, but you should resist the temptation to guess.\n",
    "To find out what the columns mean, [read the documentation](https://gea.esac.esa.int/archive/documentation/GDR2/Gaia_archive/chap_datamodel/sec_dm_main_tables/ssec_dm_gaia_source.html).\n",
    "\n",
    "If you want to know what can go wrong when you don't read the documentation, [you might like this article](https://www.vox.com/future-perfect/2019/6/4/18650969/married-women-miserable-fake-paul-dolan-happiness)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise\n",
    "\n",
    "One of the other tables we'll use is `gaiadr2.panstarrs1_original_valid`.  Use `load_table` to get the metadata for this table.  How many columns are there and what are their names?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Retrieving table 'gaiadr2.panstarrs1_original_valid'\n",
      "Parsing table 'gaiadr2.panstarrs1_original_valid'...\n",
      "Done.\n",
      "TAP Table name: gaiadr2.gaiadr2.panstarrs1_original_valid\n",
      "Description: The Panoramic Survey Telescope and Rapid Response System (Pan-STARRS) is\n",
      "a system for wide-field astronomical imaging developed and operated by\n",
      "the Institute for Astronomy at the University of Hawaii. Pan-STARRS1\n",
      "(PS1) is the first part of Pan-STARRS to be completed and is the basis\n",
      "for Data Release 1 (DR1). The PS1 survey used a 1.8 meter telescope and\n",
      "its 1.4 Gigapixel camera to image the sky in five broadband filters (g,\n",
      "r, i, z, y).\n",
      "\n",
      "The current table contains a filtered subsample of the 10 723 304 629\n",
      "entries listed in the original ObjectThin table.\n",
      "We used only ObjectThin and MeanObject tables to extract\n",
      "panstarrs1OriginalValid table, this means that objects detected only in\n",
      "stack images are not included here. The main reason for us to avoid the\n",
      "use of objects detected in stack images is that their astrometry is not\n",
      "as good as the mean objects astrometry: “The stack positions (raStack,\n",
      "decStack) have considerably larger systematic astrometric errors than\n",
      "the mean epoch positions (raMean, decMean).” The astrometry for the\n",
      "MeanObject positions uses Gaia DR1 as a reference catalog, while the\n",
      "stack positions use 2MASS as a reference catalog.\n",
      "\n",
      "In details, we filtered out all objects where:\n",
      "\n",
      "-   nDetections = 1\n",
      "\n",
      "-   no good quality data in Pan-STARRS, objInfoFlag 33554432 not set\n",
      "\n",
      "-   mean astrometry could not be measured, objInfoFlag 524288 set\n",
      "\n",
      "-   stack position used for mean astrometry, objInfoFlag 1048576 set\n",
      "\n",
      "-   error on all magnitudes equal to 0 or to -999;\n",
      "\n",
      "-   all magnitudes set to -999;\n",
      "\n",
      "-   error on RA or DEC greater than 1 arcsec.\n",
      "\n",
      "The number of objects in panstarrs1OriginalValid is 2 264 263 282.\n",
      "\n",
      "The panstarrs1OriginalValid table contains only a subset of the columns\n",
      "available in the combined ObjectThin and MeanObject tables. A\n",
      "description of the original ObjectThin and MeanObjects tables can be\n",
      "found at:\n",
      "https://outerspace.stsci.edu/display/PANSTARRS/PS1+Database+object+and+detection+tables\n",
      "\n",
      "Download:\n",
      "http://mastweb.stsci.edu/ps1casjobs/home.aspx\n",
      "Documentation:\n",
      "https://outerspace.stsci.edu/display/PANSTARRS\n",
      "http://pswww.ifa.hawaii.edu/pswww/\n",
      "References:\n",
      "The Pan-STARRS1 Surveys, Chambers, K.C., et al. 2016, arXiv:1612.05560\n",
      "Pan-STARRS Data Processing System, Magnier, E. A., et al. 2016,\n",
      "arXiv:1612.05240\n",
      "Pan-STARRS Pixel Processing: Detrending, Warping, Stacking, Waters, C.\n",
      "Z., et al. 2016, arXiv:1612.05245\n",
      "Pan-STARRS Pixel Analysis: Source Detection and Characterization,\n",
      "Magnier, E. A., et al. 2016, arXiv:1612.05244\n",
      "Pan-STARRS Photometric and Astrometric Calibration, Magnier, E. A., et\n",
      "al. 2016, arXiv:1612.05242\n",
      "The Pan-STARRS1 Database and Data Products, Flewelling, H. A., et al.\n",
      "2016, arXiv:1612.05243\n",
      "\n",
      "Catalogue curator:\n",
      "SSDC - ASI Space Science Data Center\n",
      "https://www.ssdc.asi.it/\n",
      "Num. columns: 26\n",
      "obj_name\n",
      "obj_id\n",
      "ra\n",
      "dec\n",
      "ra_error\n",
      "dec_error\n",
      "epoch_mean\n",
      "g_mean_psf_mag\n",
      "g_mean_psf_mag_error\n",
      "g_flags\n",
      "r_mean_psf_mag\n",
      "r_mean_psf_mag_error\n",
      "r_flags\n",
      "i_mean_psf_mag\n",
      "i_mean_psf_mag_error\n",
      "i_flags\n",
      "z_mean_psf_mag\n",
      "z_mean_psf_mag_error\n",
      "z_flags\n",
      "y_mean_psf_mag\n",
      "y_mean_psf_mag_error\n",
      "y_flags\n",
      "n_detections\n",
      "zone_id\n",
      "obj_info_flag\n",
      "quality_flag\n"
     ]
    }
   ],
   "source": [
    "# Solution\n",
    "\n",
    "meta2 = Gaia.load_table('gaiadr2.panstarrs1_original_valid')\n",
    "print(meta2)\n",
    "\n",
    "for column in meta2.columns:\n",
    "    print(column.name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Writing queries\n",
    "\n",
    "By now you might be wondering how we download the actual data.  With tables this big, you generally don't.  Instead, you use queries to select only the data you want.\n",
    "\n",
    "A query is a string written in a query language like SQL; for the Gaia database, the query language is a dialect of SQL called ADQL.\n",
    "\n",
    "Here's an example of an ADQL query."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "query1 = \"\"\"SELECT \n",
    "TOP 10\n",
    "source_id, ref_epoch, ra, dec, parallax \n",
    "FROM gaiadr2.gaia_source\"\"\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Python note:** We use a [triple-quoted string](https://docs.python.org/3/tutorial/introduction.html#strings) here so we can include line breaks in the query, which makes it easier to read.\n",
    "\n",
    "The words in uppercase are ADQL keywords:\n",
    "\n",
    "* `SELECT` indicates that we are selecting data (as opposed to adding or modifying data).\n",
    "\n",
    "* `TOP` indicates that we only want the first 10 rows of the table, which is useful for testing a query before asking for all of the data.\n",
    "\n",
    "* `FROM` specifies which table we want data from.\n",
    "\n",
    "The third line is a list of column names, indicating which columns we want.  \n",
    "\n",
    "In this example, the keywords are capitalized and the column names are lowercase.  This is a common style, but it is not required.  ADQL and SQL are not case-sensitive."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To run this query, we use the `Gaia` object, which represents our connection to the Gaia database, and invoke `launch_job`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<astroquery.utils.tap.model.job.Job at 0x7f2e23f2afa0>"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "job1 = Gaia.launch_job(query1)\n",
    "job1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The result is an object that represents the job running on a Gaia server.\n",
    "\n",
    "If you print it, it displays metadata for the forthcoming table."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<Table length=10>\n",
      "   name    dtype  unit                            description                             n_bad\n",
      "--------- ------- ---- ------------------------------------------------------------------ -----\n",
      "source_id   int64      Unique source identifier (unique within a particular Data Release)     0\n",
      "ref_epoch float64   yr                                                    Reference epoch     0\n",
      "       ra float64  deg                                                    Right ascension     0\n",
      "      dec float64  deg                                                        Declination     0\n",
      " parallax float64  mas                                                           Parallax     2\n",
      "Jobid: None\n",
      "Phase: COMPLETED\n",
      "Owner: None\n",
      "Output file: sync_20201229114647.xml.gz\n",
      "Results: None\n"
     ]
    }
   ],
   "source": [
    "print(job1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Don't worry about `Results: None`.  That does not actually mean there are no results.\n",
    "\n",
    "However, `Phase: COMPLETED` indicates that the job is complete, so we can get the results like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "astropy.table.table.Table"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "results1 = job1.get_results()\n",
    "type(results1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Optional detail:**  Why is `table` repeated three times?  The first is the name of the module, the second is the name of the submodule, and the third is the name of the class.  Most of the time we only care about the last one.  It's like the Linnean name for gorilla, which is *Gorilla gorilla gorilla*."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The result is an [Astropy Table](https://docs.astropy.org/en/stable/table/), which is similar to a table in an SQL database except:\n",
    "\n",
    "* SQL databases are stored on disk drives, so they are persistent; that is, they \"survive\" even if you turn off the computer.  An Astropy `Table` is stored in memory; it disappears when you turn off the computer (or shut down this Jupyter notebook).\n",
    "\n",
    "* SQL databases are designed to process queries.  An Astropy `Table` can perform some query-like operations, like selecting columns and rows.  But these operations use Python syntax, not SQL.\n",
    "\n",
    "Jupyter knows how to display the contents of a `Table`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<i>Table length=10</i>\n",
       "<table id=\"table139836148327136\" class=\"table-striped table-bordered table-condensed\">\n",
       "<thead><tr><th>source_id</th><th>ref_epoch</th><th>ra</th><th>dec</th><th>parallax</th></tr></thead>\n",
       "<thead><tr><th></th><th>yr</th><th>deg</th><th>deg</th><th>mas</th></tr></thead>\n",
       "<thead><tr><th>int64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th></tr></thead>\n",
       "<tr><td>6758509757594141440</td><td>2015.5</td><td>290.4899010727352</td><td>-30.34317218420783</td><td>0.48023816159705535</td></tr>\n",
       "<tr><td>6758508692437976960</td><td>2015.5</td><td>290.64176055082714</td><td>-30.28972013142225</td><td>2.2625971293368154</td></tr>\n",
       "<tr><td>6758527036250849280</td><td>2015.5</td><td>290.35703708993327</td><td>-30.193657826181596</td><td>-0.2763960334229464</td></tr>\n",
       "<tr><td>6758564458298242944</td><td>2015.5</td><td>290.77376294142846</td><td>-29.765368439225238</td><td>0.5907906528352993</td></tr>\n",
       "<tr><td>6758558612842155776</td><td>2015.5</td><td>290.67550630386245</td><td>-29.92113396078169</td><td>0.2858563565989917</td></tr>\n",
       "<tr><td>6758556379459921920</td><td>2015.5</td><td>290.5454006212404</td><td>-29.900709054816964</td><td>-1.0012355835832834</td></tr>\n",
       "<tr><td>6758537520260385152</td><td>2015.5</td><td>290.7341683169994</td><td>-30.158181298418626</td><td>--</td></tr>\n",
       "<tr><td>6758506355980010624</td><td>2015.5</td><td>290.586950869878</td><td>-30.37137642167569</td><td>0.3769870991981157</td></tr>\n",
       "<tr><td>6758561606433968128</td><td>2015.5</td><td>290.82697136098506</td><td>-29.75247697212053</td><td>--</td></tr>\n",
       "<tr><td>6758564183414408448</td><td>2015.5</td><td>290.7133096669958</td><td>-29.781743673679607</td><td>0.9376387942856869</td></tr>\n",
       "</table>"
      ],
      "text/plain": [
       "<Table length=10>\n",
       "     source_id      ref_epoch ...         dec               parallax     \n",
       "                        yr    ...         deg                 mas        \n",
       "       int64         float64  ...       float64             float64      \n",
       "------------------- --------- ... ------------------- -------------------\n",
       "6758509757594141440    2015.5 ...  -30.34317218420783 0.48023816159705535\n",
       "6758508692437976960    2015.5 ...  -30.28972013142225  2.2625971293368154\n",
       "6758527036250849280    2015.5 ... -30.193657826181596 -0.2763960334229464\n",
       "6758564458298242944    2015.5 ... -29.765368439225238  0.5907906528352993\n",
       "6758558612842155776    2015.5 ...  -29.92113396078169  0.2858563565989917\n",
       "6758556379459921920    2015.5 ... -29.900709054816964 -1.0012355835832834\n",
       "6758537520260385152    2015.5 ... -30.158181298418626                  --\n",
       "6758506355980010624    2015.5 ...  -30.37137642167569  0.3769870991981157\n",
       "6758561606433968128    2015.5 ...  -29.75247697212053                  --\n",
       "6758564183414408448    2015.5 ... -29.781743673679607  0.9376387942856869"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "results1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Each column has a name, units, and a data type.\n",
    "\n",
    "For example, the units of `ra` and `dec` are degrees, and their data type is `float64`, which is a 64-bit floating-point number, used to store measurements with a fraction part.\n",
    "\n",
    "This information comes from the Gaia database, and has been stored in the Astropy `Table` by Astroquery."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise\n",
    "\n",
    "Read [the documentation of this table](https://gea.esac.esa.int/archive/documentation/GDR2/Gaia_archive/chap_datamodel/sec_dm_main_tables/ssec_dm_gaia_source.html) and choose a column that looks interesting to you.  Add the column name to the query and run it again.  What are the units of the column you selected?  What is its data type?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Asynchronous queries\n",
    "\n",
    "`launch_job` asks the server to run the job \"synchronously\", which normally means it runs immediately.  But synchronous jobs are limited to 2000 rows.  For queries that return more rows, you should run \"asynchronously\", which mean they might take longer to get started.\n",
    "\n",
    "If you are not sure how many rows a query will return, you can use the SQL command `COUNT` to find out how many rows are in the result without actually returning them.  We'll see an example of this later.\n",
    "\n",
    "The results of an asynchronous query are stored in a file on the server, so you can start a query and come back later to get the results.\n",
    "\n",
    "For anonymous users, files are kept for three days.\n",
    "\n",
    "As an example, let's try a query that's similar to `query1`, with two changes:\n",
    "\n",
    "* It selects the first 3000 rows, so it is bigger than we should run synchronously.\n",
    "\n",
    "* It uses a new keyword, `WHERE`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "query2 = \"\"\"SELECT TOP 3000\n",
    "source_id, ref_epoch, ra, dec, parallax\n",
    "FROM gaiadr2.gaia_source\n",
    "WHERE parallax < 1\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A `WHERE` clause indicates which rows we want; in this case, the query selects only rows \"where\" `parallax` is less than 1.  This has the effect of selecting stars with relatively low parallax, which are farther away.  We'll use this clause to exclude nearby stars that are unlikely to be part of GD-1.\n",
    "\n",
    "`WHERE` is one of the most common clauses in ADQL/SQL, and one of the most useful, because it allows us to select only the rows we need from the database.\n",
    "\n",
    "We use `launch_job_async` to submit an asynchronous query."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO: Query finished. [astroquery.utils.tap.core]\n",
      "<Table length=3000>\n",
      "   name    dtype  unit                            description                            \n",
      "--------- ------- ---- ------------------------------------------------------------------\n",
      "source_id   int64      Unique source identifier (unique within a particular Data Release)\n",
      "ref_epoch float64   yr                                                    Reference epoch\n",
      "       ra float64  deg                                                    Right ascension\n",
      "      dec float64  deg                                                        Declination\n",
      " parallax float64  mas                                                           Parallax\n",
      "Jobid: 1609260407863O\n",
      "Phase: COMPLETED\n",
      "Owner: None\n",
      "Output file: async_20201229114648.vot\n",
      "Results: None\n"
     ]
    }
   ],
   "source": [
    "job2 = Gaia.launch_job_async(query2)\n",
    "print(job2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And here are the results."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<i>Table length=3000</i>\n",
       "<table id=\"table139836145366016\" class=\"table-striped table-bordered table-condensed\">\n",
       "<thead><tr><th>source_id</th><th>ref_epoch</th><th>ra</th><th>dec</th><th>parallax</th></tr></thead>\n",
       "<thead><tr><th></th><th>yr</th><th>deg</th><th>deg</th><th>mas</th></tr></thead>\n",
       "<thead><tr><th>int64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th></tr></thead>\n",
       "<tr><td>6758509757594141440</td><td>2015.5</td><td>290.4899010727352</td><td>-30.34317218420783</td><td>0.48023816159705535</td></tr>\n",
       "<tr><td>6758527036250849280</td><td>2015.5</td><td>290.35703708993327</td><td>-30.193657826181596</td><td>-0.2763960334229464</td></tr>\n",
       "<tr><td>6758564458298242944</td><td>2015.5</td><td>290.77376294142846</td><td>-29.765368439225238</td><td>0.5907906528352993</td></tr>\n",
       "<tr><td>6758558612842155776</td><td>2015.5</td><td>290.67550630386245</td><td>-29.92113396078169</td><td>0.2858563565989917</td></tr>\n",
       "<tr><td>6758556379459921920</td><td>2015.5</td><td>290.5454006212404</td><td>-29.900709054816964</td><td>-1.0012355835832834</td></tr>\n",
       "<tr><td>6758506355980010624</td><td>2015.5</td><td>290.586950869878</td><td>-30.37137642167569</td><td>0.3769870991981157</td></tr>\n",
       "<tr><td>6758564183414408448</td><td>2015.5</td><td>290.7133096669958</td><td>-29.781743673679607</td><td>0.9376387942856869</td></tr>\n",
       "<tr><td>6758529789322653184</td><td>2015.5</td><td>290.35449465190385</td><td>-30.10231481465004</td><td>-1.3305133038319952</td></tr>\n",
       "<tr><td>6758507485555336064</td><td>2015.5</td><td>290.6745961953205</td><td>-30.35965148061028</td><td>0.057302711920868686</td></tr>\n",
       "<tr><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td></tr>\n",
       "<tr><td>4660464894038295424</td><td>2015.5</td><td>79.74509945051724</td><td>-66.49656012737759</td><td>0.1631257821260955</td></tr>\n",
       "<tr><td>4660463519650480128</td><td>2015.5</td><td>80.06150680482719</td><td>-66.42891601595986</td><td>-0.5822669736733328</td></tr>\n",
       "<tr><td>4660487674554071040</td><td>2015.5</td><td>80.03536662790846</td><td>-66.33136792885134</td><td>-1.4978065466579966</td></tr>\n",
       "<tr><td>4660494718300886784</td><td>2015.5</td><td>79.6181997343967</td><td>-66.17472335318212</td><td>0.1488652133861382</td></tr>\n",
       "<tr><td>4660476473274159360</td><td>2015.5</td><td>79.12508291180023</td><td>-66.35644844757275</td><td>0.10671540523101529</td></tr>\n",
       "<tr><td>4660471010093940224</td><td>2015.5</td><td>79.1908378165463</td><td>-66.48916840294096</td><td>0.8152150079365807</td></tr>\n",
       "<tr><td>4660498394807167744</td><td>2015.5</td><td>80.23431532382547</td><td>-66.08688681815092</td><td>-0.14060596426163252</td></tr>\n",
       "<tr><td>4660498738391722880</td><td>2015.5</td><td>80.20205898946918</td><td>-66.04392313295126</td><td>0.1894642263668475</td></tr>\n",
       "<tr><td>4660474068091096960</td><td>2015.5</td><td>78.93686107060341</td><td>-66.45795576745896</td><td>0.4665513634059366</td></tr>\n",
       "<tr><td>4660437303162697728</td><td>2015.5</td><td>80.63872120225027</td><td>-66.46144560233674</td><td>-1.1319163320535979</td></tr>\n",
       "</table>"
      ],
      "text/plain": [
       "<Table length=3000>\n",
       "     source_id      ref_epoch ...         dec               parallax      \n",
       "                        yr    ...         deg                 mas         \n",
       "       int64         float64  ...       float64             float64       \n",
       "------------------- --------- ... ------------------- --------------------\n",
       "6758509757594141440    2015.5 ...  -30.34317218420783  0.48023816159705535\n",
       "6758527036250849280    2015.5 ... -30.193657826181596  -0.2763960334229464\n",
       "6758564458298242944    2015.5 ... -29.765368439225238   0.5907906528352993\n",
       "6758558612842155776    2015.5 ...  -29.92113396078169   0.2858563565989917\n",
       "6758556379459921920    2015.5 ... -29.900709054816964  -1.0012355835832834\n",
       "6758506355980010624    2015.5 ...  -30.37137642167569   0.3769870991981157\n",
       "6758564183414408448    2015.5 ... -29.781743673679607   0.9376387942856869\n",
       "6758529789322653184    2015.5 ...  -30.10231481465004  -1.3305133038319952\n",
       "6758507485555336064    2015.5 ...  -30.35965148061028 0.057302711920868686\n",
       "                ...       ... ...                 ...                  ...\n",
       "4660464894038295424    2015.5 ...  -66.49656012737759   0.1631257821260955\n",
       "4660463519650480128    2015.5 ...  -66.42891601595986  -0.5822669736733328\n",
       "4660487674554071040    2015.5 ...  -66.33136792885134  -1.4978065466579966\n",
       "4660494718300886784    2015.5 ...  -66.17472335318212   0.1488652133861382\n",
       "4660476473274159360    2015.5 ...  -66.35644844757275  0.10671540523101529\n",
       "4660471010093940224    2015.5 ...  -66.48916840294096   0.8152150079365807\n",
       "4660498394807167744    2015.5 ...  -66.08688681815092 -0.14060596426163252\n",
       "4660498738391722880    2015.5 ...  -66.04392313295126   0.1894642263668475\n",
       "4660474068091096960    2015.5 ...  -66.45795576745896   0.4665513634059366\n",
       "4660437303162697728    2015.5 ...  -66.46144560233674  -1.1319163320535979"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "results2 = job2.get_results()\n",
    "results2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You might notice that some values of `parallax` are negative.  As [this FAQ explains](https://www.cosmos.esa.int/web/gaia/archive-tips#negative%20parallax), \"Negative parallaxes are caused by errors in the observations.\"  Negative parallaxes have \"no physical meaning,\" but they can be a \"useful diagnostic on the quality of the astrometric solution.\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise\n",
    "\n",
    "The clauses in a query have to be in the right order.  Go back and change the order of the clauses in `query2` and run it again.  \n",
    "\n",
    "The query should fail, but notice that you don't get much useful debugging information.  \n",
    "\n",
    "For this reason, developing and debugging ADQL queries can be really hard.  A few suggestions that might help:\n",
    "\n",
    "* Whenever possible, start with a working query, either an example you find online or a query you have used in the past.\n",
    "\n",
    "* Make small changes and test each change before you continue.\n",
    "\n",
    "* While you are debugging, use `TOP` to limit the number of rows in the result.  That will make each test run faster, which reduces your development time.  \n",
    "\n",
    "* Launching test queries synchronously might make them start faster, too."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Operators\n",
    "\n",
    "In a `WHERE` clause, you can use any of the [SQL comparison operators](https://www.w3schools.com/sql/sql_operators.asp); here are the most common ones:\n",
    "\n",
    "| Symbol | Operation\n",
    "|--------| :---\n",
    "| `>` | greater than\n",
    "| `<` | less than\n",
    "| `>=` | greater than or equal\n",
    "| `<=` | less than or equal\n",
    "| `=` | equal\n",
    "| `!=` or `<>` | not equal\n",
    "\n",
    "Most of these are the same as Python, but some are not.  In particular, notice that the equality operator is `=`, not `==`.\n",
    "Be careful to keep your Python out of your ADQL!\n",
    "\n",
    "You can combine comparisons using the logical operators:\n",
    "\n",
    "* AND: true if both comparisons are true\n",
    "* OR: true if either or both comparisons are true\n",
    "\n",
    "Finally, you can use `NOT` to invert the result of a comparison. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise\n",
    "\n",
    "[Read about SQL operators here](https://www.w3schools.com/sql/sql_operators.asp) and then modify the previous query to select rows where `bp_rp` is between `-0.75` and `2`.\n",
    "\n",
    "You can [read about this variable here](https://gea.esac.esa.int/archive/documentation/GDR2/Gaia_archive/chap_datamodel/sec_dm_main_tables/ssec_dm_gaia_source.html)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [],
   "source": [
    "# Solution\n",
    "\n",
    "# Here's a solution using > and < operators\n",
    "\n",
    "query = \"\"\"SELECT TOP 10\n",
    "source_id, ref_epoch, ra, dec, parallax\n",
    "FROM gaiadr2.gaia_source\n",
    "WHERE parallax < 1 \n",
    "  AND bp_rp > -0.75 AND bp_rp < 2\n",
    "\"\"\"\n",
    "\n",
    "# And here's a solution using the BETWEEN operator\n",
    "\n",
    "query = \"\"\"SELECT TOP 10\n",
    "source_id, ref_epoch, ra, dec, parallax\n",
    "FROM gaiadr2.gaia_source\n",
    "WHERE parallax < 1 \n",
    "  AND bp_rp BETWEEN -0.75 AND 2\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This [Hertzsprung-Russell diagram](https://sci.esa.int/web/gaia/-/60198-gaia-hertzsprung-russell-diagram) shows the BP-RP color and luminosity of stars in the Gaia catalog (Copyright: ESA/Gaia/DPAC, CC BY-SA 3.0 IGO).\n",
    "\n",
    "<img width=\"300\" src=\"https://github.com/AllenDowney/AstronomicalData/raw/main/images/1567214809100-ESA_Gaia_DR2_HRD_Gaia_625.jpg\">\n",
    "\n",
    "Selecting stars with `bp-rp` less than 2 excludes many [class M dwarf stars](https://xkcd.com/2360/), which are low temperature, low luminosity.  A star like that at GD-1's distance would be hard to detect, so if it is detected, it it more likely to be in the foreground."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Cleaning up\n",
    "\n",
    "Asynchronous jobs have a `jobid`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(None, '1609260407863O')"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "job1.jobid, job2.jobid"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Which you can use to remove the job from the server."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Removed jobs: '['1609260407863O']'.\n"
     ]
    }
   ],
   "source": [
    "Gaia.remove_jobs([job2.jobid])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you don't remove it job from the server, it will be removed eventually, so don't feel too bad if you don't clean up after yourself."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Formatting queries\n",
    "\n",
    "So far the queries have been string \"literals\", meaning that the entire string is part of the program.\n",
    "But writing queries yourself can be slow, repetitive, and error-prone.\n",
    "\n",
    "It is often a good idea to write Python code that assembles a query for you.  One useful tool for that is the [string `format` method](https://www.w3schools.com/python/ref_string_format.asp).\n",
    "\n",
    "As an example, we'll divide the previous query into two parts; a list of column names and a \"base\" for the query that contains everything except the column names.\n",
    "\n",
    "Here's the list of columns we'll select.  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "columns = 'source_id, ra, dec, pmra, pmdec, parallax, radial_velocity'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And here's the base; it's a string that contains at least one format specifier in curly brackets (braces)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [],
   "source": [
    "query3_base = \"\"\"SELECT TOP 10 \n",
    "{columns}\n",
    "FROM gaiadr2.gaia_source\n",
    "WHERE parallax < 1\n",
    "  AND bp_rp BETWEEN -0.75 AND 2\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This base query contains one format specifier, `{columns}`, which is a placeholder for the list of column names we will provide.\n",
    "\n",
    "To assemble the query, we invoke `format` on the base string and provide a keyword argument that assigns a value to `columns`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [],
   "source": [
    "query3 = query3_base.format(columns=columns)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The result is a string with line breaks.  If you display it, the line breaks appear as `\\n`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'SELECT TOP 10 \\nsource_id, ra, dec, pmra, pmdec, parallax, radial_velocity\\nFROM gaiadr2.gaia_source\\nWHERE parallax < 1\\n  AND bp_rp BETWEEN -0.75 AND 2\\n'"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "query3"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "But if you print it, the line breaks appear as... line breaks."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SELECT TOP 10 \n",
      "source_id, ra, dec, pmra, pmdec, parallax, radial_velocity\n",
      "FROM gaiadr2.gaia_source\n",
      "WHERE parallax < 1\n",
      "  AND bp_rp BETWEEN -0.75 AND 2\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print(query3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Notice that the format specifier has been replaced with the value of `columns`.\n",
    "\n",
    "Let's run it and see if it works:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<Table length=10>\n",
      "      name       dtype    unit                              description                             n_bad\n",
      "--------------- ------- -------- ------------------------------------------------------------------ -----\n",
      "      source_id   int64          Unique source identifier (unique within a particular Data Release)     0\n",
      "             ra float64      deg                                                    Right ascension     0\n",
      "            dec float64      deg                                                        Declination     0\n",
      "           pmra float64 mas / yr                         Proper motion in right ascension direction     0\n",
      "          pmdec float64 mas / yr                             Proper motion in declination direction     0\n",
      "       parallax float64      mas                                                           Parallax     0\n",
      "radial_velocity float64   km / s                                                    Radial velocity    10\n",
      "Jobid: None\n",
      "Phase: COMPLETED\n",
      "Owner: None\n",
      "Output file: sync_20201229114653.xml.gz\n",
      "Results: None\n"
     ]
    }
   ],
   "source": [
    "job3 = Gaia.launch_job(query3)\n",
    "print(job3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<i>Table length=10</i>\n",
       "<table id=\"table139836148327184\" class=\"table-striped table-bordered table-condensed\">\n",
       "<thead><tr><th>source_id</th><th>ra</th><th>dec</th><th>pmra</th><th>pmdec</th><th>parallax</th><th>radial_velocity</th></tr></thead>\n",
       "<thead><tr><th></th><th>deg</th><th>deg</th><th>mas / yr</th><th>mas / yr</th><th>mas</th><th>km / s</th></tr></thead>\n",
       "<thead><tr><th>int64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th></tr></thead>\n",
       "<tr><td>4660466371507774848</td><td>79.49100199261952</td><td>-66.41411777672668</td><td>2.6073927760139983</td><td>-1.1968907801968522</td><td>-0.13534455558687877</td><td>--</td></tr>\n",
       "<tr><td>4660498704031984000</td><td>80.19346436358076</td><td>-66.04907675232856</td><td>1.644062563874402</td><td>-1.954975321006136</td><td>-0.1774586376397</td><td>--</td></tr>\n",
       "<tr><td>4660458949824817024</td><td>79.68666778641992</td><td>-66.52220959662557</td><td>1.4777697275880581</td><td>0.3328961930362448</td><td>-0.030149510331454386</td><td>--</td></tr>\n",
       "<tr><td>4660451974773926528</td><td>79.89972073493868</td><td>-66.75037858071191</td><td>2.4635048563021065</td><td>-0.7474574729840501</td><td>-0.005219591141134416</td><td>--</td></tr>\n",
       "<tr><td>4660474033731357056</td><td>78.93214036467484</td><td>-66.46483644591667</td><td>1.2369118132455594</td><td>-1.7187143034638677</td><td>0.6018032937392243</td><td>--</td></tr>\n",
       "<tr><td>4660454105077874688</td><td>79.91045649235578</td><td>-66.68106846135971</td><td>1.4747855407533677</td><td>0.022464361420165786</td><td>-0.19949109843083218</td><td>--</td></tr>\n",
       "<tr><td>4660494855753740544</td><td>79.63101881952036</td><td>-66.15063315813536</td><td>1.6227863263222113</td><td>0.20490893261905152</td><td>0.0013030724292998944</td><td>--</td></tr>\n",
       "<tr><td>4660439536571308160</td><td>80.24817961417894</td><td>-66.46303270664092</td><td>1.8652105429518493</td><td>-0.5618584442373111</td><td>-0.10578442360531497</td><td>--</td></tr>\n",
       "<tr><td>4660470185440466560</td><td>79.25942306061864</td><td>-66.51120777549605</td><td>3.373561172003989</td><td>0.25326243152876704</td><td>-0.6932631338638376</td><td>--</td></tr>\n",
       "<tr><td>4660441460690365568</td><td>80.38862155241748</td><td>-66.34404494135046</td><td>1.6588478675146066</td><td>-0.09646951910977163</td><td>-0.2100859303087445</td><td>--</td></tr>\n",
       "</table>"
      ],
      "text/plain": [
       "<Table length=10>\n",
       "     source_id              ra        ...        parallax       radial_velocity\n",
       "                           deg        ...          mas               km / s    \n",
       "       int64             float64      ...        float64            float64    \n",
       "------------------- ----------------- ... --------------------- ---------------\n",
       "4660466371507774848 79.49100199261952 ...  -0.13534455558687877              --\n",
       "4660498704031984000 80.19346436358076 ...      -0.1774586376397              --\n",
       "4660458949824817024 79.68666778641992 ... -0.030149510331454386              --\n",
       "4660451974773926528 79.89972073493868 ... -0.005219591141134416              --\n",
       "4660474033731357056 78.93214036467484 ...    0.6018032937392243              --\n",
       "4660454105077874688 79.91045649235578 ...  -0.19949109843083218              --\n",
       "4660494855753740544 79.63101881952036 ... 0.0013030724292998944              --\n",
       "4660439536571308160 80.24817961417894 ...  -0.10578442360531497              --\n",
       "4660470185440466560 79.25942306061864 ...   -0.6932631338638376              --\n",
       "4660441460690365568 80.38862155241748 ...   -0.2100859303087445              --"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "results3 = job3.get_results()\n",
    "results3"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Good so far."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise\n",
    "\n",
    "This query always selects sources with `parallax` less than 1.  But suppose you want to take that upper bound as an input.\n",
    "\n",
    "Modify `query3_base` to replace `1` with a format specifier like `{max_parallax}`.  Now, when you call `format`, add a keyword argument that assigns a value to `max_parallax`, and confirm that the format specifier gets replaced with the value you provide."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "tags": [
     "hide-cell"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SELECT TOP 10\n",
      "source_id, ref_epoch, ra, dec, parallax\n",
      "FROM gaiadr2.gaia_source\n",
      "WHERE parallax < 1 \n",
      "  AND bp_rp BETWEEN -0.75 AND 2\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Solution\n",
    "\n",
    "query4_base = \"\"\"SELECT TOP 10\n",
    "{columns}\n",
    "FROM gaiadr2.gaia_source\n",
    "WHERE parallax < {max_parallax} AND \n",
    "bp_rp BETWEEN -0.75 AND 2\n",
    "\"\"\"\n",
    "\n",
    "query4 = query4_base.format(columns=columns,\n",
    "                            max_parallax=0.5)\n",
    "print(query)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Summary\n",
    "\n",
    "This notebook demonstrates the following steps:\n",
    "\n",
    "1. Making a connection to the Gaia server,\n",
    "\n",
    "2. Exploring information about the database and the tables it contains,\n",
    "\n",
    "3. Writing a query and sending it to the server, and finally\n",
    "\n",
    "4. Downloading the response from the server as an Astropy `Table`.\n",
    "\n",
    "In the next lesson we will extend these queries to select a particular region of the sky."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Best practices\n",
    "\n",
    "* If you can't download an entire dataset (or it's not practical) use queries to select the data you need.\n",
    "\n",
    "* Read the metadata and the documentation to make sure you understand the tables, their columns, and what they mean.\n",
    "\n",
    "* Develop queries incrementally: start with something simple, test it, and add a little bit at a time.\n",
    "\n",
    "* Use ADQL features like `TOP` and `COUNT` to test before you run a query that might return a lot of data.\n",
    "\n",
    "* If you know your query will return fewer than 3000 rows, you can run it synchronously, which might complete faster (but it doesn't seem to make much difference).  If it might return more than 3000 rows, you should run it asynchronously.\n",
    "\n",
    "* ADQL and SQL are not case-sensitive, so you don't have to capitalize the keywords, but you should.\n",
    "\n",
    "* ADQL and SQL don't require you to break a query into multiple lines, but you should.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Jupyter notebooks can be good for developing and testing code, but they have some drawbacks.  In particular, if you run the cells out of order, you might find that variables don't have the values you expect.\n",
    "\n",
    "There are a few things you can do to mitigate these problems:\n",
    "\n",
    "* Make each section of the notebook self-contained.  Try not to use the same variable name in more than one section.\n",
    "\n",
    "* Keep notebooks short.  Look for places where you can break your analysis into phases with one notebook per phase."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    ">One of the other tables we'll use is\n",
    "> `gaiadr2.panstarrs1_original_valid`.  Use `load_table` to get the\n",
    "> metadata for this table.  How many columns are there and what are\n",
    "> their names?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "celltoolbar": "Tags",
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
