16

I need to get rows from the database where the records are of one month. I tried this SELECT:

$result = mysql_query("SELECT * FROM my_table WHERE DATEPART('month', date_column)=11");

In database is a lot of rows that have a date in the 11. month, but i do not get any results. Can anyone help me? Thank!

Vérace
  • 854
  • 10
  • 41
user1827257
  • 1,600
  • 4
  • 17
  • 24
  • 1
    Please don't use the `mysql_*` functions as they are in the [deprecation process](http://news.php.net/php.internals/53799). Use [MySQLi](http://php.net/manual/en/book.mysqli.php) or [PDO](http://php.net/manual/en/book.pdo.php) instead and [be a better PHP Developer](http://jason.pureconcepts.net/2012/08/better-php-developer/). – Jason McCreary Nov 15 '12 at 16:34
  • with even minimal error handling, you'd have found out why this wasn't working: `$result = mysql_query(...) or die(mysql_error());`. never EVER assume a query succeeded. ALWAYS check for errors. – Marc B Nov 15 '12 at 17:20

4 Answers4

34

There is no DATEPART function in MySQL. Use MONTH(date_column) or EXTRACT(MONTH FROM date_column) instead.

MvG
  • 57,380
  • 22
  • 148
  • 276
6
    SELECT * FROM my_table WHERE MONTH(date_column)=11
Imre L
  • 6,159
  • 24
  • 32
2

If you have an index on date_column and you concern about performance it is better to NOT apply functions over the column. (Be aware that this solution, do not anwsers exactly what you asked, becouse it also involves the year)

-- For mysql specific:
SELECT * FROM my_table
WHERE date_column >= '2012-11-01' 
  and date_column < '2012-11-01' + INTERVAL 1 MONTH

(mysql fiddle)

-- For tsql specific:
SELECT * FROM my_table
WHERE date_column >= '2012-11-01'
  and date_column < DATEADD(month,1,'2012-11-01')

(tsql fiddle)

Saic Siquot
  • 6,513
  • 5
  • 34
  • 56
-1

If your DATEPART is not working in MySQL then you can use:

SELECT * 
FROM MyTable 
WHERE MONTH(joiningDate) = MONTH(NOW())-1 
  AND YEAR(joiningDate) = YEAR(NOW());

It will return all records who have inserted into MyTable in the last month.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Shubham Verma
  • 8,783
  • 6
  • 58
  • 79