{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Overview of Sub Queries\n",
"Let us understand details related to Sub Queries. We will also briefly discuss about nested sub queries."
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"tags": [
"remove-cell"
]
},
"outputs": [
{
"data": {
"text/html": [
"\n"
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"%%HTML\n",
""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* We can have queries in from clause and such queries are called as sub queries.\n",
"* Sub queries are commonly used with queries using analytic functions to filter the data further. We will see details after going through analytic functions as part of this section.\n",
"* It is mandatory to have alias for the sub query.\n",
"* Sub queries can also be used in `WHERE` clause with `IN` as well as `EXISTS`. As part of the sub query we can have join like conditions between tables in `FROM` clause of the main query and sub query. Such queries are called as **Nested Sub Queries**."
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The sql extension is already loaded. To reload it, use:\n",
" %reload_ext sql\n"
]
}
],
"source": [
"%load_ext sql"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"env: DATABASE_URL=postgresql://itversity_retail_user:retail_password@localhost:5432/itversity_retail_db\n"
]
}
],
"source": [
"%env DATABASE_URL=postgresql://itversity_retail_user:retail_password@localhost:5432/itversity_retail_db"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"```{note}\n",
"Simplest example for a subquery\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" * postgresql://itversity_retail_user:***@localhost:5432/itversity_retail_db\n",
"1 rows affected.\n"
]
},
{
"data": {
"text/html": [
"
\n",
"
\n",
"
current_date
\n",
"
\n",
"
\n",
"
2020-12-01
\n",
"
\n",
"
"
],
"text/plain": [
"[(datetime.date(2020, 12, 1),)]"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"%%sql\n",
"\n",
"SELECT * FROM (SELECT current_date) AS q"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"```{note}\n",
"Realistic example for a subquery. We will get into details related to this query after covering analytic functions\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" * postgresql://itversity_retail_user:***@localhost:5432/itversity_retail_db\n",
"20 rows affected.\n"
]
},
{
"data": {
"text/html": [
"