Baker2795 Baker2795 - 2 months ago 8
SQL Question

How do I format a date in SQL?

I have to meet the condition that the purchase date is before 2012 and I can't figure out how to format my SQL code to get this right.

My current code:

SELECT g.GameName, p.GameID, g.GameID
FROM games g, purchases p
WHERE p.GameID = g.GameID
AND p.DatePurchase < 2012-01-01


And the database is formatted in the same was (as in '2012-06-15') but when I run this code it runs but I get 0 results.

Answer
SELECT g.GameName, p.GameID, g.GameID 
FROM games g, purchases p 
WHERE p.GameID = g.GameID
AND p.DatePurchase < '2012-01-01'

If the date stored in the database is in datetime format, then just cast it as Date. Please look at the below code

   SELECT g.GameName, p.GameID, g.GameID 
   FROM games g, purchases p 
   WHERE p.GameID = g.GameID
   AND CAST(p.DatePurchase AS DATE) < '2012-01-01'