Could anyone advise how the SQL below retrieves what I want to retrieve?
There are tables ORDER_HEADER and ORDER_DETAILS for my Inventory System. The former records all the instances of orders that my company receives, whereas the latter order lines. Database-wise, the tables are designed as follows (* represents primary keys):
ORDER_HEADER: REQUEST__T*, ORDER_DATE, CUSTOMER__T
ORDER_DETAILS: REQUEST__T*, NO*, PRODUCT__T, QTY_NEEDED, QTY_SUPPLIED
Orders are recorded by the date and the issuer of the order (certain company made an order on so and so date). The primary keys for ORDER_DETAILS are REQUEST__T and NO. Each record in the ORDER_DETAILS table represents an order line. Each line in an order represents the product and the quantity ordered. Thus, a record in this table should express that the Nth line (NO) of the order (REQUEST__T) requires certain number (QTY_NEEDED) of products (PRODUCT__T) and, so far, certain number of them (QTY_SUPPLIED) have been supplied.
Orders are shipped to the customers only when each order lines has been provied with the products to the quantity needed. In order to retrieve such orders in ORDER_HEADER table, I created the following SQL and believe me it works. But I don't know why it works as I want it....
select *
from ORDER_HEADER a
where 0 = all
(select (QTY_NEEDED - QTY_SUPPLIED)
from ORDER_DETAILS b
where a.REQUEST__T = b.REQUEST__T)
The key for the SQL to work seems to me the join condition in the subquery: where a.REQUEST__T = b.REQUEST__T. Without it, the SQL retrieves no records since the subquery after ALL operator usually retrieves order lines where not all the quantity needed is supplied yet. The condition 0 = all (SUBQUERY) returning truth value FALSE, the main SELECT statement retrieves no data.
Yet, with the join condition, everything changes: the query works. The join condition seems to be working like "group by" for the ALL operator. Why does it work like this? I consulted several references but could not find how a Joined-Subquery Works After ALL Operator.