SQLite Tutorial

  • Home
  • Views
  • Indexes
  • Triggers
  • Functions
    • Aggregate Functions
    • Date Functions
    • String Functions
    • Window Functions
  • Interfaces
    • SQLite Java
    • SQLite Node.js
    • SQLite PHP
    • SQLite Python
  • Try It
Home / SQLite Tutorial / SQLite Subquery

SQLite Subquery

Summary: in this tutorial, you will learn about the SQLite subquery to construct more readable and complex queries.

Introduction to SQLite subquery

A subquery is a SELECT statement nested in another statement. See the following statement.

1
2
3
4
5
6
SELECT column_1
FROM table_1
WHERE column_1 = (
   SELECT column_1
   FROM table_2
);

The following query is the outer query:

1
2
3
SELECT column_1
  FROM table_1
WHERE colum_1 =

And the following query is the subquery.

1
2
(SELECT column_1
  FROM table_2)

You must use a pair of parentheses to enclose a subquery. Note that you can nest a subquery inside another subquery with a certain depth.

Typically, a subquery returns a single row as an atomic value, though it may return multiple rows for comparing values with the IN operator.

You can use a subquery in the SELECT, FROM, WHERE, and JOIN clauses.

SQLite subquery examples

We will use the tracks and albums tables from the sample database for the demonstration.

1) SQLite subquery in the WHERE clause example

You can use a simple subquery as a search condition. For example, the following statement returns all the tracks in the album with the title  Let There Be Rock

1
2
3
4
5
6
7
8
9
SELECT trackid,
       name,
       albumid
FROM tracks
WHERE albumid = (
   SELECT albumid
   FROM albums
   WHERE title = 'Let There Be Rock'
);

SQLite Subquery example

The subquery returns the id of the album with the title 'Let There Be Rock'. The query uses the equal operator (=) to compare albumid returned by the subquery with the  albumid in the tracks table.

If the subquery returns multiple values, you can use the IN operator to check for the existence of a single value against a set of value.

See the following employees and customers table in the sample database:

For example, the following query returns the customers whose sales representatives are in Canada.

1
2
3
4
5
6
7
8
9
SELECT customerid,
       firstname,
       lastname
  FROM customers
WHERE supportrepid IN (
           SELECT employeeid
             FROM employees
            WHERE country = 'Canada'
       );

SQLite Subquery with IN operator example

The subquery returns a list of ids of the employees who locate in Canada. The outer query uses the IN operator to find the customers who have the sales representative id in the list.

2) SQLite subquery in the FROM clause example

Sometimes you want to apply aggregate functions to a column multiple times. For example, first, you want to sum the size of an album and then calculate the average size of all albums. You may come up with the following query.

1
2
3
SELECT AVG(SUM(bytes)
FROM tracks
GROUP BY albumid;

This query is not valid.

To fix it, you can use a subquery in the FROM clause as follows:

1
2
3
4
5
6
7
8
9
10
11
SELECT
    AVG(album.size)
FROM
    (
        SELECT
            SUM(bytes) SIZE
        FROM
            tracks
        GROUP BY
            albumid
    ) AS album;

1
2
3
AVG(album.size)
---------------
  338288920.317

In this case, SQLite first executes the subquery in the FROM clause and returns a result set. Then, SQLite uses this result set as a derived table in the outer query.

SQLite correlated subquery

All the subqueries you have seen so far can be executed independently. In other words, it does not depend on the outer query.

The correlated subquery is a subquery that uses the values from the outer query. Unlike an ordinal subquery, a correlated subquery cannot be executed independently.

The correlated subquery is not efficient because it is evaluated for each row processed by the outer query.

The following query uses a correlated subquery to return the albums whose size is less than 10MB.

1
2
3
4
5
6
7
8
9
SELECT albumid,
       title
  FROM albums
WHERE 10000000 > (
                      SELECT sum(bytes)
                        FROM tracks
                       WHERE tracks.AlbumId = albums.AlbumId
                  )
ORDER BY title;

SQLite Correlated Subquery Example

How the query works.

  • For each row processed in the outer query, the correlated subquery calculates the size of the albums from the tracks that belong the current album using the SUM function.
  • The predicate in the WHERE clause filters the albums that have the size greater than or equal 10MB (10000000 bytes).

SQLite correlated subquery in the SELECT clause example

The following query uses a correlated subquery in the SELECT clause to return the number of tracks in an album.

1
2
3
4
5
6
7
8
9
10
SELECT albumid,
       title,
       (
           SELECT count(trackid)
             FROM tracks
            WHERE tracks.AlbumId = albums.AlbumId
       )
       tracks_count
  FROM albums
ORDER BY tracks_count DESC;

SQLite Subquery in SELECT clause example

In this tutorial, we have introduced you to the subquery and shown various ways to use a subquery in a query to select data from tables.

  • Was this tutorial helpful ?
  • YesNo
Previous Tutorial: SQLite Intersect
Next Tutorial: SQLite EXISTS

Getting Started

  • What Is SQLite
  • Download & Install SQLite
  • SQLite Sample Database
  • SQLite Commands

SQLite Tutorial

  • SQLite Select
  • SQLite Order By
  • SQLite Select Distinct
  • SQLite Where
  • SQLite Limit
  • SQLite BETWEEN
  • SQLite IN
  • SQLite Like
  • SQLite IS NULL
  • SQLite GLOB
  • SQLite Join
  • SQLite Inner Join
  • SQLite Left Join
  • SQLite Cross Join
  • SQLite Self-Join
  • SQLite Full Outer Join
  • SQLite Group By
  • SQLite Having
  • SQLite Union
  • SQLite Except
  • SQLite Intersect
  • SQLite Subquery
  • SQLite EXISTS
  • SQLite Case
  • SQLite Insert
  • SQLite Update
  • SQLite Delete
  • SQLite Replace
  • SQLite Transaction

SQLite Data Definition

  • SQLite Data Types
  • SQLite Date & Time
  • SQLite Create Table
  • SQLite Primary Key
  • SQLite Foreign Key
  • SQLite NOT NULL Constraint
  • SQLite UNIQUE Constraint
  • SQLite CHECK Constraint
  • SQLite AUTOINCREMENT
  • SQLite Alter Table
  • SQLite Rename Column
  • SQLite Drop Table
  • SQLite Create View
  • SQLite Drop View
  • SQLite Index
  • SQLite Expression-based Index
  • SQLite Trigger
  • SQLite VACUUM
  • SQLite Transaction
  • SQLite Full-text Search

SQLite Tools

  • SQLite Commands
  • SQLite Show Tables
  • SQLite Describe Table
  • SQLite Dump
  • SQLite Import CSV
  • SQLite Export CSV

SQLite Functions

  • SQLite AVG
  • SQLite COUNT
  • SQLite MAX
  • SQLite MIN
  • SQLite SUM

SQLite Interfaces

  • SQLite PHP
  • SQLite Node.js
  • SQLite Java
  • SQLite Python

About SQLite Tutorial

SQLite Tutorial website helps you master SQLite quickly and easily. It explains the complex concepts in simple and easy-to-understand ways so that you can both understand SQLite fast and know how to apply it in your software development work more effectively.

Looking for a tutorial…

If you did not find the tutorial that you are looking for, you can use the following search box. In case the tutorial is not available, you can request for it using the request for a SQLite tutorial form.

Recent Tutorials

  • SQLite Concat
  • SQLite INSTEAD OF Triggers
  • SQLite Join
  • SQLite IS NULL
  • SQLite Rename Column
  • SQLite DROP VIEW
  • SQLite Window Frame
  • SQLite CUME_DIST

Site Links

  • Home
  • About
  • Contact
  • Resources
  • Privacy Policy

Copyright © 2020 SQLite Tutorial. All rights Reserved.

⤒