SQL Subqueries – Tutorialpath

SQL Subqueries

  • A subquery is a SQL query within a query.
  • Subqueries are nested queries that provide data to the enclosing query.
  • Subqueries can return individual values or a list of records
  • Subqueries must be enclosed with parenthesis
Rules for Subqueries:
  • A subquery cannot be immediately enclosed in a set function.
  • You can place the Subquery in a number of SQL clauses: WHERE clause, HAVING clause, FROM clause.
    Subqueries can be used with SELECT, UPDATE, INSERT, DELETE statements along with expression operator. It could be equality operator or comparison operator such as =, >, =, <= and Like operator.
  • Subquery must be enclosed in parentheses.
  • A subquery is a query within another query. The outer query is called as main query and inner query is called as subquery.
  • The subquery generally executes first, and its output is used to complete the query condition for the main or outer query.
  • An ORDER BY command cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY command can be used to perform the same function as the ORDER BY in a subquery.
  • Subqueries can return individual values or a list of records.

Syntax:
There is not any general syntax for Subqueries are regular queries placed inside parenthesis.

Subqueries are seen to be used most frequently with SELECT statement as shown below:

Here is an subquery with the IN operator.

in_operator_subquery
in_operator_subquery

Subqueries can also assign column values for each record:

subquery_column_value
subquery_column_value

SQL Subquery Examples

SQL_Subquery
SQL_Subquery

Problem: List products with order quantities greater than 100.

 

 

 

 

 

SQL_Subquery
SQL_Subquery

 

results
results

Leave a Reply

Your email address will not be published.