{"id":23501,"date":"2023-09-03T18:34:52","date_gmt":"2023-09-03T18:34:52","guid":{"rendered":"https:\/\/machinelearningplus.com\/?p=23501"},"modified":"2023-09-13T17:39:00","modified_gmt":"2023-09-13T17:39:00","slug":"sql-subquery","status":"publish","type":"post","link":"https:\/\/machinelearningplus.com\/sql\/sql-subquery\/","title":{"rendered":"SQL Subquery &#8211; How to write subqueries using simple examples"},"content":{"rendered":"<p><strong>SQL Subquery, also known as inner query or nested query, are used to query data from one or more tables and then used in another SQL statement. They are an integral part of SQL since they allow complex database queries to be handled in a simpler way.<\/strong><\/p>\n<p>A subquery can be used in the <code>SELECT<\/code>, <code>INSERT<\/code>, <code>UPDATE<\/code>, or <code>DELETE<\/code> statement or inside another subquery. They are usually placed within parentheses and located in the <code>WHERE<\/code> or <code>HAVING<\/code> clause.<\/p>\n<p>Let&#8217;s take an example to illustrate the concept of subqueries.<\/p>\n<p><em><strong>Also Read | <a href=\"https:\/\/machinelearningplus.com\/sql\/sql-tutorial\/\">SQL Tutorial &#8211; A Simple and Intuitive Guide<\/a><\/strong><\/em><\/p>\n<p><a href=\"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2023\/09\/sql-subqueries_small.jpg\"><img fetchpriority=\"high\" decoding=\"async\" src=\"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2023\/09\/sql-subqueries_small-1024x678.jpg\" alt=\"\" width=\"1024\" height=\"678\" class=\"aligncenter size-large wp-image-23668\" srcset=\"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2023\/09\/sql-subqueries_small-1024x678.jpg 1024w, https:\/\/machinelearningplus.com\/wp-content\/uploads\/2023\/09\/sql-subqueries_small-300x199.jpg 300w, https:\/\/machinelearningplus.com\/wp-content\/uploads\/2023\/09\/sql-subqueries_small-768x508.jpg 768w, https:\/\/machinelearningplus.com\/wp-content\/uploads\/2023\/09\/sql-subqueries_small.jpg 1358w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/a><\/p>\n<p>In this lesson we will cover:<\/p>\n<ol>\n<li><a href=\"#UnderstandingtheneedforSQLSubquerywithanexample\">Understanding the need for SQL Subquery with an example<\/a><\/li>\n<li><a href=\"#SolutionApproach\">Solution Approach<\/a><\/li>\n<li><a href=\"#SubQuery-Tougherexample1\">Sub Query &#8211; Tougher example 1<\/a><\/li>\n<li><a href=\"#Solutionusingaseparatetablewithoutsubquery\">Solution using a separate table (without subquery)<\/a><\/li>\n<li><a href=\"#SolutionusingSubQueryApproach\">Solution using Sub Query Approach<\/a><\/li>\n<li><a href=\"#SubQuery-TougherExample2\">Sub Query &#8211; Tougher Example 2<\/a><\/li>\n<li><a href=\"#Solvebyapplyingsubquery\">Solve by applying subquery<\/a><\/li>\n<\/ol>\n<h2>1. <a name='UnderstandingtheneedforSQLSubquerywithanexample'><\/a>Understanding the need for SQL Subqueries<\/h2>\n<p>There are certain situations where you will absolutely need to write a Subquery. This will be clear if you understand with an example.<\/p>\n<p>Consider the following three tables, the contents of which is shown below in code blocks.<\/p>\n<ol>\n<li><strong>Employees<\/strong><\/li>\n<li><strong>Departments<\/strong><\/li>\n<li><strong>Sales<\/strong><\/li>\n<\/ol>\n<p>Question: <strong>Find out the employees who earn more than the overall average salary.<\/strong><\/p>\n<p>These tables can be created in SQLite DB using this <a href=\"https:\/\/gist.github.com\/machinelearningplus\/09d40dcbf49c513e4114c91af772e748\">schema<\/a>.<\/p>\n<p><strong>Let&#8217;s print the contents of the tables<\/strong><\/p>\n<p>The <code>Employees table<\/code><\/p>\n<pre><code class=\"language-sql\">SELECT * from Employees;\n<\/code><\/pre>\n<table>\n<thead>\n<tr>\n<th>ID<\/th>\n<th>Name<\/th>\n<th>Salary<\/th>\n<th>DepartmentID<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>1<\/td>\n<td>Alice<\/td>\n<td>35000<\/td>\n<td>1<\/td>\n<\/tr>\n<tr>\n<td>2<\/td>\n<td>Bob<\/td>\n<td>40000<\/td>\n<td>2<\/td>\n<\/tr>\n<tr>\n<td>3<\/td>\n<td>Carol<\/td>\n<td>55000<\/td>\n<td>3<\/td>\n<\/tr>\n<tr>\n<td>4<\/td>\n<td>David<\/td>\n<td>60000<\/td>\n<td>2<\/td>\n<\/tr>\n<tr>\n<td>5<\/td>\n<td>Ethan<\/td>\n<td>70000<\/td>\n<td>1<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>The <code>Departments<\/code> table<\/p>\n<pre><code class=\"language-sql\">SELECT * from Departments;\n<\/code><\/pre>\n<table>\n<thead>\n<tr>\n<th>ID<\/th>\n<th>Name<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>1<\/td>\n<td>HR<\/td>\n<\/tr>\n<tr>\n<td>2<\/td>\n<td>Finance<\/td>\n<\/tr>\n<tr>\n<td>3<\/td>\n<td>Marketing<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>The <code>Sales<\/code> table.<\/p>\n<pre><code class=\"language-sql\">SELECT * from Sales;\n<\/code><\/pre>\n<table>\n<thead>\n<tr>\n<th>EmployeeID<\/th>\n<th>Product<\/th>\n<th>Quantity<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>1<\/td>\n<td>A<\/td>\n<td>10<\/td>\n<\/tr>\n<tr>\n<td>1<\/td>\n<td>B<\/td>\n<td>5<\/td>\n<\/tr>\n<tr>\n<td>2<\/td>\n<td>A<\/td>\n<td>7<\/td>\n<\/tr>\n<tr>\n<td>2<\/td>\n<td>C<\/td>\n<td>3<\/td>\n<\/tr>\n<tr>\n<td>3<\/td>\n<td>B<\/td>\n<td>8<\/td>\n<\/tr>\n<tr>\n<td>3<\/td>\n<td>C<\/td>\n<td>2<\/td>\n<\/tr>\n<tr>\n<td>4<\/td>\n<td>A<\/td>\n<td>9<\/td>\n<\/tr>\n<tr>\n<td>4<\/td>\n<td>B<\/td>\n<td>6<\/td>\n<\/tr>\n<tr>\n<td>5<\/td>\n<td>C<\/td>\n<td>4<\/td>\n<\/tr>\n<tr>\n<td>5<\/td>\n<td>A<\/td>\n<td>3<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>Remember, we want to find out the employees who earn <em>more than<\/em> the overall average salary.<\/p>\n<h2>2. <a name='SolutionApproach'><\/a>Solution Approach<\/h2>\n<p>To solve this, we select the <code>name<\/code> and <code>salary<\/code> from <code>Employees<\/code> table. But we need only the employees salaries that are more than the average.<\/p>\n<p>So the plan is to use the <code>WHERE<\/code> condition, to filter those observations where salary is more than average.<\/p>\n<p>Let&#8217;s try it out.<\/p>\n<pre><code class=\"language-sql\">SELECT Name, Salary \nFROM Employees E1\nWHERE Salary &gt; AVG(Salary);\n<\/code><\/pre>\n<p>But this does NOT work!<\/p>\n<p>This operation errors out giving an operational error &#8211; &#8220;Misuse of AVG(Salary) function&#8221;.<\/p>\n<p><strong>Why?<\/strong><\/p>\n<p>Since AVG() is a group function, <strong>you can only use it in a <code>SELECT<\/code> statement or in a <code>HAVING<\/code> clause.<\/strong><\/p>\n<p>\nThis is quite important to understand.<br \/>\n<\/p>\n<p>So, how do we tackle this?<\/p>\n<p>We need to use Subquery.<\/p>\n<p>This can be done using two approaches.<\/p>\n<p><strong>Approach 1:<\/strong> Create query to compute the average and store in a new table. Then, reference it as a subquery.<\/p>\n<p><strong>Approach 2:<\/strong> Direct sub query<\/p>\n<p>Let&#8217;s see both approaches.<\/p>\n<h3><strong>APPROACH 1:<\/strong><\/h3>\n<p><--PAUSE AND THINK ABOUT HOW YOU WOULD DO APPROACH 1 --><\/p>\n<p>Use this <a href=\"https:\/\/www.db-fiddle.com\/f\/cipaAsuKR19KG8wtbUuogT\/0\">link to solve hands-on<\/a>.<\/p>\n<ol>\n<li>Create a new table that will contain the average salary.<\/li>\n<\/ol>\n<pre><code class=\"language-sql\">DROP TABLE IF EXISTS AVGSALARY;\n\nCREATE TABLE AVGSALARY AS\nSELECT AVG(salary) as AVG_SALARY\nFROM EMPLOYEES;\n\nSELECT * FROM AVGSALARY;\n<\/code><\/pre>\n<table>\n<thead>\n<tr>\n<th>AVG_SALARY<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>52000.0<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>Now, let&#8217;s write the query in the WHERE condition to check if the <code>SALARY &gt; AVG(SALARY)<\/code>.<\/p>\n<pre><code class=\"language-sql\">SELECT Name, Salary \nFROM Employees E1\nWHERE Salary &gt; (SELECT AVG_SALARY from AVGSALARY);\n<\/code><\/pre>\n<table>\n<thead>\n<tr>\n<th>Name<\/th>\n<th>Salary<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Carol<\/td>\n<td>55000<\/td>\n<\/tr>\n<tr>\n<td>David<\/td>\n<td>60000<\/td>\n<\/tr>\n<tr>\n<td>Ethan<\/td>\n<td>70000<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3><strong>APPROACH 2: Directly subquery from the employees table<\/strong><\/h3>\n<p>Alternately, you can directly subquery it instead of storing the average value in a separate table.<\/p>\n<pre><code class=\"language-sql\">SELECT Name, Salary \nFROM Employees E1\nWHERE Salary &gt; (SELECT AVG(SALARY) from Employees);\n<\/code><\/pre>\n<table>\n<thead>\n<tr>\n<th>Name<\/th>\n<th>Salary<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Carol<\/td>\n<td>55000<\/td>\n<\/tr>\n<tr>\n<td>David<\/td>\n<td>60000<\/td>\n<\/tr>\n<tr>\n<td>Ethan<\/td>\n<td>70000<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>Hope you got the idea behind the need for Subqueries. Now, let&#8217;s look at a slightly tougher example.<\/p>\n<p>In above example, we selected employees whose salary was above overall average. <em>What if you want to select employees whose salary is above their respective department average?<\/em><\/p>\n<h2>3. <a name='SubQuery-Tougherexample1'><\/a>Sub Query &#8211; Tougher example 1<\/h2>\n<p><strong>Task:<\/strong> Find out the employees who earn more than (or equal to) the average salary <em>in their respective department<\/em>.<\/p>\n<p>To do this, we select the name and salary from Employees table. But we need only the employees salaries that are more than the average <em>in their respective department..<\/em><\/p>\n<p>So in WHERE condition, we need to filter those observations where salary is more than the department average and NOT the total average.<\/p>\n<p>Let&#8217;s first find the department average.<\/p>\n<h2>4. <a name='Solutionusingaseparatetablewithoutsubquery'><\/a>Solution using a separate table (without subquery)<\/h2>\n<p>Let&#8217;s first try to solve this without a subquery first. Then we will attempt to create the subquery.<br \/>\nThat way, you will be clear how subquery works.<\/p>\n<p>In the beginning, it is a good idea to create intermediate temp tables to store the result, just to make sure your query does what it is meant to do. You can create such temp tables, verify the values and drop the tables when they are no longer needed.<\/p>\n<p><strong>Approach 1<\/strong>:<br \/>\n1. Step 1: Create a new table that will hold the average department salaries.<br \/>\n2. Step 2: Merge this table with the Employees table<br \/>\n3. Step 3: Do the filtering.<\/p>\n<p><strong>First, Print the Employees table<\/strong><\/p>\n<pre><code class=\"language-sql\">SELECT * FROM EMPLOYEES;\n<\/code><\/pre>\n<table>\n<thead>\n<tr>\n<th>ID<\/th>\n<th>Name<\/th>\n<th>Salary<\/th>\n<th>DepartmentID<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>1<\/td>\n<td>Alice<\/td>\n<td>35000<\/td>\n<td>1<\/td>\n<\/tr>\n<tr>\n<td>2<\/td>\n<td>Bob<\/td>\n<td>40000<\/td>\n<td>2<\/td>\n<\/tr>\n<tr>\n<td>3<\/td>\n<td>Carol<\/td>\n<td>55000<\/td>\n<td>3<\/td>\n<\/tr>\n<tr>\n<td>4<\/td>\n<td>David<\/td>\n<td>60000<\/td>\n<td>2<\/td>\n<\/tr>\n<tr>\n<td>5<\/td>\n<td>Ethan<\/td>\n<td>70000<\/td>\n<td>1<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p><strong>Compute the Average Salary by Department (in a new table)<\/strong><\/p>\n<pre><code class=\"language-sql\">DROP TABLE IF EXISTS DEPARTMENTSALARY;\n\nCREATE TABLE DEPARTMENTSALARY AS\nSELECT  DEPARTMENTID, \n        AVG(SALARY) as AVG_SALARY\nFROM EMPLOYEES\nGROUP BY DepartmentID;\n<\/code><\/pre>\n<p><strong>Show DepartmentSalary Table<\/strong><\/p>\n<pre><code class=\"language-sql\">SELECT * FROM DEPARTMENTSALARY;\n<\/code><\/pre>\n<table>\n<thead>\n<tr>\n<th>DepartmentID<\/th>\n<th>AVG_SALARY<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>1<\/td>\n<td>52500.0<\/td>\n<\/tr>\n<tr>\n<td>2<\/td>\n<td>50000.0<\/td>\n<\/tr>\n<tr>\n<td>3<\/td>\n<td>55000.0<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p><strong>Merge this with the Employees Table<\/strong><\/p>\n<pre><code class=\"language-sql\">SELECT A.*, B.AVG_SALARY\nFROM EMPLOYEES as A\nLEFT JOIN \nDEPARTMENTSALARY as B \nON A.DepartmentID = B.DepartmentID;\n<\/code><\/pre>\n<table>\n<thead>\n<tr>\n<th>ID<\/th>\n<th>Name<\/th>\n<th>Salary<\/th>\n<th>DepartmentID<\/th>\n<th>AVG_SALARY<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>1<\/td>\n<td>Alice<\/td>\n<td>35000<\/td>\n<td>1<\/td>\n<td>52500.0<\/td>\n<\/tr>\n<tr>\n<td>2<\/td>\n<td>Bob<\/td>\n<td>40000<\/td>\n<td>2<\/td>\n<td>50000.0<\/td>\n<\/tr>\n<tr>\n<td>3<\/td>\n<td>Carol<\/td>\n<td>55000<\/td>\n<td>3<\/td>\n<td>55000.0<\/td>\n<\/tr>\n<tr>\n<td>4<\/td>\n<td>David<\/td>\n<td>60000<\/td>\n<td>2<\/td>\n<td>50000.0<\/td>\n<\/tr>\n<tr>\n<td>5<\/td>\n<td>Ethan<\/td>\n<td>70000<\/td>\n<td>1<\/td>\n<td>52500.0<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p><strong>Now, Let&#8217;s filter out salaries less than dept salaries<\/strong><\/p>\n<pre><code class=\"language-sql\">SELECT A.NAME, A.SALARY\nFROM EMPLOYEES as A\nLEFT JOIN \nDEPARTMENTSALARY as B \nON A.DepartmentID = B.DepartmentID \nWHERE SALARY &gt;= AVG_SALARY;\n<\/code><\/pre>\n<table>\n<thead>\n<tr>\n<th>Name<\/th>\n<th>Salary<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Carol<\/td>\n<td>55000<\/td>\n<\/tr>\n<tr>\n<td>David<\/td>\n<td>60000<\/td>\n<\/tr>\n<tr>\n<td>Ethan<\/td>\n<td>70000<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>So, that&#8217;s the step by step logic.<\/p>\n<p>How do we do it without having to create a new table as seen in 1 Step?<\/p>\n<h2>5. <a name='SolutionusingSubQueryApproach'><\/a>Solution using Sub Query Approach<\/h2>\n<p>Observe the <code>WHERE<\/code> condition here. Let&#8217;s try to make sense of it.<\/p>\n<pre><code class=\"language-sql\">SELECT E1.Name, E1.Salary \nFROM Employees E1\nWHERE Salary &gt;= (\n    SELECT AVG(E2.Salary) \n    FROM Employees E2\n    WHERE E1.DepartmentID = E2.DepartmentID\n);\n<\/code><\/pre>\n<table>\n<thead>\n<tr>\n<th>Name<\/th>\n<th>Salary<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Carol<\/td>\n<td>55000<\/td>\n<\/tr>\n<tr>\n<td>David<\/td>\n<td>60000<\/td>\n<\/tr>\n<tr>\n<td>Ethan<\/td>\n<td>70000<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p><strong>How to understand this query?<\/strong><\/p>\n<p>We want to select those salaries that are greater than department average. So, we need to apply this in this WHERE clause.<\/p>\n<p>Think of it like this:<\/p>\n<p>The filter condition applied in the WHERE clause gets applied to every row of the table. So, the query gets evaluated for every row to compute the department average.<\/p>\n<p>The subquery <code>SELECT AVG(Salary) FROM Employees GROUP BY DepartmentID<\/code> will first calculate the average salary for each department. Then the outer query will compare each employee&#8217;s salary with the average salary of their respective department and return those who earn more than the average.<\/p>\n<h2>6. <a name='SubQuery-TougherExample2'><\/a>Sub Query &#8211; Tougher Example 2<\/h2>\n<p><strong>Task:<\/strong> Find out the employees who sold Product A AND sold more than the average quantity sold by all employees.<\/p>\n<p>How to solve this?<\/p>\n<p>To do this, this query requires information about both product as well as employees. This information does not lie in one table.<\/p>\n<p>So, first step is to <strong>&#8220;Figure out what tables the data you need resides in.&#8221;<\/strong><\/p>\n<p>We have the following Tables:<\/p>\n<ol>\n<li>Sales (EmployeeID, Product, Quantity)<\/li>\n<li>Departments (ID, Name)<\/li>\n<li>Employees (ID, Name, Salary, DepartmentID)<\/li>\n<\/ol>\n<p>Sales contains the <code>EmployeeID<\/code> but the <code>EmployeeName<\/code> has to come from the <code>Employees<\/code> table.<\/p>\n<p><---PAUSE AND THINK HOW TO SOLVE FOR NEXT 120 seconds.---><\/p>\n<p>SOLVE HandsOn <a href=\"https:\/\/www.db-fiddle.com\/f\/cipaAsuKR19KG8wtbUuogT\/0\">here<\/a>.<\/p>\n<h2>7. Solve by applying subquery<\/h2>\n<p><strong>Steps:<\/strong><\/p>\n<ol>\n<li>First, find the total quantity sold by each employee, for product A.<\/li>\n<li>Then Filter those records greater than avg quantity sold.<\/li>\n<\/ol>\n<p><strong>First, Compute average total quantity sold by each employee for product A<\/strong><\/p>\n<pre><code class=\"language-sql\">SELECT  E.Name, \n        S.Product, \n        SUM(S.Quantity) as TotalQuantity\nFROM Employees E\nJOIN Sales S ON E.ID = S.EmployeeID\nWHERE S.PRODUCT = \"A\"\nGROUP BY E.Name, S.Product;\n<\/code><\/pre>\n<table>\n<thead>\n<tr>\n<th>Name<\/th>\n<th>Product<\/th>\n<th>TotalQuantity<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Alice<\/td>\n<td>A<\/td>\n<td>10<\/td>\n<\/tr>\n<tr>\n<td>Bob<\/td>\n<td>A<\/td>\n<td>7<\/td>\n<\/tr>\n<tr>\n<td>David<\/td>\n<td>A<\/td>\n<td>9<\/td>\n<\/tr>\n<tr>\n<td>Ethan<\/td>\n<td>A<\/td>\n<td>3<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p><strong>Then, filter those records where the Total Quantity (of product A) sold by an employees is greater than total average (of product A) sold by an employee?<\/strong><\/p>\n<pre><code class=\"language-sql\">SELECT  E.Name, \n        S.Product, \n        SUM(S.Quantity) as TotalQuantity\nFROM Employees E\nJOIN Sales S ON E.ID = S.EmployeeID\nWHERE S.PRODUCT = \"A\"\nGROUP BY E.Name, S.Product\nHAVING TotalQuantity &gt; (\"Average of total qty of prdt A sold by an employee\")\n);\n<\/code><\/pre>\n<p>Now, We need to compute &#8220;Average of total qty of prdt A sold by an employee&#8221;.<\/p>\n<p>So, first compute total qty of product A sold by each employee. Then compute the average.<\/p>\n<pre><code class=\"language-sql\">SELECT SUM(QUANTITY) \nFROM SALES \nWHERE PRODUCT=\"A\" \nGROUP BY EMPLOYEEID;\n<\/code><\/pre>\n<table>\n<thead>\n<tr>\n<th>SUM(QUANTITY)<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>10<\/td>\n<\/tr>\n<tr>\n<td>7<\/td>\n<\/tr>\n<tr>\n<td>9<\/td>\n<\/tr>\n<tr>\n<td>3<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>But we want the average of these. So, put a query above this.<\/p>\n<pre><code class=\"language-sql\">SELECT AVG(SUMQTY) as AVG_A\nFROM (SELECT SUM(QUANTITY) as SUMQTY \n      FROM SALES \n      WHERE PRODUCT=\"A\"\n      GROUP BY EMPLOYEEID)\n<\/code><\/pre>\n<table>\n<thead>\n<tr>\n<th>AVG_A<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>7.25<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p><strong>Now, apply this subquery inside the main query<\/strong><\/p>\n<pre><code class=\"language-sql\">SELECT  E.Name, \n        S.Product, \n        SUM(S.Quantity) as TotalQuantity\nFROM Employees E\nJOIN Sales S ON E.ID = S.EmployeeID\nWHERE S.PRODUCT = \"A\"\nGROUP BY E.Name, S.Product\nHAVING TotalQuantity &gt; (SELECT AVG(SUMQTY) as AVG_A \n                        FROM (SELECT SUM(QUANTITY) as SUMQTY \n                              FROM SALES \n                              WHERE PRODUCT=\"A\"\n                              GROUP BY EMPLOYEEID) as subquery\n);\n<\/code><\/pre>\n<table>\n<thead>\n<tr>\n<th>Name<\/th>\n<th>Product<\/th>\n<th>TotalQuantity<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Alice<\/td>\n<td>A<\/td>\n<td>10<\/td>\n<\/tr>\n<tr>\n<td>David<\/td>\n<td>A<\/td>\n<td>9<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>Here, the subquery calculates the average quantity sold of product &#8216;A&#8217; by all employees. Then the outer query sums up the quantity of product &#8216;A&#8217; sold by each employee and compares it with the average quantity calculated by the subquery.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>SQL Subquery, also known as inner query or nested query, are used to query data from one or more tables and then used in another SQL statement. They are an integral part of SQL since they allow complex database queries to be handled in a simpler way. A subquery can be used in the SELECT, [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":24001,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"site-sidebar-layout":"default","site-content-layout":"default","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"default","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[2091],"tags":[],"class_list":["post-23501","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-sql"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.0 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>SQL Subquery - How to write subqueries using simple examples | ML+<\/title>\n<meta name=\"description\" content=\"SQL Subquery, also known as inner queries or nested queries, are used to query data from one or more tables and then used in another SQL statement.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/localhost:8080\/sql\/sql-subquery\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"SQL Subquery - How to write subqueries using simple examples | ML+\" \/>\n<meta property=\"og:description\" content=\"SQL Subquery, also known as inner queries or nested queries, are used to query data from one or more tables and then used in another SQL statement.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/localhost:8080\/sql\/sql-subquery\/\" \/>\n<meta property=\"og:site_name\" content=\"machinelearningplus\" \/>\n<meta property=\"article:author\" content=\"https:\/\/www.facebook.com\/rtipaday\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-09-03T18:34:52+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-09-13T17:39:00+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/localhost:8080\/wp-content\/uploads\/2023\/09\/SQL-Subquery.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1080\" \/>\n\t<meta property=\"og:image:height\" content=\"1080\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Selva Prabhakaran\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/R_Programming\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Selva Prabhakaran\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"8 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"TechArticle\",\"@id\":\"https:\\\/\\\/localhost:8080\\\/sql\\\/sql-subquery\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/localhost:8080\\\/sql\\\/sql-subquery\\\/\"},\"author\":{\"name\":\"Selva Prabhakaran\",\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#\\\/schema\\\/person\\\/510885c0515804366fa644c38258391e\"},\"headline\":\"SQL Subquery &#8211; How to write subqueries using simple examples\",\"datePublished\":\"2023-09-03T18:34:52+00:00\",\"dateModified\":\"2023-09-13T17:39:00+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/localhost:8080\\\/sql\\\/sql-subquery\\\/\"},\"wordCount\":1198,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/localhost:8080\\\/sql\\\/sql-subquery\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/uploads\\\/2023\\\/09\\\/SQL-Subquery.png\",\"articleSection\":[\"SQL\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/localhost:8080\\\/sql\\\/sql-subquery\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/localhost:8080\\\/sql\\\/sql-subquery\\\/\",\"url\":\"https:\\\/\\\/localhost:8080\\\/sql\\\/sql-subquery\\\/\",\"name\":\"SQL Subquery - How to write subqueries using simple examples | ML+\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/localhost:8080\\\/sql\\\/sql-subquery\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/localhost:8080\\\/sql\\\/sql-subquery\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/uploads\\\/2023\\\/09\\\/SQL-Subquery.png\",\"datePublished\":\"2023-09-03T18:34:52+00:00\",\"dateModified\":\"2023-09-13T17:39:00+00:00\",\"description\":\"SQL Subquery, also known as inner queries or nested queries, are used to query data from one or more tables and then used in another SQL statement.\",\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/localhost:8080\\\/sql\\\/sql-subquery\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/localhost:8080\\\/sql\\\/sql-subquery\\\/#primaryimage\",\"url\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/uploads\\\/2023\\\/09\\\/SQL-Subquery.png\",\"contentUrl\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/uploads\\\/2023\\\/09\\\/SQL-Subquery.png\",\"width\":1080,\"height\":1080,\"caption\":\"SQL Subquery\"},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#website\",\"url\":\"https:\\\/\\\/machinelearningplus.com\\\/\",\"name\":\"machinelearningplus\",\"description\":\"Learn Data Science (AI \\\/ ML) Online\",\"publisher\":{\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/machinelearningplus.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#organization\",\"name\":\"machinelearningplus\",\"url\":\"https:\\\/\\\/machinelearningplus.com\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/uploads\\\/2022\\\/05\\\/MachineLearningplus-logo.svg\",\"contentUrl\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/uploads\\\/2022\\\/05\\\/MachineLearningplus-logo.svg\",\"width\":348,\"height\":36,\"caption\":\"machinelearningplus\"},\"image\":{\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#\\\/schema\\\/logo\\\/image\\\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#\\\/schema\\\/person\\\/510885c0515804366fa644c38258391e\",\"name\":\"Selva Prabhakaran\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/litespeed\\\/avatar\\\/a994280177da541405c016f593e86ea7.jpg?ver=1783622267\",\"url\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/litespeed\\\/avatar\\\/a994280177da541405c016f593e86ea7.jpg?ver=1783622267\",\"contentUrl\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/litespeed\\\/avatar\\\/a994280177da541405c016f593e86ea7.jpg?ver=1783622267\",\"caption\":\"Selva Prabhakaran\"},\"description\":\"Selva is an experienced Data Scientist and leader, specializing in executing AI projects for large companies. Selva started machinelearningplus to make Data Science \\\/ ML \\\/ AI accessible to everyone. The website enjoys 4 Million+ readership. His courses, lessons, and videos are loved by hundreds of thousands of students and practitioners.\",\"sameAs\":[\"https:\\\/\\\/localhost:8080\\\/\",\"https:\\\/\\\/www.facebook.com\\\/rtipaday\\\/\",\"https:\\\/\\\/x.com\\\/https:\\\/\\\/twitter.com\\\/R_Programming\"],\"url\":\"https:\\\/\\\/machinelearningplus.com\\\/author\\\/selva86\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"SQL Subquery - How to write subqueries using simple examples | ML+","description":"SQL Subquery, also known as inner queries or nested queries, are used to query data from one or more tables and then used in another SQL statement.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/localhost:8080\/sql\/sql-subquery\/","og_locale":"en_US","og_type":"article","og_title":"SQL Subquery - How to write subqueries using simple examples | ML+","og_description":"SQL Subquery, also known as inner queries or nested queries, are used to query data from one or more tables and then used in another SQL statement.","og_url":"https:\/\/localhost:8080\/sql\/sql-subquery\/","og_site_name":"machinelearningplus","article_author":"https:\/\/www.facebook.com\/rtipaday\/","article_published_time":"2023-09-03T18:34:52+00:00","article_modified_time":"2023-09-13T17:39:00+00:00","og_image":[{"width":1080,"height":1080,"url":"https:\/\/localhost:8080\/wp-content\/uploads\/2023\/09\/SQL-Subquery.png","type":"image\/png"}],"author":"Selva Prabhakaran","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/R_Programming","twitter_misc":{"Written by":"Selva Prabhakaran","Est. reading time":"8 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"TechArticle","@id":"https:\/\/localhost:8080\/sql\/sql-subquery\/#article","isPartOf":{"@id":"https:\/\/localhost:8080\/sql\/sql-subquery\/"},"author":{"name":"Selva Prabhakaran","@id":"https:\/\/machinelearningplus.com\/#\/schema\/person\/510885c0515804366fa644c38258391e"},"headline":"SQL Subquery &#8211; How to write subqueries using simple examples","datePublished":"2023-09-03T18:34:52+00:00","dateModified":"2023-09-13T17:39:00+00:00","mainEntityOfPage":{"@id":"https:\/\/localhost:8080\/sql\/sql-subquery\/"},"wordCount":1198,"commentCount":0,"publisher":{"@id":"https:\/\/machinelearningplus.com\/#organization"},"image":{"@id":"https:\/\/localhost:8080\/sql\/sql-subquery\/#primaryimage"},"thumbnailUrl":"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2023\/09\/SQL-Subquery.png","articleSection":["SQL"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/localhost:8080\/sql\/sql-subquery\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/localhost:8080\/sql\/sql-subquery\/","url":"https:\/\/localhost:8080\/sql\/sql-subquery\/","name":"SQL Subquery - How to write subqueries using simple examples | ML+","isPartOf":{"@id":"https:\/\/machinelearningplus.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/localhost:8080\/sql\/sql-subquery\/#primaryimage"},"image":{"@id":"https:\/\/localhost:8080\/sql\/sql-subquery\/#primaryimage"},"thumbnailUrl":"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2023\/09\/SQL-Subquery.png","datePublished":"2023-09-03T18:34:52+00:00","dateModified":"2023-09-13T17:39:00+00:00","description":"SQL Subquery, also known as inner queries or nested queries, are used to query data from one or more tables and then used in another SQL statement.","inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/localhost:8080\/sql\/sql-subquery\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/localhost:8080\/sql\/sql-subquery\/#primaryimage","url":"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2023\/09\/SQL-Subquery.png","contentUrl":"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2023\/09\/SQL-Subquery.png","width":1080,"height":1080,"caption":"SQL Subquery"},{"@type":"WebSite","@id":"https:\/\/machinelearningplus.com\/#website","url":"https:\/\/machinelearningplus.com\/","name":"machinelearningplus","description":"Learn Data Science (AI \/ ML) Online","publisher":{"@id":"https:\/\/machinelearningplus.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/machinelearningplus.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/machinelearningplus.com\/#organization","name":"machinelearningplus","url":"https:\/\/machinelearningplus.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/machinelearningplus.com\/#\/schema\/logo\/image\/","url":"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2022\/05\/MachineLearningplus-logo.svg","contentUrl":"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2022\/05\/MachineLearningplus-logo.svg","width":348,"height":36,"caption":"machinelearningplus"},"image":{"@id":"https:\/\/machinelearningplus.com\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/machinelearningplus.com\/#\/schema\/person\/510885c0515804366fa644c38258391e","name":"Selva Prabhakaran","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/machinelearningplus.com\/wp-content\/litespeed\/avatar\/a994280177da541405c016f593e86ea7.jpg?ver=1783622267","url":"https:\/\/machinelearningplus.com\/wp-content\/litespeed\/avatar\/a994280177da541405c016f593e86ea7.jpg?ver=1783622267","contentUrl":"https:\/\/machinelearningplus.com\/wp-content\/litespeed\/avatar\/a994280177da541405c016f593e86ea7.jpg?ver=1783622267","caption":"Selva Prabhakaran"},"description":"Selva is an experienced Data Scientist and leader, specializing in executing AI projects for large companies. Selva started machinelearningplus to make Data Science \/ ML \/ AI accessible to everyone. The website enjoys 4 Million+ readership. His courses, lessons, and videos are loved by hundreds of thousands of students and practitioners.","sameAs":["https:\/\/localhost:8080\/","https:\/\/www.facebook.com\/rtipaday\/","https:\/\/x.com\/https:\/\/twitter.com\/R_Programming"],"url":"https:\/\/machinelearningplus.com\/author\/selva86\/"}]}},"_links":{"self":[{"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/posts\/23501","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/comments?post=23501"}],"version-history":[{"count":0,"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/posts\/23501\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/media\/24001"}],"wp:attachment":[{"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/media?parent=23501"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/categories?post=23501"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/tags?post=23501"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}