Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - Last Day Of Quarter (Most Efficient Way)

Tags:

mysql

I've seen a few other examples of this for SQL, but I am looking particularly for MySQL.

This is the code I have (which works, but I think it's drastically inefficient). I am using the arbitrary date '2011-05-15' which should and does return '2011-06-30'.

DATE_SUB( 
    DATE_ADD( 
        CONCAT( 
            YEAR( CURDATE() ), 
            '-01-01' 
        ), 
        INTERVAL QUARTER('2011-05-15') QUARTER 
    ), 
    INTERVAL 1 DAY
)

What is the better way to do this?

like image 548
Kerry Jones Avatar asked Aug 04 '11 22:08

Kerry Jones


People also ask

How do I get last quarter in MySQL?

QUARTER() function MySQL QUARTER() returns the quarter of the year for a date. The return value is in the range of 1 to 4. Syntax: QUARTER(date);

What is Date_add in MySQL?

The DATE_ADD() function adds a time/date interval to a date and then returns the date.

What is Date_sub in MySQL?

The DATE_SUB() function subtracts a time/date interval from a date and then returns the date.

Which function in MySQL can be used to get the date after 1 month?

Use the MONTH() function to retrieve a month from a date/datetime/timestamp column in MySQL. This function takes only one argument – either an expression which returns a date/datetime/ timestamp value or the name of a date/datetime/timestamp column.


1 Answers

In general, built-in functions in MySQL are very fast compared to other things like disk and memory I/O so they have little impact on efficiency.

You could probably save some milliseconds by getting rid of string conversions:

SELECT  MAKEDATE(YEAR(CURDATE()), 1) + INTERVAL QUARTER(CURDATE()) QUARTER - INTERVAL 1 DAY

but, again, I wouldn't even worry for such optimizations.

like image 156
Quassnoi Avatar answered Oct 11 '22 00:10

Quassnoi