[sql] How to subtract 30 days from the current date using SQL Server

I am unable subtract 30 days from the current date and I am a newbie to SQL Server.

This is the data in my column

date 
------------------------------
Fri, 14 Nov 2014 23:03:35 GMT
Mon, 03 Nov 2014 15:18:00 GMT
Tue, 11 Nov 2014 01:24:47 GMT
Thu, 06 Nov 2014 19:13:47 GMT
Tue, 04 Nov 2014 12:37:06 GMT
Fri, 1 Nov 2014 00:33:00 GMT
Sat, 5 Nov 2014 01:06:00 GMT
Sun, 16 Nov 2014 06:37:12 GMT

For creating the above column I used varchar(50) and now my problem is I want to display the dates for past 15-20 days from the date column can any one help with this issue ? update [ how can i display last 7 days dates in order

This question is related to sql sql-server sql-server-2008 sql-server-2012

The answer is


You can convert it to datetime, and then use DATEADD(DAY, -30, date).

See here.

edit

I suspect many people are finding this question because they want to substract from current date (as is the title of the question, but not what OP intended). The comment of munyul below answers that question more specifically. Since comments are considered ethereal (may be deleted at any given point), I'll repeat it here:

DATEADD(DAY, -30, GETDATE())

Try this:

SELECT      GETDATE(), 'Today'
UNION ALL
SELECT      DATEADD(DAY,  10, GETDATE()), '10 Days Later'
UNION ALL
SELECT      DATEADD(DAY, –10, GETDATE()), '10 Days Earlier'
UNION ALL
SELECT      DATEADD(MONTH,  1, GETDATE()), 'Next Month'
UNION ALL
SELECT      DATEADD(MONTH, –1, GETDATE()), 'Previous Month'
UNION ALL
SELECT      DATEADD(YEAR,  1, GETDATE()), 'Next Year'
UNION ALL
SELECT      DATEADD(YEAR, –1, GETDATE()), 'Previous Year'

Result Set:

———————– —————
2011-05-20 21:11:42.390 Today
2011-05-30 21:11:42.390 10 Days Later
2011-05-10 21:11:42.390 10 Days Earlier
2011-06-20 21:11:42.390 Next Month
2011-04-20 21:11:42.390 Previous Month
2012-05-20 21:11:42.390 Next Year
2010-05-20 21:11:42.390 Previous Year

TRY THIS:

Cast your VARCHAR value to DATETIME and add -30 for subtraction. Also, In sql-server the format Fri, 14 Nov 2014 23:03:35 GMT was not converted to DATETIME. Try substring for it:

SELECT DATEADD(dd, -30, 
       CAST(SUBSTRING ('Fri, 14 Nov 2014 23:03:35 GMT', 6, 21) 
       AS DATETIME))

SELECT DATEADD(day,-30,date) AS before30d 
FROM...

But it is strongly recommended to keep date in datetime column, not varchar.


Questions with sql tag:

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 Export result set on Dbeaver to CSV How to create temp table using Create statement in SQL Server? SQL Query Where Date = Today Minus 7 Days How do I pass a list as a parameter in a stored procedure? #1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’ MySQL Error: : 'Access denied for user 'root'@'localhost' SQL Server IF EXISTS THEN 1 ELSE 2 How to add a boolean datatype column to an existing table in sql? Presto SQL - Converting a date string to date format What is the meaning of <> in mysql query? Change Date Format(DD/MM/YYYY) in SQL SELECT Statement Convert timestamp to date in Oracle SQL #1292 - Incorrect date value: '0000-00-00' Postgresql tables exists, but getting "relation does not exist" when querying SQL query to check if a name begins and ends with a vowel Find the number of employees in each department - SQL Oracle Error in MySQL when setting default value for DATE or DATETIME Drop view if exists Could not find server 'server name' in sys.servers. SQL Server 2014 How to create a Date in SQL Server given the Day, Month and Year as Integers TypeError: tuple indices must be integers, not str Select Rows with id having even number SELECT list is not in GROUP BY clause and contains nonaggregated column IN vs ANY operator in PostgreSQL How to insert date values into table Error related to only_full_group_by when executing a query in MySql How to select the first row of each group? Connecting to Microsoft SQL server using Python eloquent laravel: How to get a row count from a ->get() How to execute raw queries with Laravel 5.1? In Oracle SQL: How do you insert the current date + time into a table? Extract number from string with Oracle function Rebuild all indexes in a Database SQL: Two select statements in one query DB2 SQL error sqlcode=-104 sqlstate=42601 What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types How to run .sql file in Oracle SQL developer tool to import database? Concatenate columns in Apache Spark DataFrame How Stuff and 'For Xml Path' work in SQL Server? Fatal error: Call to a member function query() on null

Questions with sql-server tag:

Passing multiple values for same variable in stored procedure SQL permissions for roles Count the Number of Tables in a SQL Server Database Visual Studio 2017 does not have Business Intelligence Integration Services/Projects ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database How to create temp table using Create statement in SQL Server? SQL Query Where Date = Today Minus 7 Days How do I pass a list as a parameter in a stored procedure? SQL Server date format yyyymmdd SQL Server IF EXISTS THEN 1 ELSE 2 'Microsoft.ACE.OLEDB.16.0' provider is not registered on the local machine. (System.Data) How to add a boolean datatype column to an existing table in sql? How to import an Excel file into SQL Server? How to use the COLLATE in a JOIN in SQL Server? Change Date Format(DD/MM/YYYY) in SQL SELECT Statement Stored procedure with default parameters Drop view if exists Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object How to update large table with millions of rows in SQL Server? Could not find server 'server name' in sys.servers. SQL Server 2014 How to create a Date in SQL Server given the Day, Month and Year as Integers Select Rows with id having even number A connection was successfully established with the server, but then an error occurred during the login process. (Error Number: 233) SQL Server: Error converting data type nvarchar to numeric How to add LocalDB to Visual Studio 2015 Community's SQL Server Object Explorer? Using DISTINCT along with GROUP BY in SQL Server Rebuild all indexes in a Database How to generate Entity Relationship (ER) Diagram of a database using Microsoft SQL Server Management Studio? The target principal name is incorrect. Cannot generate SSPI context How Stuff and 'For Xml Path' work in SQL Server? How to view the roles and permissions granted to any database user in Azure SQL server instance? How do I create a local database inside of Microsoft SQL Server 2014? Format number as percent in MS SQL Server MSSQL Regular expression How to select all the columns of a table except one column? SQL count rows in a table EXEC sp_executesql with multiple parameters 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 Remove decimal values using SQL query How to drop all tables from a database with one SQL query? How to get last 7 days data from current datetime to last 7 days in sql server Get last 30 day records from today date in SQL Server Using Excel VBA to run SQL query No process is on the other end of the pipe (SQL Server 2012) How to subtract 30 days from the current date using SQL Server Calculate time difference in minutes in SQL Server How to join two tables by multiple columns in SQL? The database cannot be opened because it is version 782. This server supports version 706 and earlier. A downgrade path is not supported

Questions with sql-server-2008 tag:

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? 'MOD' is not a recognized built-in function name Index was outside the bounds of the Array. (Microsoft.SqlServer.smo) Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls How to connect to SQL Server from command prompt with Windows authentication SQL-Server: Error - Exclusive access could not be obtained because the database is in use SQL query for getting data for last 3 months How to solve the system.data.sqlclient.sqlexception (0x80131904) error Reset identity seed after deleting records in SQL Server T-SQL split string based on delimiter How to generate a range of numbers between two numbers? I cannot start SQL Server browser How to execute function in SQL Server 2008 UPDATE if exists else INSERT in SQL Server 2008 SQL Server Insert if not exists OPTION (RECOMPILE) is Always Faster; Why? How to import a bak file into SQL Server Express How to set table name in dynamic SQL query? How to automatically generate unique id in SQL like UID12345678? SQL Server : export query as a .txt file Update Top 1 record in table sql server How to check SQL Server version How to display two digits after decimal point in SQL Server Import Excel Spreadsheet Data to an EXISTING sql table? Change NULL values in Datetime format to empty string Trouble using ROW_NUMBER() OVER (PARTITION BY ...) In SQL Server, how to create while loop in select Backup a single table with its data from a database in sql server 2008 Datetime BETWEEN statement not working in SQL Server Convert varchar dd/mm/yyyy to dd/mm/yyyy datetime Getting the current date in SQL Server? How to update Identity Column in SQL Server? replace NULL with Blank value or Zero in sql server Unpivot with column name SQL Server: Invalid Column Name Comma separated results in SQL if condition in sql server update query Conditional WHERE clause in SQL Server Combining (concatenating) date and time into a datetime how to convert date to a format `mm/dd/yyyy` How to add hours to current date in SQL Server?

Questions with sql-server-2012 tag:

Count the Number of Tables in a SQL Server Database SQL Server IF EXISTS THEN 1 ELSE 2 Get last 30 day records from today date in SQL Server No process is on the other end of the pipe (SQL Server 2012) How to subtract 30 days from the current date using SQL Server Possible to restore a backup of SQL Server 2014 on SQL Server 2012? SQL Server: Best way to concatenate multiple columns? SQL Server - An expression of non-boolean type specified in a context where a condition is expected, near 'RETURN' SSIS Excel Connection Manager failed to Connect to the Source Sql server - log is full due to ACTIVE_TRANSACTION Index was outside the bounds of the Array. (Microsoft.SqlServer.smo) SQL Server IIF vs CASE System.Data.SqlClient.SqlException: Login failed for user Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0 Conversion failed when converting from a character string to uniqueidentifier - Two GUIDs How to automatically generate unique id in SQL like UID12345678? How to restore a SQL Server 2012 database to SQL Server 2008 R2? The server principal is not able to access the database under the current security context in SQL Server MS 2012 The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions Insert Multiple Rows Into Temp Table With SQL Server 2012 Cannot execute script: Insufficient memory to continue the execution of the program Cannot Resolve Collation Conflict Correct way to select from two tables in SQL Server with no common field to join on Convert Date format into DD/MMM/YYYY format in SQL Server Cannot connect to SQL Server named instance from another SQL Server How can I use LTRIM/RTRIM to search and replace leading/trailing spaces? Recover unsaved SQL query scripts How to enable bulk permission in SQL Server SQL Server 2012 column identity increment jumping from 6 to 1000+ on 7th entry Last executed queries for a specific database New Line Issue when copying data from SQL Server 2012 to Excel SQL Server 2012 Install or add Full-text search How can I tell if a VARCHAR variable contains a substring? "No backupset selected to be restored" SQL Server 2012 Installing SQL Server 2012 - Error: Prior Visual Studio 2010 instances requiring update SQL Server 2012 can't start because of a login failure Enable remote connections for SQL Server Express 2012 Auto increment primary key in SQL Server Management Studio 2012 How do I import a .bak file into Microsoft SQL Server 2012? What is the connection string for localdb for version 11 Where is SQL Server Management Studio 2012? SQL Server Configuration Manager not found Insert/Update/Delete with function in SQL Server Find Locked Table in SQL Server How to check if a column exists in a SQL Server table?