Home > Software design >  Is there any performance issue in this query
Is there any performance issue in this query

Time:06-20

I have a table like this

CREATE TABLE IF NOT EXISTS `test`.`job` (
  `id` BIGINT(20) NOT NULL,
  ...
  `creation_date` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `created_by` BIGINT(20) NOT NULL,
  `last_modified_date` DATETIME NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  `last_modified_by` BIGINT(20) NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  INDEX `test_date_idx` (`last_modified_date` DESC))
ENGINE = InnoDB;

and I would like to find the data that between a starting date and ending date with SQL

SELECT * FROM "test"
WHERE creation_date >= "{startingTime}"
AND creation_date <= "{endingTime}"

my boss said there maybe a performance issue if I use this SQL query and I would like to know what is the problem about the query?

CodePudding user response:

A couple of things:

  • To satisfy your query efficiently you need this index.

     ALTER TABLE job ADD INDEX creation (creation_date);
    

    MySQL can random-access it to the first eligible row, then scan it sequentially. Without it MySQL must examine every row in the table to find the eligible ones.

    MySQL handles queries like yours and queries using BETWEEN the same way.

  • Using SELECT * is usually less efficient than naming the columns you need. That's because your app often does not need all the columns. Retrieving and sending columns you don't need is a bit wasteful.

CodePudding user response:

Let's see the rest of the query. If it is more like

WHERE foo_id = 123
  AND creation_date >= "{startingTime}"
  AND creation_date <= "{endingTime}"

then this would be optimal:

INDEX(foo_id, creation_date)

{endingTime} is either clumsy or buggy.
Clumsy: It's no fun typing in 2020/02/29 23:59:59.
Clumsy and Buggy: 2020/03/01 00:00:00

The "buggy" comes because of having an extra midnight.

If the range is simply some number of days, consider:

  AND creation_date >= "{startindDate}"
  AND creation_date  < "{startindDate}"   INTERVAL {numDays}
  • Related