SQL Date Function

SQL Date

When we deal with dates, the most difficult task is probably to ensure that the format of the date we insert matches the format of the date column in the database.

As long as the data contains only the date part, running the query will not cause any problems. However, if it involves time, the situation is a bit complex.

Before discussing the complexity of date queries, let's first look at the most important built-in date processing functions.

MySQL Date Functions

The following table lists the most important built-in date functions in MySQL:

Function Description
NOW() Return the current date and time
CURDATE() Return the current date
CURTIME() Return the current time
DATE() Extract the date part of a date or date/time expression
EXTRACT() Return the individual parts of the date/time
DATE_ADD() Add a specified time interval to a date
DATE_SUB() Subtract a specified time interval from a date
DATEDIFF() Return the number of days between two dates
DATE_FORMAT() Gina datti/zaɗaɗa datti dona yin datti da dacewa datti yin datti:

SQL Server Date Functions

The following table lists the most important built-in date functions in SQL Server:

Function Description
GETDATE() Return datti/zaɗaɗa datti dona yin datti yin datti:
DATEPART() Return datti/zaɗaɗa datti dona yin datti yin datti:
DATEADD() Adda ko subtracta datti dona yin datti yin datti:
DATEDIFF() Return datti datti dona yin datti yin datti:
CONVERT() Gina datti/zaɗaɗa datti dona yin datti da dacewa datti yin datti:

SQL Date data type

MySQL yana gina datti yin data type dona yin daikiwa datti yin daikiwa yin datti/zaɗaɗa datti yin datti:

  • DATE - تنسيق YYYY-MM-DD
  • DATETIME - تنسيق: YYYY-MM-DD HH:MM:SS
  • TIMESTAMP - تنسيق: YYYY-MM-DD HH:MM:SS
  • YEAR - تنسيق YYYY أو YY

يستخدم SQL Server النوع التالي من البيانات لتحديد التواريخ أو قيم التاريخ/الوقت في قاعدة البيانات:

  • DATE - تنسيق YYYY-MM-DD
  • DATETIME - تنسيق: YYYY-MM-DD HH:MM:SS
  • SMALLDATETIME - تنسيق: YYYY-MM-DD HH:MM:SS
  • TIMESTAMP - تنسيق: رقم واحد فقط

معالجة التواريخ SQL

إذا لم يكن هناك جزء الوقت، يمكننا مقارنة تواريخ بسهولة!

لنفترض أن لدينا جدول "Orders" التالي:

OrderId ProductName OrderDate
1 الحاسوب 2008-12-26
2 الطابعة 2008-12-26
3 الشيفرة 2008-11-12
4 الهاتف 2008-10-19

الآن، نريد منح سجلات OrderDate هي "2008-12-26" من الجدول السابق.

نستخدم جملة SELECT التالية:

SELECT * FROM Orders WHERE OrderDate='2008-12-26'

نتائج البحث:

OrderId ProductName OrderDate
1 الحاسوب 2008-12-26
3 الشيفرة 2008-12-26

الآن لنفترض أن "Orders" مشابه لهذا (لاحظ جزء الوقت في عمود "OrderDate"):

OrderId ProductName OrderDate
1 الحاسوب 2008-12-26 16:23:55
2 الطابعة 2008-12-26 10:45:26
3 الشيفرة 2008-11-12 14:12:08
4 الهاتف 2008-10-19 12:56:10

إذا استخدمنا جملة SELECT أعلاه:

SELECT * FROM Orders WHERE OrderDate='2008-12-26'

لن نحصل على نتيجة. هذا بسبب أن التاريخ في الاستعلام لا يحتوي على جزء الوقت.

إشارة:إذا كنت ترغب في جعل الاستعلام بسيطًا وسهلًا الت mantenance، فلا تستخدم جزء الوقت في التاريخ!