SQLite – 14 – Subqueries

Subqueries, also known as nested queries or subselects, are a powerful feature in SQLite and SQL in general. They allow you to embed one query (the inner query) within another query (the outer query). Subqueries are used to retrieve data needed for the execution of the outer query, making it a versatile tool for complex data retrieval and manipulation. In this discussion, we will explore subqueries in SQLite, their types, syntax, and practical examples.

Types of Subqueries:

SQLite supports two main types of subqueries:

  1. Single-row subquery: This type of subquery returns a single value (a single row and single column) and is often used in comparisons or calculations within the outer query.
  2. Multi-row subquery: A multi-row subquery returns multiple rows and can be used in operations like IN, ANY, ALL, or EXISTS to compare a set of values or results.

Basic Syntax for Subqueries:

The basic syntax for a subquery in SQLite is as follows:

SELECT column_name(s) FROM table_name WHERE column_name operator (SELECT column_name FROM table_name WHERE condition);

In this syntax:

  • column_name(s) represents the columns you want to retrieve from the outer query.
  • table_name is the name of the table you’re querying.
  • column_name operator is the operator (e.g., =, >, <, IN, ANY, ALL, EXISTS) used to compare the results of the subquery.
  • (SELECT column_name FROM table_name WHERE condition) is the subquery itself, which retrieves data based on specified criteria.

Example 1: Single-row Subquery

Suppose you have a table named Products and you want to find all products with a price higher than the average price of all products:

SELECT ProductName, Price FROM Products WHERE Price > (SELECT AVG(Price) FROM Products);

In this query:

  • We select the ProductName and Price columns from the Products table.
  • We use a subquery to calculate the average price using SELECT AVG(Price) FROM Products.
  • The main query retrieves products where the price is greater than the average price calculated by the subquery.

Example 2: Multi-row Subquery

Let’s say you have a table called Orders and another table named Customers. You want to find customers who have placed at least one order:

SELECT CustomerName FROM Customers WHERE CustomerID IN (SELECT DISTINCT CustomerID FROM Orders);

In this query:

  • We select the CustomerName from the Customers table.
  • We use a subquery to retrieve all distinct CustomerID values from the Orders table.
  • The main query retrieves customers whose CustomerID is found in the result of the subquery.

Example 3: Subquery with EXISTS

You may want to find employees who have not placed any orders. In this case, you can use the EXISTS keyword with a subquery:

SELECT EmployeeName FROM Employees WHERE NOT EXISTS (SELECT * FROM Orders WHERE Orders.EmployeeID = Employees.EmployeeID);

In this query:

  • We select the EmployeeName from the Employees table.
  • We use a subquery to check if there are any records in the Orders table where the EmployeeID matches the EmployeeID in the outer query.
  • The NOT EXISTS condition returns employees who do not have a corresponding record in the Orders table.

Example 4: Subquery in INSERT Statement

Subqueries can also be used in INSERT statements. Suppose you have a table named HighValueCustomers where you want to insert customers with total purchases exceeding a certain amount:

INSERT INTO HighValueCustomers (CustomerID, CustomerName) SELECT CustomerID, CustomerName FROM Customers WHERE TotalPurchases > (SELECT SUM(OrderAmount) FROM Orders WHERE Orders.CustomerID = Customers.CustomerID);

In this query:

  • We specify the columns we want to insert (CustomerID and CustomerName) into the HighValueCustomers table.
  • We use a subquery to calculate the total purchases for each customer in the Orders table.
  • The main query inserts customers who meet the condition of having total purchases exceeding the subquery result.

Conclusion:

Subqueries in SQLite are a versatile and powerful feature that allows you to perform complex data retrieval and manipulation tasks. Whether you need to filter, compare, or calculate data within an outer query, subqueries provide the flexibility to achieve your desired results. Understanding how to use subqueries effectively is essential for advanced SQL query building and data analysis in SQLite databases.