'How to check the query has values and get the difference of the start date and end date in intervals in postgres SQL?

These are the summary of issue:

  • There is an issue of not going inside the if clause and data not inserted.
  • Need to compute the target_progress_date as the difference between the end_date and start_date and all the interval months to be computed and stored in the variable so as to insert into the project_target_progress table.

Viz: Start date :1-1-2021, End date : 1-12-2021 Months: 1-1-2021 1-2-2021 1-3-2021 .... 12-12-2021

// To check if any values are there
        $query_check = pg_query(DBCON,"select id , (COALESCE(revised_cost,administrative_sanction_project_cost,award_tender_project_cost) as cost, COALESCE(award_tender_contract_date,administrative_sanction_date,actual_start_date) as start_date, COALESCE(revised_completion_date,scheduled_completion_date)::date) as end_date from sp_index_v4 where id = $proj_id ");
        // If it has no null values then execute the logic - Autoset of target progress before editing it.
        if ($query_check != null) {
            console.log ('Hi'+$query_check);
        $query_cost = pg_query(DBCON,"select id ,(COALESCE(revised_cost,administrative_sanction_project_cost,award_tender_project_cost)/ datediff('month',COALESCE(award_tender_contract_date,administrative_sanction_date,actual_start_date)::date, COALESCE(revised_completion_date,scheduled_completion_date)::date)) as cost_of_one_month, TRUNC(((COALESCE(revised_cost,administrative_sanction_project_cost,award_tender_project_cost)/ datediff('month',COALESCE(award_tender_contract_date,administrative_sanction_date,actual_start_date)::date, COALESCE(revised_completion_date,scheduled_completion_date)::date))/ (COALESCE(revised_cost,administrative_sanction_project_cost,award_tender_project_cost)))*100,2) as cost_percent from sp_index_v4  id = $proj_id");
    // Insert for new project entry update for already having project
            $ins_query = "insert into project_target_progress(project_id,cum_financial_progress_in_cr,cum_financial_progress_in_percent,cum_physical_progress_in_percent,target_progress_date)values('$id',cost_of_one_month,cost_percent,cost_percent,start_date)";
            $insert_data = pg_query(DBCON, $ins_query);
}
        else {
            echo "Value cannot be inserted";
            console.log("inside the else block");
        }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source