SQL Querying - Matching datetimes vs Matching integers

I have a bunch of data in my database and I want to filter out data that has been saved for over a week. I am using SQLServer and I found that I can use the function DATEDIFF

.

At the moment it works fine and fast, but at the moment I don't have a lot of entries, so everything works pretty smoothly.

After doing some research on the internet, I found out that comparing integers in databases is faster than comparing strings, my guess at this point is that comparing datetimes (using this function) is even slower on a large scale.

Let's say the content of my database table looks like this: enter image description here

I am currently filtering out entries that are older, for example a week later:

SELECT * FROM onlineMainTable WHERE DATEDIFF(wk, Date, GETDATE()) > 1

      

I am guessing that this query will be quite slow if there are a thousand rows in the table.

The status column represents the state of the computation, I wondered if I would speed up the process if I looked for a specific status instead of matching dates, for me to set this status to one that represents "old records" "I need to update these rows before how I choose them it will look something like this:

UPDATE table SET Status = -1 WHERE NOT Status = -1 AND DATEDIFF(wk, Date, GETDATE()) > 1;
SELECT * FROM table WHERE Status = -1;

      

I used "-1" as an example.

So obviously I could be wrong, but think's update would be fast enough in this case, since so many records won't be updated since the old ones have already been updated with its status. The selection will be faster as I will be matching integers instead of datetimes.

The downside to my (possible) solution is that I will query twice every time I receive data, even if it may not be necessary (if each row is more than one week old).

It boils down to this: should I compare the datetime or should I update an integer column based on that datetime and then select using a comparison of those ints?

If there is another / better way to do this, I am all ears.

Context I am making a webapp for requesting quotes. Requests must expire in a week as they will not be valid at this point. I need to display valid requests and expired requests (so that customers have an overview). All of these queries are stored in a database table.

+3


source to share


1 answer


Indexes are objects that are projects to improve the results of select queries, the disadvantage is that they slow down delete and update operations, so they need to be used when needed. Typically DBMSs provide tools to explain the query execution plan.

Maybe you just need to add an index to the Date column:

create index "index_name" on onlineMainTable(Date)

      



and the request can be

 SELECT * FROM onlineMainTable WHERE Date > DATEADD(week,-1,GETDATE());

      

+2


source







All Articles