Hi,
Correlated queries work here because correlated queries run once for each row in the outer dataset. So, for each record, find the one with the next highest date, and then check if it is less than 1 hour in the future. SQL will repeat that process for each row, so you can check each record, though not necessarily "in order" - all you can be sure is that all of them will be checked. Aliasing the outer table Table1 as t1 is essentially so it can be used in the inner query to reference a field value in the outer query.
I read the linked page quickly. I agree with the general statement that tables should never be assumed to have order. However, I don't agree that you have to use vba or cursors to find records that are "next" or "previous". Just like any numbers, you can use sql comparative operators with min() or max() to find them, even if they are not in order (the smallest number that is bigger than this one is "next"). It might be overkill to say SQL has no concept of next or previous - I find it a little too black and white. Next is a semantic concept that can be defined as part of your data, and if SQL needs to handle it, it can. We probably do it more often than we realize - a payment will be applied to the oldest outstanding invoice, then the "next" one, and so on. A student waiting list will assign open seats to the first student on the waiting list, then the "next" one. You may in practice choose to implement this with code or even with cursors, but nothing necessarily prevents you from using SQL if you want to.
I wouldn't object to using cursors or vba, by the way. It would be worth testing to see if the extra overhead creating cursors objects pays off with faster processing or not. An indexed data field should allow for faster searching using binary search techniques so it shouldn't be terribly slow but correlated queries in general are going to perform worse than most queries due to the nature of the beast. In this particular case, ordering the records and then going one by one (in order
) may work efficiently if speed is a concern.
I don't know about the aliasing - if you mean I didn't use the keyword AS, then yes that is optional. I believe in the subquery the t2 alias is also option (the table could be unaliased) - that's how I'd do it in SQL Server. But I would need to test it to be sure in MSAccess:
Code:
where (select min(t2.MyField) from Table1 t2 where t2.MyField > t1.MyField)
Or:
Code:
where (select min(MyField) from Table1 where MyField > t1.MyField)