Querying Records of the Last 3 Days with SQL – DATEDIFF

21.03.2025
3.129
Querying Records of the Last 3 Days with SQL – DATEDIFF

If we want to query the records of the last 2 days or the last 3 days or the last 1 week or the last 1 week or the last 1 month from the records in our database using the Sql Datediff query, how should we follow?

For this, we can solve it both in SQL and with the programming platform we use. No need to waste time writing methods or functions. Of course these are methods, but in a very simple way we can write a few things to answer this request.

First of all, what we are going to write applies to MS-SQL. It may not be compatible with MySQL. At the end of the SQL query, we will use the Sql DATEIFF query after the Where statement.

DATEDIFF ( datepart , startdate , enddate )

This statement;

By typing “day, month, year, hours, minutes or seconds” in the first argument, datepart, we specify that we will sort by day, month or year.

In the 2nd part, although startdate means the start date, it asks for the name of the field you will reference. For example, if we want to query the database according to the date of birth or transaction date fields, you write the name of that field here.

In the 3rd part, in the enddate section, you can get the date of that day with getdate().

We have defined these descriptions for the last 2 or 3 days. If you are going to make transactions between certain dates, you can write values to the parameters accordingly. You can see the records made in the last 3 days with the example below.

SELECT ad,soyad,d_tarihi FROM ozluk_tablosu 

WHERE  DATEDIFF(day, islem_tarih, getdate()) BETWEEN 0 AND 2

ORDER BY islem_tarihi DESC
SQL
Likewise, to query last month's records;
SELECT ad,soyad,d_tarihi FROM ozluk_tablosu 

WHERE  DATEDIFF(month, islem_tarih, getdate()) BETWEEN 0 AND 2

ORDER BY islem_tarihi DESC
SQL

The important point to note is that the type of the field named islem_date in the database must be“DATETIME“.
Otherwise the query may not work.

MAKE A COMMENT
COMMENTS - 0 COMMENTS

No comments yet.

Bu web sitesi, bilgisayarınıza bilgi depolamak amacıyla bazı tanımlama bilgilerini kullanabilir.
Bu bilgilerin bir kısmı sitenin çalışmasında esas rolü üstlenirken bir kısmı ise kullanıcı deneyimlerinin iyileştirilmesine ve geliştirilmesine yardımcı olur.
Sitemize ilk girişinizde vermiş olduğunuz çerez onayı ile bu tanımlama bilgilerinin yerleştirilmesine izin vermiş olursunuz.
Çerez bilgilerinizi güncellemek için ekranın sol alt köşesinde bulunan mavi kurabiye logosuna tıklamanız yeterli. Kişisel Verilerin Korunması,
Gizlilik Politikası ve Çerez (Cookie) Kullanımı İlkeleri hakkında detaylı bilgi için KVKK&GDPR sayfamızı inceleyiniz.
| omersahin.com.tr |
Copyright | 2007-2025