Postgresql – Mealplan: Allow ordering until 9am

datetimepostgresql

Imagine you have a meal service and everyday there is a different meal which customers can order.

Mon, Dec 12: Pasta
Tue, Dec 13: Pizza
Wed, Dec 14: Gnocci

Orders are possible until 9am.

This mean Monday on 8am customers may order Pasta for today, at 9:15am they are no longer allowed to order for today.

How to handle this is with PostgreSQL.

I see two ways:

  1. Create a cron job which switches the column "orderable" to False.
  2. Create a view which calculates the field "orderable" on the fly.

Is there a feasible third or forth way?

Which way is simple and robust?

Best Answer

As long as you have the dates in a date column, you can use a simple CASE to choose, which meal is selected.

The result if the query, depends when you look for the example, it will choose pasta before 9 in the morning a Minute later and you would get gnocchi, you only have to enter the menus ahead of time

In an event you could delete the old menus, but that is not necessary, as you will not have millions of rows.

CREATe TABLe "OrDERS" ("orderdate" date, "food" varchar(40))
INSERT INTO "OrDERS" VALUES (CURRENT_DATE  ,'Pasta'), (CURRENT_DATE  + INTERVAL '1 day','Gnocchi')
SELECT to_char("orderdate",'Dy, Mon DD'), "food" FROM "OrDERS" 
WHERE "orderdate" = 
       CASE WHEN NOW() < now()::date + interval '9h' THEN now()::date
            ELSE now()::date + INTERVAL '1 day'
       END
to_char     | food  
:---------- | :-----
Tue, Dec 22 | Gnocci

db<>fiddle here