SELECT min date for a varchar column - sql

The date column of my table is VARCHAR not datetime.
Eg
entry
'03/01/2011'
'03/22/2011'
'05/22/2010'
when I do a
SELECT min(entry) FROM table
I will get '03/01/2011' as it is the min in alphabetical order. I want to retrieve '05/22/2010' instead which is the min date. How do I convert the column to datetime and get the min.
Thanks

Assuming all entries are 'castable' as datetime:
SELECT MIN(CAST(entry as datetime))
FROM table
Assuming there might be some cases where entry isnt a datetime:
SELECT MIN(CAST(ISNULL(NULLIF(ISDATE([entry]),0),'31/12/9999') as datetime))
FROM table
If all records are a date column, as #Steve Wellens recommended, I would change the datetype to a datetime field to save future problems

I would fix your database schema. Change the column type to a datetime. Otherwise you'll have problems forever.

Make your varchar a date (or datetime) by using CAST or CONVERT of course.

Try CASTing it.
SELECT min(CAST(entry AS DATETIME)) FROM table
Hope this helps.

Related

How to find the wrong dates after an 'out-of-range value' error in SQL Server?

I want to convert a column in the format mm/dd/yyyy to datetime, but when I do I get the following error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
I found in other posts that this means that some dates don't make sense, such as 10/35/2021. I tried to find the wrong dates by slicing the varchars to get the dates with SUBSTRING(date, 3, 2) but it turns out some dates are in the form m/d/yyyy, so when I slice I get something like 1/.
I have no idea how to find the wrong dates, and how to (even though there are wrong dates) convert everything to datetime.
Thanks!
If some of your data is in MM/dd/YYYY and some M/d/yyyy this really makes for a bit of a mess. I would likely do something like this:
--Add a new varchar column (yes varchar) to save a copy of your bad data
ALTER TABLE dbo.YourData ADD BadDate varchar(10);
GO
--Change the data you have to the ISO format yyyyMMdd and store the bad data in the BadDate column
UPDATE dbo.YourData
SET DateColumn = CONVERT(varchar(8),TRY_CONVERT(date,DateColumn,101),112),
BadDate = CASE WHEN TRY_CONVERT(date,DateColumn,101) IS NULL THEN DateColumn END
WHERE DateColumn IS NOT NULL;
GO
--Change data type of your data column
ALTER TABLE dbo.YourData ALTER COLUMN DateColumn date NULL;
GO
--You can view your bad data with:
SELECT BadData
FROM dbo.YourData
WHERE BadData IS NOT NULL;
If you just want to locate rows with values that are obviously bad dates - disregarding any ambiguities - just use try_convert and check for NULLs
eg
with dates as (
select * from (values('01/02/2021'),('02/01/2021'),('33/02/2021'),('01/13/2021'))v(d)
)
select *
from dates
where Try_Convert(date, d) is null

Extra date from Datetime

I have a CSV file Date column with the following values:
StartDate
---------------------------
01/02/2014 0:00
09/04/2013 0:00
I want to extract only the date part from the above column value. I created the table with data type as Varchar, because if I declare it as DATETIME then I am not able to perform a bulk insert.
Date part alone you can extract using LEFT function.
(provided all your data in the format as you specified above)
select LEFT(colname,10)
You can BULK INSERT into a table where you will keep the data for intermediary storage. Try something like:
SELECT id, LEFT(CONVERT(VARCHAR, dateCol, 103), 10) FROM temptbl
Take a look at the following MSDN page for date formats available to you with CONVERT():
http://msdn.microsoft.com/en-us/library/ms187928.aspx
get the date part by splitting by "space"
cols[col_num].split(" ")[0]
and then make insert statement.
Why the table has datatype varchar?? why not date?

Converting datetime to short date from a declared table in sql

This is my first question on StackOverflow so I apologize for this most likely being formatted incorrectly. I am very new to sql language and am having trouble with the following query:
I have a declared table with one row selecting for a datetime (OccurrenceGroupID) and would like to have that date show up with short date formatting in the query results.
--Select for Occurrence Group
Declare #A3 table (OccurrenceGroupID datetime)
insert into #A3
select OccurrenceGroup as OccurrenceGroup,
Convert(VARCHAR(10),GETDATE(), 101) as [MM/DD/YYYY]
from tblOccurrenceGroup
where occurrencegroupid = #occurrencegroupid
I get the error message "Column name or number of supplied values does not match table definition."
Any help would be much appreciated.
Thanks.
Your error is because you are selecting two columns and trying to insert the result set into a table with only one column.
Regardless of this you are converting a datetime to a varchar presumably for presentation reasons and then wanting to insert it into a column of type datetime which doesn't make much sense. Always leave the formatting of dates to the client application.
you have declared it as datetime
Declare #A3 table (OccurrenceGroupID datetime)
so it expects a date and a time you the go on to say
Convert(VARCHAR(10),GETDATE(), 101) as [MM/DD/YYYY]
you then say convert the varchar as MM/DD/YYYY therefor it is contradictory to your first statement

SQL Server default date time stamp?

I have a field that when something is inserted I want it to get the current Date & Time and insert this into the database. Is there a way to get the date & time, and set it as the default value?
Currently the default value is: (getdate()) Which sets only the date. How do I also set the time?
GETDATE() is a date and time in SQL Server.
Run SELECT GETDATE() to verify this.
What is the datatype of your field? If it's DATE then it will not hold time values as well.
One easy way is to give the field a default constraint:
create table YourTable
(
... other columns ...
CreateDt datetime default getdate(),
... other columns ...
)
A disadvantage of this method is that you can overwrite the value by specifying it in an insert clause.
Personally I would like to use GETUTCDATE() instead GETDATE() to avoid confusions.
SYSDATETIME() will get the current date and time.
Make sure the data type of the column is datetime, and not just date or it won't be able to hold a datetime.
Most SQL implementations (engines) do have CURRENT_TIMESTAMP function.

inserting only date in a column in sql server

Is there a way to insert only date in a datetime column in sql server without the time?
for example
date (datetime)
===============
12-01-2000
16-02-2000
or i should store this as a varchar and cast it when retriving so that i can convert to whatever form i need.
my solution is to store it as varchar and convert it to datetime whenever needed
SELECT CONVERT(VARCHAR(10),GETDATE(),111) -- get datepart only
or
also check this post about creating date type :
create user defined data types:
create type Date from dateTime
http://weblogs.sqlteam.com/jeffs/archive/2007/10/31/sql-server-2005-date-time-only-data-types.aspx
If you are using SQLServer 2008 you can use the date data type.
The following SQL will strip out any time values and set them all to zero. So you won't need to worry whether a time value is there or not.
Select Cast(Floor(Cast(MyDateColumn as float)) as DateTime) as MyDateColumn
From dbo.MyTable
Just use smalldatetime or date. Convert your dates to your format before you update your date values or after you select date values in your app.
You can change format of date format in sql queries or in your app.
Here is a list on date formats in sql
http://www.sql-server-helper.com/tips/date-formats.aspx
Here's a link on date data types
http://databases.about.com/od/sqlserver/a/date_time.htm
Good Luck!