I have two tables, called "Orders" and "Holidays"
The "Orders" table
orderId | orderDate
1 02-03-2017
2 02-03-2017
3 02-03-2017
4 02-03-2017
5 04-03-2017
6 04-03-2017
7 04-03-2017
8 04-03-2017
The "Holiday" table
holiId | holiDate
1 12-03-2017
2 02-06-2017
3 06-09-2017
4 02-03-2017
Then, I have this query
SELECT orderId, orderDate,
CASE WEHN hd.holiDate IS NOT NULL THEN 'HOLIDAY'
ELSE to_char(or.Day, 'DD-MON-YYYY') AS 'WEEKDAY'
FROM Orders or
LEFT JOIN Holiday hd
ON or.orderDate = hd.holiDate
This gives me sql results like the follwoings
orderId | orderDate | WEEKDAY
1 02-03-2017 HOLIDAY
2 02-03-2017 HOLIDAY
3 02-03-2017 HOLIDAY
4 02-03-2017 HOLIDAY
5 04-03-2017 SATURDAY
6 04-03-2017 SATURDAY
7 04-03-2017 SATURDAY
8 04-03-2017 SATURDAY
Basically, what I am doing is that I compare each row of the "Orders" table against the "Holiday" table by the "left join on" clause.
Then I mark each row as 'HOLIDAY' if there is any match. It works as intended but I am wondering if I can improve this query. In real situation, I would have a lot of rows having the same orderDate value.
When the database compares the first row of the "Orders" against the "Holiday" table, it will find that this current row matches one of the rows in "Holiday" table. So the database will mark it as 'HOLIDAY'.
Then, it will move to the next row and then do the same comparison operation against "Holiday" table.
Here is what I think "efficient way" can come in.
Now I already knew that 02-03-2017 is 'HOLIDAY' from the first-row's comparison. So I throught it would be more efficient to firstly compare current row's orderDate to previous one and then if they match, just use the previous row's WEEKDAY column's value. If they don't match, just do the comparison operation against the 'Holiday' table.
Is there any possible way of doing this??