Getting the first day in a week with T-SQL

A colleague just asked me if I knew a way to get the first day in a week in SQL Server. While I'm sure that there are many ways to get the first day (date) in a week here is a very simple way that in my opinion is quite elegant. The example assumes that you want to get the date of the first day in the week that GETDATE() is in. You could of course replace GETDATE() with a column of the datetime type.

SELECT DATEADD(ww, DATEDIFF(ww,0,GETDATE()), 0)

The same method can be used to extract only the date part from a datetime in T-SQL:

DATEADD(dd, DATEDIFF(dd,0,GETDATE()), 0)

PS. For updates about new posts, sites I find useful and the occasional rant you can follow me on Twitter. You are also most welcome to subscribe to the RSS-feed.

Comments

  1. Donna's avatar

    Donna 6 months ago

    I've been searching around the internet for a simple solution to get the first date of the week for a couple of hours. Thank you for this post, it was exactly what I needed!

  2. Graham Charles's avatar

    Graham Charles 2 months ago

    Useful, although for me this always returns a Monday -- and not the day set in SET DATEFIRST. I'm still puzzling over why...

  3. GG's avatar

    GG 13 days ago

    This gets me always the first Monday in a week, but not the first day of the week, nor the Monday of a week assuming Monday is the first day. For example, if I use a Sunday instead of getdate(), it'll return the following day, the Monday, not the Monday six days earlier.

Add a comment

Allowed tags: <b>, <em>, <quote cite="">, <code>, <c-sharp-code>, <css-code>, <sql-code>, <xml-code>, <javascript-code>. If you want to display code examples, please remember to write &lt; for < and &gt; for >.

Follow me on Twitter

  1. Bookmarked: Google Scribe http://bit.ly/9iDp8s 2 days ago
  2. Blogged: The future of EPiMVC http://bit.ly/ck6EPg #episerver 2 days ago
  3. At Skånegläntan, as always #parentalleave 2 days ago
follow me

Latest comments

  1. N.Stronge wrote "Anabolic Steroid Online Shop allanabolics.com has been desig..." on Invoking methods based on a parameter without if-else statements in C#
  2. Svante wrote "Yes, I noticed that it was a singleton, and I guess the real..." on Something to beware of when using EPiAbstractions and an IoC container
  3. Joel Abrahamsson wrote "Well, first of all you wont get any arguments from me regard..." on Something to beware of when using EPiAbstractions and an IoC container

About this site

This blog is built with EPiServer Community, EPiServer CMS, ASP.NET MVC and a bunch of other great products. The source code is available for download at the projects page, where you also can read more about this site and my other projects.

read more