2

I have one scenario where I want to have max value on date column,

eg. for table

CREATE TABLE IF NOT EXISTS `sample_table` (
  `id` TINYINT UNSIGNED NOTNULL,
  `name` VARCHAR(45) NOT NULL,
  `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARYKEY(`id`))
ENGINE = InnoDB;

So I used a query as below:

SELECT MAX(created_at) AS latest FROM sample_table;

But I was suggested to index created_at column and use following query for faster result

SELECT created_at FROM sample_table ORDER BY created_at DESC LIMIT 1;

I am clueless which is best way to do so? If second query is better, than why there is inbuilt MAX function

5
  • 2
    What does the execution plan say?
    – user1822
    Commented May 19, 2014 at 14:00
  • I have to use this query in PHP code, I tried running both queries using phpMyadmin but I get different results(execution time) every time. I am new to this so I am clueless why its showing different results Commented May 19, 2014 at 14:05
  • 1
    He means what does the result of EXPLAIN show. This is the command to find out how MySQL executes a query internally after all optimization has applied. They are likely the same. Commented May 19, 2014 at 18:26
  • Result of 1st query id => 1 select_type => SIMPLE type => ALL possible_keys => NULL key => NULL key_len => NULL ref => NULL rows => 52134 Extra => ____ 2nd query result id => 1 select_type =>SIMPLE type => ALL possible_keys => NULL key => NULL key_len =>NULL ref=>NULL rows=>50883 Extra => Using filesort Commented May 20, 2014 at 6:46
  • The difference will be noticed after you create the index on 'created_at'. Commented May 20, 2014 at 18:35

1 Answer 1

4

Add an index on created_at and use your first query:

SELECT MAX(created_at) AS latest FROM sample_table;

The suggestion you got is good in other situations, like if you want a max value of a field that is smaller than certain value. i.e.

SELECT created_at FROM sample_table WHERE created_at<"2014-01-01 00:00:00" ORDER BY created_at DESC LIMIT 1;
2
  • 2
    +1 it's also useful if you want other columns from the same row. Commented May 19, 2014 at 18:38
  • So there might be many such case where 1st query is better or in some place 2nd query, how do I judge it? Is there any reference document where I can get knowledge of these kind of hacks, or any tool where I can test it before using Commented May 20, 2014 at 6:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.