No. | Title |
---|---|
1 | Explanation |
2 | Coding Example |
3 | Conclusion |
c) Subquery Types: The subquery is usually written within the WHERE or HAVING clause of the outer query. It can also be used in the SELECT or FROM clause, depending on the desired result.
d) Use Cases and Examples:
Retrieve all customers who have placed an order
SELECT * FROM customers WHERE customer_id IN (SELECT DISTINCT customer_id FROM orders);
Retrieve all customers sorted by the total amount they have spent:
SELECT customer_id, (SELECT SUM(amount) FROM orders WHERE customer_id = c.customer_id) AS total_spent
FROM customers c
ORDER BY total_spent DESC;
Retrieve all customers along with their total order count:
SELECT customer_id, (SELECT COUNT(*) FROM orders WHERE customer_id = c.customer_id) AS order_count
FROM customers c;
Retrieve all customers along with their latest order information:
SELECT c.customer_id, o.order_date, o.amount
FROM customers c
INNER JOIN orders o ON o.order_id = (SELECT MAX(order_id) FROM orders WHERE customer_id = c.customer_id);
Retrieve all customers with a flag indicating if they have placed an order:
SELECT customer_id, customer_name,
(CASE WHEN EXISTS (SELECT 1 FROM orders WHERE customer_id = c.customer_id) THEN 'Yes' ELSE 'No' END) AS has_order
FROM customers c;
e) Performance Considerations: The subquery is usually written within the WHERE or HAVING clause of the outer query. It can also be used in the SELECT or FROM clause, depending on the desired result.
Remember to always test and optimize your queries to ensure they perform well with your specific database and data volume.
SELECT CustomerName
FROM Customers
WHERE CustomerID IN (
SELECT CustomerID
FROM Orders
GROUP BY CustomerID
HAVING SUM(OrderAmount) > 500
);
SELECT EmployeeName
FROM Employees
WHERE Salary > (
SELECT AVG(Salary)
FROM Salaries
);