SQL must-know note the 11th Chapter uses subqueries

Source: Internet
Author: User

11.1 Sub-query

Any SQL statement that queries (query) is a query. However, this term generally refers to a SELECT statement.
SQL also allows you to create subqueries (subquery), which are queries that are nested within other queries.

11.2 Filtering with subqueries
SELECT cust_idFROM OrdersWHERE order_num IN(SELECT order_num                                   FROM OrderItems                                   WHERE prod_id = ‘RGA01‘);

In a SELECT statement, subqueries are always handled from inside out.

SELECT cust_name,cust_contactFROM CustomersWHERE cust_id IN(SELECT cust_id     FROM Orders     WHERE order_num IN(SELECT order_num          FROM OrderItems          WHERE prod_id = ‘RGA01‘));

Can only be a single column: a SELECT statement as a subquery can only query individual columns. An attempt to retrieve multiple columns will return an error.

11.3 Using subqueries as calculated fields

In order to execute count (*) for each customer, it should be used as a subquery.

SELECT cust_name,cust_state,(SELECT COUNT(*)      FROM Orders     WHERE Orders.cust_id = Customers.cust_id) AS ordersFROM CustomersORDER BY cust_name;

SQL must-know note the 11th Chapter uses subqueries

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.