[sql] How to select data from 30 days?

I have query:

SELECT name
FROM (
SELECT name FROM 
Hist_answer
WHERE id_city='34324' AND datetime >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH)
UNION ALL
SELECT name FROM 
Hist_internet
WHERE id_city='34324' AND datetime >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH)
) x
GROUP BY name ORDER BY name

But DATE_SUB is a MySQL function and I need function for MsSQL 2008

Tell me please how to select data from 30 days by using MsSQL 2008?

P.S.: Data type of datetime is smalldatetime

This question is related to sql sql-server-2008 keyword smalldatetime

The answer is


Short version for easy use:

SELECT * 
FROM [TableName] t
WHERE t.[DateColumnName] >= DATEADD(month, -1, GETDATE())

DATEADD and GETDATE are available in SQL Server starting with 2008 version. MSDN documentation: GETDATE and DATEADD.


For those who could not get DATEADD to work, try this instead: ( NOW( ) - INTERVAL 1 MONTH )


Try this : Using this you can select date by last 30 days,

SELECT DATEADD(DAY,-30,GETDATE())

Examples related to sql

Passing multiple values for same variable in stored procedure SQL permissions for roles Generic XSLT Search and Replace template Access And/Or exclusions Pyspark: Filter dataframe based on multiple conditions Subtracting 1 day from a timestamp date PYODBC--Data source name not found and no default driver specified select rows in sql with latest date for each ID repeated multiple times ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database

Examples related to sql-server-2008

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object How to Use Multiple Columns in Partition By And Ensure No Duplicate Row is Returned SQL Server : How to test if a string has only digit characters Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query Get last 30 day records from today date in SQL Server How to subtract 30 days from the current date using SQL Server Calculate time difference in minutes in SQL Server SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904) SQL Server Service not available in service list after installation of SQL Server Management Studio How to delete large data of table in SQL without log?

Examples related to keyword

How to select data from 30 days? How to use "raise" keyword in Python Python: SyntaxError: keyword can't be an expression Understanding implicit in Scala How do I create sql query for searching partial matches? What is the native keyword in Java for? Difference between "this" and"super" keywords in Java Equivalent of "continue" in Ruby What is the equivalent of the C# 'var' keyword in Java? Is there a goto statement in Java?

Examples related to smalldatetime

How to select data from 30 days? check for null date in CASE statement, where have I gone wrong?