[Solved] How do you get a dynamic 12 business day view in Postgresql?
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

How do you get a dynamic 12 business day view in Postgresql?

Database type:

Here is the code I currently have that gives me the last 12 days

SELECT * 
FROM table
WHERE analysis_date >= current_date - interval '12' day;

analysis_date is the date column in the table. I understand why this isn't working because it's not accounting for business days. How can I rewrite this so that I get an interval of the last 12 business days?

I tried search online and found

extract(dow from (date))

But I couldn't find an example where I need a weekday interval. Any help would be appreciated.

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Avoid Selecting Unnecessary Columns (query line: 2): Avoid selecting all columns with the '*' wildcard, unless you intend to use them all. Selecting redundant columns may result in unnecessary performance degradation.
  2. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
CREATE INDEX table_idx_analysis_date ON "table" ("analysis_date");
The optimized query:
SELECT
        * 
    FROM
        table 
    WHERE
        table.analysis_date >= current_date - INTERVAL '12' day

Related Articles



* original question posted on StackOverflow here.