Tech Junkie Blog - Real World Tutorials, Happy Coding!: SQL: Subqueries

Tuesday, July 6, 2021

SQL: Subqueries

The easiest and simplest way to explain what a subquery is to say that it's a query within a query. For example if you want to get the employee that belongs to specific territory in the Northwind database without a join, you would have to use a subquery. Like the following subquery.

SELECT EmployeeID, (FirstName + ' ' + LastName) AS Name
FROM Employees
WHERE EmployeeID IN (SELECT EmployeeID 
       FROM EmployeeTerritories 
       WHERE TerritoryID=01581) 



Things You Should Know About Subqueries:
  • They are not the most efficient performance wise
  • You can only retrieve a single column in the subquery, retrieving multiple columns will throw an error
Another way to use subqueries is to use it with Aggregate functions like the query below, which gets the average price for the category with ID value of 1:

SELECT CategoryName,
 (SELECT AVG(UnitPrice) 
 FROM Products WHERE CategoryID = 1) AS AvgPrice
FROM Categories
WHERE CategoryID = 1






2 comments:

  1. E7E24BDB46
    When considering customization options for your apparel, dtf transfers offer a versatile and high-quality solution. They ensure vibrant, durable designs that withstand repeated washing, making them ideal for both personal projects and business orders. Many entrepreneurs and hobbyists alike are turning to dtf transfers for their ease of use and professional results. Overall, this method provides a reliable way to enhance clothing with intricate and eye-catching graphics.

    ReplyDelete

Search This Blog