{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Create A View\n", "\n", "We can store a query in the database as a view.\n", "\n", "Let's imagine that we often need the record set that gives maximum and minimum pressure by country.\n", "\n", "Here's the SQL from the previous chapter that generated it:\n", "\n", "```sql\n", "SELECT\n", " f.country_code,\n", " MAX(r.temp) AS max_temp,\n", " MIN(r.temp) AS min_temp\n", "FROM readings AS r JOIN flights AS f\n", " ON r.flight = f.name\n", "GROUP BY f.country_code\n", "```\n", "\n", "Let's use this to create view. First we connect to our database:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import sqlalchemy as sa\n", "import pandas as pd\n", "engine = sa.create_engine('sqlite:///flight.db')\n", "connection = engine.connect()\n", "connection.execute(\"PRAGMA foreign_keys=on\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And then, with one extra clause, we create our view:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sql = \"\"\"\n", " CREATE VIEW max_min_temp_by_country AS\n", " SELECT\n", " f.country_code,\n", " MAX(r.temp) AS max_temp,\n", " MIN(r.temp) AS min_temp\n", " FROM readings AS r JOIN flights AS f\n", " ON r.flight = f.name\n", " GROUP BY f.country_code\n", "\"\"\"\n", "connection.execute(sql)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can include the view in a SELECT statement in exactly the same way as a table:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
country_codemax_tempmin_temp
0GB26.923
\n", "
" ], "text/plain": [ " country_code max_temp min_temp\n", "0 GB 26.9 23" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sql = \"\"\"\n", " SELECT *\n", " FROM max_min_temp_by_country\n", " WHERE country_code = 'GB'\n", "\"\"\"\n", "pd.read_sql(sql, connection)" ] } ], "metadata": { "kernelspec": { "display_name": "Python [conda env:sql_python_tutorial]", "language": "python", "name": "conda-env-sql_python_tutorial-py" }, "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.6.5" } }, "nbformat": 4, "nbformat_minor": 2 }