devxlogo

Date Time Fields

Date Time Fields

Question:
I have a database with a DateTime field of the following structure 1974-01-18T00:00:00′. How do I query it so that I can extract the dates with a particular day and month but any year?

Answer:
The datepart function in SQL will retrieve a portion of the date:

create table datesearch(	mydate datetime)goinsert into datesearch values ('01/01/2000')insert into datesearch values ('01/02/2000')insert into datesearch values ('01/03/2000')insert into datesearch values ('02/01/2000')insert into datesearch values ('02/02/2000')insert into datesearch values ('02/03/2000')goselect *from datesearchwhere datepart(dd,mydate) = 2

It will return only the rows where mydate falls on the second day of the month.

However, before writing such a query, you should consider the performance you will get from it. In order to test the performance, I created a sample table and populated it with 500,000 rows:

set nocount ongodrop table datesearchgocreate table datesearch(	id int identity(1,1) not null	constraint pk_datesearch primary key(id),	invoicedate datetime,	clientid  int,	amount numeric (9,2))godeclare @i int, @invoicedate datetime,@clientid int, @amount numeric(9,2)select @i = 0while @i < 500000begin	select @invoicedate = dateadd(dd,cast (rand() * 5000 as int),getdate())	select @clientid = cast(rand() * 500 as int)	select @amount = rand() * 500000	insert into datesearch(invoicedate,clientid,amount)	values			(@invoicedate,@clientid,@amount)	select @i = @i + 1end		gocreate index ak_datesearch_invoicedate on datesearch(invoicedate)

I then used the following two queries to compare the statistics and the showplan:

select count(*)from datesearchwheredatepart(dd,invoicedate) = 20select count(*)from datesearchwhereinvoicedate between '10/01/2000' and '12/01/2000'

The query that used datepart performed a table scan while the second query used the index on invoicedate. If you find that you are suffering a performance hit, you might choose to add another column to your table to represent just the day of the month (or whatever other value) you are searching on and index it. This is different than adding a computed column because in version 7 you can't index on a computed column.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist