SQLite Forum

Not understanding a subquery - Some guidance?
Login
Which is exactly the same as this query:

```
         select * 
           from r
left outer join t 
             on t.task = (
                          select task 
                            from t 
                           where t.ritm = r.ritm 
                        order by ud desc 
                           limit 1
                         )
;
```

which has a requirement that the value of `task` is unique.  If it is not, it will not work.

if `ud` is already a datetime value (whether a naive ISO string, or some numeric representation of the datetime, so long as it is consistently defined across all rows) the wrapping the date function around `ud` does nothing except (a) use CPU time for no useful benefit and (b) create duplicates where none existed.

In the correlated subquery "from t where t.ritm" does not refer to an outer variable.  It will only ever refer to the inner table t.

Note that if `task` is only unique within `ritm` then you would have to use:

```
         select * 
           from r
left outer join t 
             on t.ritm = r.ritm
            and t.task = (
                          select task 
                            from t 
                           where t.ritm = r.ritm 
                        order by ud desc 
                           limit 1
                         )
;
```
and if r(ritm, task) is not unique then these solution methods will not (and cannot be made) to generate the output you claim to want.  You would have to depend on a method of projection (shown earlier) that does not have such dependencies.