1

I have this query I have to automate with AWS Lambda but first I want to optimize it.

It seems legit to me but I have this feeling I can do something to improve it.

SELECT q_name, count(*)
FROM myTable
WHERE status = 2
AND DATEDIFF(mi, create_stamp, getdate()) > 1
GROUP BY q_name
5
  • 1
    Wouldn't create_stamp > getdate() be simpler?
    – Steve Ford
    Commented Jan 17, 2022 at 19:41
  • @SteveFord Yes, it's simpler, but it also does mean something different ... Commented Jan 17, 2022 at 19:59
  • what indexes do you have on the table? Commented Jan 17, 2022 at 20:05
  • I'm not sure about the indexes. I have a problem with the database at the moment. Asked for help and it should be up and running. Will get back soon as it does Commented Jan 17, 2022 at 20:15
  • 1
    You probably want an index on either (status, q_name) INCLUDE (create_stamp) or (status, create_stamp) INCLUDE (q_name) depending on the density statistics of q_name Commented Jan 17, 2022 at 22:00

1 Answer 1

9

The only improvement I can see is not to apply a function to your column, because that makes the query unsargable (unable to use indexes). Instead leave the column as it is and calculate the correct cutoff.

SELECT q_name, count(*)
FROM myTable
WHERE [status] = 2
--AND DATEDIFF(mi, create_stamp, getdate()) > 1
-- Adjust the logic to meet your requirements, because this is slightly different to what you had
AND create_stamp < DATEADD(minute, -1, getdate())
GROUP BY q_name;

Note, while dateadd does accept abbreviations for the unit to add, its much clearer to type it in full.

3
  • datediff(minute,a,b) > 1 means that 2 or more minute boundaries separate a and b, but that may not have been intentional by OP. Commented Jan 17, 2022 at 19:49
  • 1
    @DavidBrowne-Microsoft thanks - yip I realise that, I assumed they would check their logic.
    – Dale K
    Commented Jan 17, 2022 at 19:50
  • 1
    Yes. Your query is probably more what they meant: the two dates are separated by more that 60sec. Not the two dates are separated by at least 61-120 seconds, depending on when you check. Commented Jan 17, 2022 at 19:53

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