{"id":37510,"date":"2024-08-19T08:11:44","date_gmt":"2024-08-18T22:11:44","guid":{"rendered":"https:\/\/database.guide\/?p=37510"},"modified":"2024-09-17T07:00:39","modified_gmt":"2024-09-16T21:00:39","slug":"using-a-sql-subquery-in-the-select-list","status":"publish","type":"post","link":"https:\/\/database.guide\/using-a-sql-subquery-in-the-select-list\/","title":{"rendered":"Using a SQL Subquery in the SELECT List"},"content":{"rendered":"\n<p class=\"\">Let&#8217;s dive into subqueries for a moment. Specifically, how to use a SQL subquery in the <code><a href=\"https:\/\/database.guide\/sql-select-for-beginners\/\" data-type=\"post\" data-id=\"11928\">SELECT<\/a><\/code> list. It&#8217;s a handy little trick that can help us fetch related data without resorting to complex joins.<\/p>\n\n\n\n<!--more-->\n\n\n\n<h2 class=\"wp-block-heading\">Sample Database<\/h2>\n\n\n\n<p class=\"\">First, let&#8217;s set up some sample tables:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>-- Create the Authors table\nCREATE TABLE Authors (\n    AuthorID INT PRIMARY KEY,\n    AuthorName VARCHAR(100)\n);\n\n-- Create the Books table\nCREATE TABLE Books (\n    BookID INT PRIMARY KEY,\n    Title VARCHAR(200),\n    AuthorID INT,\n    PublicationYear INT,\n    FOREIGN KEY (AuthorID) REFERENCES Authors(AuthorID)\n);\n\n-- Create the Sales table\nCREATE TABLE Sales (\n    SaleID INT PRIMARY KEY,\n    BookID INT,\n    QuantitySold INT,\n    SaleDate DATE,\n    FOREIGN KEY (BookID) REFERENCES Books(BookID)\n);\n\n-- Populate the Authors table\nINSERT INTO Authors (AuthorID, AuthorName) VALUES\n(1, 'J.K. Rowling'),\n(2, 'George Orwell'),\n(3, 'Jane Austen'),\n(4, 'Stephen King');\n\n-- Populate the Books table\nINSERT INTO Books (BookID, Title, AuthorID, PublicationYear) VALUES\n(1, 'Harry Potter and the Philosopher''s Stone', 1, 1997),\n(2, '1984', 2, 1949),\n(3, 'Pride and Prejudice', 3, 1813),\n(4, 'The Shining', 4, 1977),\n(5, 'Harry Potter and the Chamber of Secrets', 1, 1998);\n\n-- Populate the Sales table\nINSERT INTO Sales (SaleID, BookID, QuantitySold, SaleDate) VALUES\n(1, 1, 100, '2023-01-15'),\n(2, 2, 50, '2023-02-20'),\n(3, 3, 75, '2023-03-10'),\n(4, 4, 60, '2023-04-05'),\n(5, 5, 90, '2023-05-12'),\n(6, 1, 120, '2023-06-18'),\n(7, 2, 40, '2023-07-22'),\n(8, 3, 80, '2023-08-30');<\/code><\/pre>\n\n\n\n<p class=\"\">Now that we&#8217;ve got our tables set up and populated, let&#8217;s see how we can write a query that uses a subquery in the <code>SELECT<\/code> list. <\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Example 1<\/h2>\n\n\n\n<p class=\"\">Imagine we want to display each book&#8217;s title along with its total sales. Here&#8217;s how we can do that:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT \n    b.Title,\n    b.PublicationYear,\n    (SELECT SUM(QuantitySold) \n     FROM Sales s \n     WHERE s.BookID = b.BookID) AS TotalSales\nFROM \n    Books b\nORDER BY \n    TotalSales DESC;<\/code><\/pre>\n\n\n\n<p class=\"\">Result:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Title                                     PublicationYear  TotalSales<br>----------------------------------------  ---------------  ----------<br>Harry Potter and the Philosopher's Stone  1997             220       <br>Pride and Prejudice                       1813             155       <br>1984                                      1949             90        <br>Harry Potter and the Chamber of Secrets   1998             90        <br>The Shining                               1977             60        <\/pre>\n\n\n\n<p class=\"\">In this query, we&#8217;re using a SQL subquery in the <code>SELECT<\/code> list to calculate the total sales for each book. The subquery is correlated, meaning it refers to the outer query. We can see this with the part that goes <code>WHERE s.BookID = b.BookID<\/code> part. The <code>b<\/code> part is the table from the outer query.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Example 2<\/h2>\n\n\n\n<p class=\"\">Here&#8217;s another example where we use a subquery in the <code>SELECT<\/code> list to find the most recent publication year for each author:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT \n    a.AuthorName,\n    (SELECT MAX(PublicationYear) \n     FROM Books b \n     WHERE b.AuthorID = a.AuthorID) AS LatestPublicationYear\nFROM \n    Authors a\nORDER BY \n    LatestPublicationYear DESC;<\/code><\/pre>\n\n\n\n<p class=\"\">Result:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">AuthorName     LatestPublicationYear<br>-------------  ---------------------<br>J.K. Rowling   1998                 <br>Stephen King   1977                 <br>George Orwell  1949                 <br>Jane Austen    1813                 <\/pre>\n\n\n\n<p class=\"\">Here, the inner query got the most recent publication for each author, and the outer query returned the authors&#8217; names and ordered the results.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Some Considerations<\/h2>\n\n\n\n<p class=\"\">A correlated subquery can&#8217;t be run independently of the outer query. In other words, we can&#8217;t copy and paste the subquery and run it by itself. That&#8217;s because it refers to outer query, and so it requires the outer query in order to run.<\/p>\n\n\n\n<p class=\"\">Putting a subquery into the <code>SELECT<\/code> list (and using subqueries in general) can have its advantages:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li class=\"\">It&#8217;s often more readable than a complex join, especially for simple calculations.<\/li>\n\n\n\n<li class=\"\">It allows us to perform aggregations without grouping in the main query.<\/li>\n\n\n\n<li class=\"\">It can be more efficient in some cases, particularly when dealing with large datasets.<\/li>\n<\/ul>\n\n\n\n<p class=\"\">However, it&#8217;s worth noting that some subqueries can result in performance issues. It all depends on the query. For more complex scenarios or when dealing with large amounts of data, you might want to consider using <a href=\"https:\/\/database.guide\/sql-joins-tutorial\/\" data-type=\"post\" data-id=\"11436\">SQL joins<\/a> or Common Table Expressions (CTEs) instead.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">SQL Joins as an Alternative<\/h2>\n\n\n\n<p class=\"\">Many subqueries can be rewritten using SQL joins. Some <a href=\"https:\/\/database.guide\/what-is-an-rdbms\/\" data-type=\"post\" data-id=\"222\">RDBMS<\/a>s rewrite our subqueries as joins behind the scenes anyway. Sometimes when we encounter performance issues with a query, we can try rewriting it to use a join instead of a subquery (or vice-versa).<\/p>\n\n\n\n<p class=\"\">See my <a href=\"https:\/\/database.guide\/sql-joins-tutorial\/\" data-type=\"post\" data-id=\"11436\">SQL Joins Tutorial<\/a> for a quick-start guide to understanding joins and including them in your SQL code.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Let&#8217;s dive into subqueries for a moment. Specifically, how to use a SQL subquery in the SELECT list. It&#8217;s a handy little trick that can help us fetch related data without resorting to complex joins.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[7],"tags":[15,10,173],"class_list":["post-37510","post","type-post","status-publish","format-standard","hentry","category-sql","tag-create-query","tag-how-to","tag-subqueries"],"_links":{"self":[{"href":"https:\/\/database.guide\/wp-json\/wp\/v2\/posts\/37510","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/database.guide\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/database.guide\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/database.guide\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/database.guide\/wp-json\/wp\/v2\/comments?post=37510"}],"version-history":[{"count":5,"href":"https:\/\/database.guide\/wp-json\/wp\/v2\/posts\/37510\/revisions"}],"predecessor-version":[{"id":38439,"href":"https:\/\/database.guide\/wp-json\/wp\/v2\/posts\/37510\/revisions\/38439"}],"wp:attachment":[{"href":"https:\/\/database.guide\/wp-json\/wp\/v2\/media?parent=37510"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/database.guide\/wp-json\/wp\/v2\/categories?post=37510"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/database.guide\/wp-json\/wp\/v2\/tags?post=37510"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}