MySQL Tutorial

MySQL Tutorial MySQL Features MySQL Database Introduction MySQL Environmental Setup MySQL Data Types MySQL variable MySQL Advance table Query MySQL database queries MySQL Entity-Relationship Model MySQL Table Query MySQL Operators MySQL logical conditions MySQL Queries MySQL Clauses Clustered vs Non-Clustered Index MySQL Full text index MySQL Descending Index MySQL Invisible Index MySQL Composite Index MySQL Prefix index MySQL Index MySQL Create index MySQL Drop Index MySQL Show index MySQL Unique index MySQL Table MySQL Variable MySQL View MySQL Constraints MySQL Command Line Client Basic Queries MySQL Stored Procedure MySQL IF Statement MySQL Subquery MySQL Triggers

MySQL Join

MySQL Join MySQL CROSS JOIN MySQL DELETE JOIN MySQL EQUI JOIN MySQL INNER JOIN MySQL Union MySQL NATURAL JOIN MySQL RIGHT JOIN MySQL SELF JOIN MySQL UPDATE JOIN

MySQL Function

MySQL Function MySQL AVG() Function MySQL SUM() Function MySQL String() Function MySQL Advance() Function MySQL Aggregate() Function MySQL COALESCE() Function MySQL Control Flow Function MySQL COUNT() Function MySQL Date And Time Function MySQL GREATEST() Function MySQL ISNULL() Function MySQL LEAST() Function MySQL Math() Function MySQL MAX() Function MySQL MIN() Function MySQL find_in_set() function MySQL ASIN() Function MySQL CEIL() function MySQL CEILING() function MySQL TAN() Function MySQL Truncate() Function MySQL FLOOR() function MySQL LN() function MySQL LOG2() function MySQL LOG10() function MySQL MOD() function MySQL PI() function MySQL POW() function MySQL RADIANS() function MySQL RAND() function MySQL ROUND() function MySQL Character Length Function MySQL Current Date Function MySQL Date Add Function MySQL Date Format Function MySQL Datediff Function MySQL Day Function MySQL Elt Function MySQL Export Set Function MySQL Field Function MySQL Format Function MySQL From Base64 Function MySQL Hex Function MySQL Insert Function MySQL Instr Function MySQL Length Function MySQL CONCAT() function MySQL FIND_IN_SET() function MySQL LIKE() function MySQL LOAD_FILE() function MySQL LOCATE() function MySQL LOG() function MySQL MONTHNAME() function MySQL NOW() function MySQL PERIOD_ADD() function MySQL PERIOD_DIFF() function MySQL POWER() function MySQL QUARTER() function MySQL REVERSE() function MySQL RIGHT() Function MySQL RPAD() function MySQL RTRIM() function MySQL SEC_TO_TIME() function MySQL SOUNDEX() function

Questions

Which Clause is Similar to Having Clause in MySQL

Misc

MySQL Error 1046 - No Database Selected Failed to Start MySQL Service Unit MySQL Service Unit not Found Import MySQL Connector Mudule not Found Error No Module Named MySQL Joins Available in MySQL MySQL Docs MySQL Download For Windows 7 64 Bit MySQL Error Code 1064 MySQL Export MySQL History MySQL Host MySQL Import MySQL Drop All Tables MySQL Drop MySQL Error Code 1175 MySQL Events MySQL Except MYSQL Foreign Key Constraint MySQL If Exists MySQL IndexOf MySQL List All Tables json_extract in MySQL TIMESTAMPDIFF in MySQL MySQL Syntax Checker Sudo MySQL Secure Installation

MySQL Subquery

The subquery is a MySQL query used to manage data operations. Mainly subquery helps to retrieve data with the necessary condition. It creates a nested query with two different queries. The primary query contains a secondary query using parenthesis. The primary query is called an outer query, whereas the second query is called the inner query. The subquery helps to search, filter, and sort the table data based on our needs.   

Rules of the MySQL Subquery

  • The inner query must place into the parenthesis of the outer query.
  • The inner query uses a single column when an outer query does not include them.
  • The subquery uses comparison operators like =, >, <, >=, <=.
  • It uses MySQL operators like IN, ANY, etc.
  • The outer query cannot use the "order by" operator. However, the inner query can use this operator.
  • Primarily, the inner query works with the "WHERE" clause and its condition.
  • The subquery operates a single table or multiple table information in a single query.

Syntax

The basic syntax of the subquery shows below.

MySQL outer query (MySQL inner query);

MySQL subquery syntax shows below.

SELECT column1, column2, column3 
FROM table-name 
WHERE column operator
  (SELECT column FROM table-name [WHERE condition]);

MySQL subquery with two tables syntax shows below.

SELECT column1, column2, column3 
FROM first table name 
WHERE column operator
  (SELECT column FROM second table name [WHERE condition]);

The outer query uses a primary table with the essential condition. The inner query uses either the primary table or the secondary table with the condition. The outer query clause uses conditions for the inner query.

Prerequisite

MySQL subquery needs to choose a database and table for operation on their data. The subquery requires a comparison operator, conditions, and clause. You can create a table and insert value in it. It is better to understand MySQL joins and MySQL key concepts.

Example of the MySQL Subquery

1) Example: The following example displays information using a subquery.

Execute the below query to display table information. The inner query uses the aggregate function "max" for the points column. The "points" column applies the "equal to" operator for the inner query result.

mysql> select topic, points
from student_data  
WHERE points = 
(select Max(points) from student_data );

OUTPUT

MySQL Subquery

The above output image shows the topic and the "points" field of the table. The maximum value of the "points" column is 44. Here, the "equal to" operator works with the inner query.

2) Example: The subquery with comparison operator example shows below.

Execute the below query to display table information where the inner query uses aggregate function max for the "points" column. Here we have the conditional operator "less than" with the points column.

mysql> select topic, points
from student_data  
WHERE points < 
(select Max(points) from student_data );

OUTPUT

MySQL Subquery

The above output image shows the topic and points field of the table. The "points" column is less than the maximum column, which is 44. Here, the "less than" operator works with the inner query. The maximum value does not display in the output.

3) Example: The subquery with the "MIN and MAX" aggregate function example shows below.

The below query uses the inner query with an aggregate function "MIN" for the grade column and “MAX” for the "points" column. The points column applies the "less than" operator.

mysql> select topic, points, MIN(grade) AS remark from student_data  WHERE points < (select Max(points) from student_data  order by points asc);

OUTPUT

MySQL Subquery

Executing the query will display the value of the points 40 and grade value A. Here, MIN and MAX aggregation uses simultaneously. 

4) Example: The subquery with the "IN" operator example shows below.

The below subquery uses the "IN" operator, and the condition applies to the "grade" column.

mysql> select topic, points, grade AS remark from student_data  where grade IN (select grade from student_data  where grade = 'A');

OUTPUT

MySQL Subquery

The above image shows the output of the subquery with the "IN" operator. It shows the information on the table for the "A" grade.

5) Example: The subquery with the "NOT IN" operator example shows below.

The below subquery uses the "NOT IN" operator, and the condition applies to the "grade" column.

mysql> select topic, points, grade AS remark from student_data  where grade NOT IN (select grade from student_data  where grade = 'A');

OUTPUT

MySQL Subquery

The above image shows the output of the subquery with the "NOT IN" operator. It shows the information of a table except for the "A" grade. The "NOT IN" operator is the inverse of the "IN" operator that shows the exact opposite of the "IN" operator's output.

6) Example: The subquery with the "EXISTS" operator example shows below.

Execute the following query to understand the subquery and its function. The "exists" operator uses with where clause. The inner query applies conditions on the grade column.

mysql> select topic, points, grade AS remark from student_data  where grade NOT IN (select grade from student_data  where grade = 'A');

OUTPUT

MySQL Subquery

The above output image shows existing information in the table. The subquery works with similar or different tables. You can use either EXISTS or NOT EXISTS operator with MySQL subquery. The table shows grade, points, and topic columns.

7) Example: The subquery with "ANY" operator example shows below.

Execute the following subquery to understand the "ANY" operator with the WHERE clause. The inner query applies conditions on the grade column. The grade column works on the "OR" logical condition.

mysql> select topic, points, grade AS remark from student_data  where grade > ANY  (select grade from student_data  where grade = 'A' OR grade ='B');

OUTPUT

MySQL Subquery

Executing the query will return the grades, points, and topic columns. The query uses "greater than" condition before "OR" logical condition.

8) Example: The subquery with the "ALL" operator example shows below.

Execute the following query to understand the subquery and its function. The "ALL" operator is used with the WHERE clause. The inner query applies conditions on the grade column. The grade column works on the "OR" logical condition.

mysql> select topic, points, grade AS remark from student_data  where grade > ALL  (select grade from student_data  where grade = 'A' OR grade ='B');

OUTPUT

MySQL Subquery

Executing the query will return the grades, points, and topic columns. The query uses "greater than" condition before "OR" logical condition.

 Advantages of the "MySQL subquery."

  • The subquery is used to avoid complicated operations of the MySQL system.
  • The subqueries make the queries in a structured form that allows us to isolate each part of a statement.
  • The subqueries provide alternative ways to query the data from the table; otherwise, we need to use complex joins and unions.
  • The subqueries are more readable than complex join or union statements.
  • It allows to work with two expressions efficiently in a single query with multiple conditions.

Disadvantages of the "MySQL subquery."

  • The subquery uses multiple conditions, clauses and operators in a single expression.
  • Sometimes, the data condition is hard to understand in a single query. The large data set becomes confusing and complicated for the subquery.
  • The inner query does not set multiple columns; otherwise, it shows an error.
  • The many operators like "order by" do not apply to the subquery.