Consider this myTable
that has some same-day records:
+-----+---------------------+---------------------+
| id | start_date | end_date |
+-----+---------------------+---------------------+
| 1 | 2017-07-17 12:00:00 | 2017-07-17 14:00:00 |
| 2 | 2017-07-17 8:00:00 | 2017-07-17 11:00:00 |
| 3 | 2017-07-17 13:00:00 | 2017-07-17 15:00:00 |
+-----+---------------------+---------------------+
And let's say I would like to get records that overlap 12:00:00 -> 14:00:00
(where 12->14 is target).
Essentially, records that are valid for (RecordStart <= TargetEnd) and (RecordEnd >= TargetStart)
I can do that with one of the following:
1- Condition in sql statement:
const myQuery =
"SELECT * FROM myTable " +
"WHERE start_date <= '" + target_end_date +
"' AND '" + target_start_date + "' <= end_date";
let filtered = DbConnection.query(myQuery)
2- Condition in code:
const myQuery = "SELECT * FROM myTable";
let records = DbConnection.query(myQuery)
let filtered = [];
records.map((rec) => {
if(Date.parse(rec.start_date) <= Date.parse(target_end_date) && Date.parse(target_start_date) <= Date.parse(rec.end_date) )
filtered.push_back(rec)
})
Which practice I should follow?
And more general, choosing the best practice is case oriented? Does it depend on how large the db is and/or how big would the result be? Or there is some knowledge that I still don't know about sql vs code?
As a programmer, Do I build both approaches for each use case and test to then choose?
EDIT:
Taking into consideration that every processing-related/querying thing is gonna happen on the API side, then filtered
(which is same final result for both approaches) will be sent through the network back to client.