{"id":1472,"date":"2013-02-02T22:29:34","date_gmt":"2013-02-03T06:29:34","guid":{"rendered":"http:\/\/www.mysqltutorial.org\/?page_id=1472"},"modified":"2023-12-31T03:18:33","modified_gmt":"2023-12-31T10:18:33","slug":"mysql-subquery","status":"publish","type":"page","link":"https:\/\/www.mysqltutorial.org\/mysql-basics\/mysql-subquery\/","title":{"rendered":"MySQL Subquery"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you will learn how to use the MySQL subquery to write complex queries and understand the correlated subquery concept.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to the MySQL Subquery<\/h2>\n\n\n\n<p>A MySQL subquery is a query nested within another query such as&nbsp;<a href=\"https:\/\/www.mysqltutorial.org\/mysql-basics\/mysql-select-from\/\"><code>SELECT<\/code><\/a>, <a href=\"https:\/\/www.mysqltutorial.org\/mysql-basics\/mysql-insert\/\"><code>INSERT<\/code><\/a>, <a href=\"https:\/\/www.mysqltutorial.org\/mysql-basics\/mysql-update\/\"><code>UPDATE<\/code>&nbsp;<\/a>or&nbsp;<a href=\"https:\/\/www.mysqltutorial.org\/mysql-basics\/mysql-delete\/\"><code>DELETE<\/code><\/a>. Also, a subquery can be nested within another subquery.<\/p>\n\n\n\n<p>A MySQL subquery is called an inner query whereas the query that contains the subquery is called an outer query. A subquery can be used anywhere that expression is used and must be closed in parentheses.<\/p>\n\n\n\n<p>For example, the following query uses a subquery to return the employees who work in the offices located in the USA.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">SELECT<\/span> \n    lastName, firstName\n<span class=\"hljs-keyword\">FROM<\/span>\n    employees\n<span class=\"hljs-keyword\">WHERE<\/span>\n    officeCode <span class=\"hljs-keyword\">IN<\/span> (<span class=\"hljs-keyword\">SELECT<\/span> \n            officeCode\n        <span class=\"hljs-keyword\">FROM<\/span>\n            offices\n        <span class=\"hljs-keyword\">WHERE<\/span>\n            country = <span class=\"hljs-string\">'USA'<\/span>);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this example:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><span style=\"line-height: 13px;\">The subquery returns all <em>office codes<\/em> of the offices located in the USA.<\/span><\/li>\n\n\n\n<li>The outer query selects the last name and first name of employees who work in the offices whose office codes are in the result set returned by the subquery.<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"395\" height=\"147\" src=\"https:\/\/www.mysqltutorial.org\/wp-content\/uploads\/2013\/02\/mysql-subquery.gif\" alt=\"\" class=\"wp-image-1474\"\/><\/figure>\n\n\n\n<p>When executing the query, MySQL evaluates the subquery first and uses the result of the subquery for the outer query.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Using a MySQL subquery in the WHERE clause<\/h2>\n\n\n\n<p>We will use the table <code>payments<\/code> in the <a href=\"https:\/\/www.mysqltutorial.org\/getting-started-with-mysql\/mysql-sample-database\/\">sample database<\/a> for the demonstration.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img loading=\"lazy\" decoding=\"async\" width=\"144\" height=\"124\" src=\"https:\/\/www.mysqltutorial.org\/wp-content\/uploads\/2019\/08\/payments.png\" alt=\"\" class=\"wp-image-8034\"\/><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">MySQL subquery with comparison operators<\/h3>\n\n\n\n<p>You can use comparison operators e.g., =, &gt;, &lt; to compare a single value returned by the subquery with the expression in the <code><a href=\"https:\/\/www.mysqltutorial.org\/mysql-basics\/mysql-where\/\">WHERE<\/a><\/code> clause.<\/p>\n\n\n\n<p>For example, the following query returns the customer who has the highest payment.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">SELECT<\/span> \n    customerNumber, \n    checkNumber, \n    amount\n<span class=\"hljs-keyword\">FROM<\/span>\n    payments\n<span class=\"hljs-keyword\">WHERE<\/span>\n    amount = (<span class=\"hljs-keyword\">SELECT<\/span> <span class=\"hljs-keyword\">MAX<\/span>(amount) <span class=\"hljs-keyword\">FROM<\/span> payments);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a class=\"sql\" href=\"https:\/\/www.mysqltutorial.org\/tryit\/query\/mysql-subquery\/#1\" target=\"_blank\" rel=\"noopener noreferrer\">Try It Out<\/a><\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">+----------------+-------------+-----------+\r\n| customerNumber | checkNumber | amount    |\r\n+----------------+-------------+-----------+\r\n|            <span class=\"hljs-number\">141<\/span> | JE105477    | <span class=\"hljs-number\">120166.58<\/span> |\r\n+----------------+-------------+-----------+\r\n<span class=\"hljs-number\">1<\/span> row <span class=\"hljs-keyword\">in<\/span> <span class=\"hljs-keyword\">set<\/span> (0.00 sec)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Besides the <code>=<\/code> operator, you can use other comparison operators such as greater than (<code>><\/code>), greater than or equal to (>=) less than(<code>&lt;<\/code>), and less than or equal to (&lt;=).<\/p>\n\n\n\n<p>For example, you can find customers whose payments are greater than the average payment using a subquery:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">SELECT<\/span> \n    customerNumber, \n    checkNumber, \n    amount\n<span class=\"hljs-keyword\">FROM<\/span>\n    payments\n<span class=\"hljs-keyword\">WHERE<\/span>\n    amount &gt; (<span class=\"hljs-keyword\">SELECT<\/span> \n            <span class=\"hljs-keyword\">AVG<\/span>(amount)\n        <span class=\"hljs-keyword\">FROM<\/span>\n            payments);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a class=\"sql\" href=\"https:\/\/www.mysqltutorial.org\/tryit\/query\/mysql-subquery\/#2\" target=\"_blank\" rel=\"noopener noreferrer\">Try It Out<\/a><\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">+----------------+-------------+-----------+\r\n| customerNumber | checkNumber | amount    |\r\n+----------------+-------------+-----------+\r\n|            112 | HQ55022     |  32641.98 |\r\n|            112 | ND748579    |  33347.88 |\r\n|            114 | GG31455     |  45864.03 |\r\n|            114 | MA765515    |  82261.22 |\n...<\/code><\/span><\/pre>\n\n\n<p>In this example:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First, get the average payment by using a subquery.<\/li>\n\n\n\n<li>Then, select the payments that are greater than the average payment returned by the subquery in the outer query.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">MySQL subquery with IN and NOT IN operators<\/h3>\n\n\n\n<p>If a subquery returns more than one value, you can use other operators such as <code><a href=\"https:\/\/www.mysqltutorial.org\/mysql-basics\/mysql-in\/\">IN<\/a><\/code> or <code><a href=\"https:\/\/www.mysqltutorial.org\/mysql-basics\/mysql-in\/\">NOT IN<\/a><\/code> operator in the <code>WHERE<\/code> clause.<\/p>\n\n\n\n<p>See the following <code>customers<\/code> and <code>orders<\/code> tables:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img loading=\"lazy\" decoding=\"async\" width=\"434\" height=\"304\" src=\"https:\/\/www.mysqltutorial.org\/wp-content\/uploads\/2019\/08\/customers-orders.png\" alt=\"\" class=\"wp-image-8036\" srcset=\"https:\/\/www.mysqltutorial.org\/wp-content\/uploads\/2019\/08\/customers-orders.png 434w, https:\/\/www.mysqltutorial.org\/wp-content\/uploads\/2019\/08\/customers-orders-200x140.png 200w\" sizes=\"auto, (max-width: 434px) 100vw, 434px\" \/><\/figure>\n\n\n\n<p>For example, you can use a subquery with <code>NOT IN<\/code> operator to find the customers who have not placed any orders as follows:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">SELECT<\/span> \n    customerName\n<span class=\"hljs-keyword\">FROM<\/span>\n    customers\n<span class=\"hljs-keyword\">WHERE<\/span>\n    customerNumber <span class=\"hljs-keyword\">NOT<\/span> <span class=\"hljs-keyword\">IN<\/span> (<span class=\"hljs-keyword\">SELECT<\/span> <span class=\"hljs-keyword\">DISTINCT<\/span>\n            customerNumber\n        <span class=\"hljs-keyword\">FROM<\/span>\n            orders);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a class=\"sql\" href=\"https:\/\/www.mysqltutorial.org\/tryit\/query\/mysql-subquery\/#3\" target=\"_blank\" rel=\"noopener noreferrer\">Try It Out<\/a><\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">+--------------------------------+\r\n| customerName                   |\r\n+--------------------------------+\r\n| Havel &amp; Zbyszek Co             |\r\n| American Souvenirs Inc         |\r\n| Porto Imports Co.              |\r\n| Asian Shopping Network, Co     |\n...<\/code><\/span><\/pre>\n\n\n<h2 class=\"wp-block-heading\">MySQL subquery in the FROM clause<\/h2>\n\n\n\n<p>When you use a subquery in the <code>FROM<\/code> clause, the result set returned from a subquery is used as a <a href=\"https:\/\/www.mysqltutorial.org\/mysql-basics\/mysql-temporary-table\/\">temporary table.<\/a> This table is referred to as a <a href=\"https:\/\/www.mysqltutorial.org\/mysql-basics\/mysql-derived-table\/\">derived table<\/a> or materialized subquery.<\/p>\n\n\n\n<p>The following subquery finds the <a href=\"https:\/\/www.mysqltutorial.org\/mysql-aggregate-functions\/mysql-max-function\/\">maximum<\/a>, <a href=\"https:\/\/www.mysqltutorial.org\/mysql-aggregate-functions\/mysql-min\/\">minimum, <\/a>and <a href=\"https:\/\/www.mysqltutorial.org\/mysql-aggregate-functions\/mysql-avg\/\">average <\/a>number of items in sale orders:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">SELECT<\/span> \n    <span class=\"hljs-keyword\">MAX<\/span>(items), \n    <span class=\"hljs-keyword\">MIN<\/span>(items), \n    <span class=\"hljs-keyword\">FLOOR<\/span>(<span class=\"hljs-keyword\">AVG<\/span>(items))\n<span class=\"hljs-keyword\">FROM<\/span>\n    (<span class=\"hljs-keyword\">SELECT<\/span> \n        orderNumber, <span class=\"hljs-keyword\">COUNT<\/span>(orderNumber) <span class=\"hljs-keyword\">AS<\/span> items\n    <span class=\"hljs-keyword\">FROM<\/span>\n        orderdetails\n    <span class=\"hljs-keyword\">GROUP<\/span> <span class=\"hljs-keyword\">BY<\/span> orderNumber) <span class=\"hljs-keyword\">AS<\/span> lineitems;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a class=\"sql\" href=\"https:\/\/www.mysqltutorial.org\/tryit\/query\/mysql-subquery\/#6\" target=\"_blank\" rel=\"noopener noreferrer\">Try It Out<\/a><\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">+------------+------------+-------------------+\r\n| MAX(items) | MIN(items) | FLOOR(AVG(items)) |\r\n+------------+------------+-------------------+\r\n|         <span class=\"hljs-number\">18<\/span> |          <span class=\"hljs-number\">1<\/span> |                 <span class=\"hljs-number\">9<\/span> |\r\n+------------+------------+-------------------+\r\n<span class=\"hljs-number\">1<\/span> row <span class=\"hljs-keyword\">in<\/span> <span class=\"hljs-keyword\">set<\/span> (0.01 sec)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Note that the <code><a href=\"https:\/\/www.mysqltutorial.org\/mysql-math-functions\/mysql-floor\/\">FLOOR()<\/a><\/code> is used to remove decimal places from the average values of items.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">MySQL correlated subquery<\/h2>\n\n\n\n<p>In the previous examples, you notice that a subquery is independent. It means that you can execute the subquery as a standalone query, for example:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">SELECT<\/span> \n    orderNumber, \n    <span class=\"hljs-keyword\">COUNT<\/span>(orderNumber) <span class=\"hljs-keyword\">AS<\/span> items\n<span class=\"hljs-keyword\">FROM<\/span>\n    orderdetails\n<span class=\"hljs-keyword\">GROUP<\/span> <span class=\"hljs-keyword\">BY<\/span> orderNumber;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Unlike a standalone subquery, a correlated subquery is a subquery that uses the data from the outer query. In other words, a correlated subquery depends on the outer query. A correlated subquery is evaluated once for each row in the outer query.<\/p>\n\n\n\n<p>See the following <code>products<\/code> table from the <a href=\"https:\/\/www.mysqltutorial.org\/getting-started-with-mysql\/mysql-sample-database\/\">sample database<\/a>:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" src=\"https:\/\/www.mysqltutorial.org\/wp-content\/uploads\/2023\/10\/products.svg\" alt=\"\" class=\"wp-image-10788\"\/><\/figure>\n\n\n\n<p>The following example uses a correlated subquery to select products whose buy prices are greater than the average buy price of all products in each<em>\u00a0<\/em>product line.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">SELECT<\/span> \n    productname, \n    buyprice\n<span class=\"hljs-keyword\">FROM<\/span>\n    products p1\n<span class=\"hljs-keyword\">WHERE<\/span>\n    buyprice &gt; (<span class=\"hljs-keyword\">SELECT<\/span> \n            <span class=\"hljs-keyword\">AVG<\/span>(buyprice)\n        <span class=\"hljs-keyword\">FROM<\/span>\n            products\n        <span class=\"hljs-keyword\">WHERE<\/span>\n            productline = p1.productline);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a class=\"sql\" href=\"https:\/\/www.mysqltutorial.org\/tryit\/query\/mysql-subquery\/#7\" target=\"_blank\" rel=\"noopener noreferrer\">Try It Out<\/a><\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">+-----------------------------------------+----------+\r\n| productname                             | buyprice |\r\n+-----------------------------------------+----------+\r\n| 1952 Alpine Renault 1300                |    98.58 |\r\n| 1996 Moto Guzzi 1100i                   |    68.99 |\r\n| 2003 Harley-Davidson Eagle Drag Bike    |    91.02 |\r\n| 1972 Alfa Romeo GTA                     |    85.68 |\r\n| 1962 LanciaA Delta 16V                  |   103.42 |\r\n| 1968 Ford Mustang                       |    95.34 |\n..<\/code><\/span><\/pre>\n\n\n<p>In this example, both the outer query and correlated subquery reference the same <code>products<\/code> table. Therefore, we need to use a table alias <code>p1<\/code> for the <code>products<\/code> table in the outer query.<\/p>\n\n\n\n<p>Unlike a regular subquery, you cannot execute a correlated subquery independently like this. If you do so, MySQL doesn&#8217;t know the p1 table and will issue an error.<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">SELECT \n    AVG(buyprice)\nFROM\n    products\nWHERE\n    productline = p1.productline;<\/code><\/span><\/pre>\n\n\n<p>For each row in the <code>products<\/code> (or p1) table, the correlated subquery needs to execute once to get the average buy price of all products in the <code>productline<\/code> of that row.<\/p>\n\n\n\n<p>If the buy price of the current row is greater than the average buy price returned by the correlated subquery, the query includes the row in the result set.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">MySQL subquery with EXISTS and NOT EXISTS<\/h3>\n\n\n\n<p>When a subquery is used with the&nbsp;<a href=\"https:\/\/www.mysqltutorial.org\/mysql-basicshttps:\/\/www.mysqltutorial.org\/mysql-basics\/mysql-exists\/\"><code>EXISTS<\/code><\/a> or <code><a href=\"https:\/\/www.mysqltutorial.org\/mysql-basicshttps:\/\/www.mysqltutorial.org\/mysql-basics\/mysql-exists\/\">NOT EXISTS<\/a><\/code> operator, a subquery returns a Boolean value of <code>TRUE<\/code> or <code>FALSE<\/code>.&nbsp; The following query illustrates a subquery used with the <code>EXISTS<\/code> operator:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">SELECT<\/span> \n    *\n<span class=\"hljs-keyword\">FROM<\/span>\n    table_name\n<span class=\"hljs-keyword\">WHERE<\/span>\n    <span class=\"hljs-keyword\">EXISTS<\/span>( subquery );<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In the query above, if the subquery returns any rows, <code>EXISTS subquery<\/code> returns <code>TRUE<\/code>, otherwise, it returns <code>FALSE<\/code>.<\/p>\n\n\n\n<p>The <code>EXISTS<\/code> and <code>NOT EXISTS<\/code> are often used in the correlated subqueries.<\/p>\n\n\n\n<p>Let&#8217;s take a look at the <code>orders<\/code> and <code>orderdetails<\/code> tables from the <a href=\"https:\/\/www.mysqltutorial.org\/getting-started-with-mysql\/mysql-sample-database\/\">sample database<\/a>:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img loading=\"lazy\" decoding=\"async\" width=\"424\" height=\"184\" src=\"https:\/\/www.mysqltutorial.org\/wp-content\/uploads\/2019\/08\/orders-orderdetails-table.png\" alt=\"orders orderdetails table\" class=\"wp-image-7867\" srcset=\"https:\/\/www.mysqltutorial.org\/wp-content\/uploads\/2019\/08\/orders-orderdetails-table.png 424w, https:\/\/www.mysqltutorial.org\/wp-content\/uploads\/2019\/08\/orders-orderdetails-table-200x87.png 200w\" sizes=\"auto, (max-width: 424px) 100vw, 424px\" \/><\/figure>\n\n\n\n<p>The following query finds sales orders whose total values are greater than 60K.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">SELECT<\/span> \n    orderNumber, \n    <span class=\"hljs-keyword\">SUM<\/span>(priceEach * quantityOrdered) total\n<span class=\"hljs-keyword\">FROM<\/span>\n    orderdetails\n        <span class=\"hljs-keyword\">INNER<\/span> <span class=\"hljs-keyword\">JOIN<\/span>\n    orders <span class=\"hljs-keyword\">USING<\/span> (orderNumber)\n<span class=\"hljs-keyword\">GROUP<\/span> <span class=\"hljs-keyword\">BY<\/span> orderNumber\n<span class=\"hljs-keyword\">HAVING<\/span> <span class=\"hljs-keyword\">SUM<\/span>(priceEach * quantityOrdered) &gt; <span class=\"hljs-number\">60000<\/span>;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-12\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">+-------------+----------+\r\n| orderNumber | total    |\r\n+-------------+----------+\r\n|       <span class=\"hljs-number\">10165<\/span> | <span class=\"hljs-number\">67392.85<\/span> |\r\n|       <span class=\"hljs-number\">10310<\/span> | <span class=\"hljs-number\">61234.67<\/span> |\r\n|       <span class=\"hljs-number\">10287<\/span> | <span class=\"hljs-number\">61402.00<\/span> |\r\n+-------------+----------+\r\n<span class=\"hljs-number\">3<\/span> rows <span class=\"hljs-keyword\">in<\/span> <span class=\"hljs-keyword\">set<\/span> (0.01 sec)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>It returns 3 rows, meaning that there are three sales orders whose total values are greater than 60K.<\/p>\n\n\n\n<p>You can use the query above as a correlated subquery to find customers who placed at least one sales order with a total value greater than 60K by using the <code>EXISTS<\/code> operator:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-13\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">SELECT<\/span> \n    customerNumber, \n    customerName\n<span class=\"hljs-keyword\">FROM<\/span>\n    customers\n<span class=\"hljs-keyword\">WHERE<\/span>\n    <span class=\"hljs-keyword\">EXISTS<\/span>( <span class=\"hljs-keyword\">SELECT<\/span> \n            orderNumber, <span class=\"hljs-keyword\">SUM<\/span>(priceEach * quantityOrdered)\n        <span class=\"hljs-keyword\">FROM<\/span>\n            orderdetails\n                <span class=\"hljs-keyword\">INNER<\/span> <span class=\"hljs-keyword\">JOIN<\/span>\n            orders <span class=\"hljs-keyword\">USING<\/span> (orderNumber)\n        <span class=\"hljs-keyword\">WHERE<\/span>\n            customerNumber = customers.customerNumber\n        <span class=\"hljs-keyword\">GROUP<\/span> <span class=\"hljs-keyword\">BY<\/span> orderNumber\n        <span class=\"hljs-keyword\">HAVING<\/span> <span class=\"hljs-keyword\">SUM<\/span>(priceEach * quantityOrdered) &gt; <span class=\"hljs-number\">60000<\/span>);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-13\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-14\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">+----------------+--------------------------+\r\n| customerNumber | customerName             |\r\n+----------------+--------------------------+\r\n|            <span class=\"hljs-number\">148<\/span> | Dragon Souveniers, Ltd.  |\r\n|            <span class=\"hljs-number\">259<\/span> | Toms Spezialit\u251c\u00f1ten, Ltd |\r\n|            <span class=\"hljs-number\">298<\/span> | Vida Sport, Ltd          |\r\n+----------------+--------------------------+\r\n<span class=\"hljs-number\">3<\/span> rows <span class=\"hljs-keyword\">in<\/span> <span class=\"hljs-keyword\">set<\/span> (0.01 sec)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-14\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Summary<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A subquery is a query nested within another query (or outer query).<\/li>\n\n\n\n<li>A correlated subquery depends on the outer query.<\/li>\n<\/ul>\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful? <\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"1472\"\n\t\t\t\tdata-post-url=\"https:\/\/www.mysqltutorial.org\/mysql-basics\/mysql-subquery\/\"\n\t\t\t\tdata-post-title=\"MySQL Subquery\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"1472\"\n\t\t\t\tdata-post-url=\"https:\/\/www.mysqltutorial.org\/mysql-basics\/mysql-subquery\/\"\n\t\t\t\tdata-post-title=\"MySQL Subquery\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\n\t\t\t<button class=\"btn btn-primary wth-btn-submit\">Send<\/button>\n\t\t\t<button class=\"btn wth-btn-cancel\">Cancel<\/button>\n\t\t\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you&#8217;ll learn about MySQL subquery and correlated subquery to form complex queries.<\/p>\n","protected":false},"author":2,"featured_media":0,"parent":174,"menu_order":24,"comment_status":"open","ping_status":"open","template":"","meta":{"footnotes":""},"class_list":["post-1472","page","type-page","status-publish","hentry"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.5 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>MySQL Subquery<\/title>\n<meta name=\"description\" content=\"In this tutorial, you&#039;ll learn about MySQL subquery and correlated subquery to form complex queries.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.mysqltutorial.org\/mysql-basics\/mysql-subquery\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"MySQL Subquery\" \/>\n<meta property=\"og:description\" content=\"In this tutorial, you&#039;ll learn about MySQL subquery and correlated subquery to form complex queries.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.mysqltutorial.org\/mysql-basics\/mysql-subquery\/\" \/>\n<meta property=\"og:site_name\" content=\"MySQL Tutorial\" \/>\n<meta property=\"article:modified_time\" content=\"2023-12-31T10:18:33+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.mysqltutorial.org\/wp-content\/uploads\/2013\/02\/mysql-subquery.gif\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"5 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.mysqltutorial.org\\\/mysql-basics\\\/mysql-subquery\\\/\",\"url\":\"https:\\\/\\\/www.mysqltutorial.org\\\/mysql-basics\\\/mysql-subquery\\\/\",\"name\":\"MySQL Subquery\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.mysqltutorial.org\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.mysqltutorial.org\\\/mysql-basics\\\/mysql-subquery\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.mysqltutorial.org\\\/mysql-basics\\\/mysql-subquery\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.mysqltutorial.org\\\/wp-content\\\/uploads\\\/2013\\\/02\\\/mysql-subquery.gif\",\"datePublished\":\"2013-02-03T06:29:34+00:00\",\"dateModified\":\"2023-12-31T10:18:33+00:00\",\"description\":\"In this tutorial, you'll learn about MySQL subquery and correlated subquery to form complex queries.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.mysqltutorial.org\\\/mysql-basics\\\/mysql-subquery\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.mysqltutorial.org\\\/mysql-basics\\\/mysql-subquery\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.mysqltutorial.org\\\/mysql-basics\\\/mysql-subquery\\\/#primaryimage\",\"url\":\"https:\\\/\\\/www.mysqltutorial.org\\\/wp-content\\\/uploads\\\/2013\\\/02\\\/mysql-subquery.gif\",\"contentUrl\":\"https:\\\/\\\/www.mysqltutorial.org\\\/wp-content\\\/uploads\\\/2013\\\/02\\\/mysql-subquery.gif\",\"width\":395,\"height\":147},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.mysqltutorial.org\\\/mysql-basics\\\/mysql-subquery\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.mysqltutorial.org\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"MySQL Basics\",\"item\":\"https:\\\/\\\/www.mysqltutorial.org\\\/mysql-basics\\\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"MySQL Subquery\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.mysqltutorial.org\\\/#website\",\"url\":\"https:\\\/\\\/www.mysqltutorial.org\\\/\",\"name\":\"MySQL Tutorial\",\"description\":\"A comprehensive MySQL Tutorial\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.mysqltutorial.org\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"MySQL Subquery","description":"In this tutorial, you'll learn about MySQL subquery and correlated subquery to form complex queries.","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:\/\/www.mysqltutorial.org\/mysql-basics\/mysql-subquery\/","og_locale":"en_US","og_type":"article","og_title":"MySQL Subquery","og_description":"In this tutorial, you'll learn about MySQL subquery and correlated subquery to form complex queries.","og_url":"https:\/\/www.mysqltutorial.org\/mysql-basics\/mysql-subquery\/","og_site_name":"MySQL Tutorial","article_modified_time":"2023-12-31T10:18:33+00:00","og_image":[{"url":"https:\/\/www.mysqltutorial.org\/wp-content\/uploads\/2013\/02\/mysql-subquery.gif","type":"","width":"","height":""}],"twitter_misc":{"Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.mysqltutorial.org\/mysql-basics\/mysql-subquery\/","url":"https:\/\/www.mysqltutorial.org\/mysql-basics\/mysql-subquery\/","name":"MySQL Subquery","isPartOf":{"@id":"https:\/\/www.mysqltutorial.org\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.mysqltutorial.org\/mysql-basics\/mysql-subquery\/#primaryimage"},"image":{"@id":"https:\/\/www.mysqltutorial.org\/mysql-basics\/mysql-subquery\/#primaryimage"},"thumbnailUrl":"https:\/\/www.mysqltutorial.org\/wp-content\/uploads\/2013\/02\/mysql-subquery.gif","datePublished":"2013-02-03T06:29:34+00:00","dateModified":"2023-12-31T10:18:33+00:00","description":"In this tutorial, you'll learn about MySQL subquery and correlated subquery to form complex queries.","breadcrumb":{"@id":"https:\/\/www.mysqltutorial.org\/mysql-basics\/mysql-subquery\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.mysqltutorial.org\/mysql-basics\/mysql-subquery\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.mysqltutorial.org\/mysql-basics\/mysql-subquery\/#primaryimage","url":"https:\/\/www.mysqltutorial.org\/wp-content\/uploads\/2013\/02\/mysql-subquery.gif","contentUrl":"https:\/\/www.mysqltutorial.org\/wp-content\/uploads\/2013\/02\/mysql-subquery.gif","width":395,"height":147},{"@type":"BreadcrumbList","@id":"https:\/\/www.mysqltutorial.org\/mysql-basics\/mysql-subquery\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.mysqltutorial.org\/"},{"@type":"ListItem","position":2,"name":"MySQL Basics","item":"https:\/\/www.mysqltutorial.org\/mysql-basics\/"},{"@type":"ListItem","position":3,"name":"MySQL Subquery"}]},{"@type":"WebSite","@id":"https:\/\/www.mysqltutorial.org\/#website","url":"https:\/\/www.mysqltutorial.org\/","name":"MySQL Tutorial","description":"A comprehensive MySQL Tutorial","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.mysqltutorial.org\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"}]}},"_links":{"self":[{"href":"https:\/\/www.mysqltutorial.org\/wp-json\/wp\/v2\/pages\/1472","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.mysqltutorial.org\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.mysqltutorial.org\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.mysqltutorial.org\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.mysqltutorial.org\/wp-json\/wp\/v2\/comments?post=1472"}],"version-history":[{"count":5,"href":"https:\/\/www.mysqltutorial.org\/wp-json\/wp\/v2\/pages\/1472\/revisions"}],"predecessor-version":[{"id":13951,"href":"https:\/\/www.mysqltutorial.org\/wp-json\/wp\/v2\/pages\/1472\/revisions\/13951"}],"up":[{"embeddable":true,"href":"https:\/\/www.mysqltutorial.org\/wp-json\/wp\/v2\/pages\/174"}],"wp:attachment":[{"href":"https:\/\/www.mysqltutorial.org\/wp-json\/wp\/v2\/media?parent=1472"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}