How to Filter using SQL IsDate() Function and Cast

Video: SQL IsDate() Function as a Filter

Using the SQL IsDate() Function in your filter needs a little trick to make it work.

In your career you may run into an issue where you have a date stored as a varchar.

When this happens, you may need to use the SQL IsDate in the Where Clause.

You need to first use the SQL IsDate Function to check if the value is a valid date.

Then you can convert the varchar to a date using Cast or Convert.

Even though you have filtered on the SQL Isdate, you might still have a problem with the conversion.

This video shows you how to deal with it.

I don’t mention it in the video, but when dealing with dates, you always have to keep in mind the default date settings of the database.

Cast and Isdate use these defaults and could cause you some trouble if you aren’t aware of them.

Here are the scripts to run the queries that are in the video.

create table emp
(
id int primary key identity(1,1)
,emp_name varchar(50)
,emp_birthday varchar(20)
)
GO
insert into emp (emp_name,emp_birthday) values ('Bob','12/12/2001');
insert into emp (emp_name,emp_birthday) values ('Mary','123');
insert into emp (emp_name,emp_birthday) values ('Jill','12/1/2005');
insert into emp (emp_name,emp_birthday) values ('Jim','1/12/1999');
insert into emp (emp_name,emp_birthday) values ('Sue','7/15/2011');
insert into emp (emp_name,emp_birthday) values ('Sally','20120315');
GO

select id,emp_name,emp_birthday
,isdate(emp_birthday)
from emp
where isdate(emp_birthday)=1
and 
case when isdate(emp_birthday)=0 then cast(null as date)
    else cast(emp_birthday as date)
end < '1/1/2006'

Here is the YouTube Video SQL Isdate Function as a Filter with Cast .

Tags: , , , , ,

Facebook Comments:

Leave A Reply (2 comments so far)


  1. Rade Radumilo
    83 days ago

    I’d like to see a performance comparison on large tables, with this:
    select id. emp_name, emp_birthday
    from (
    select id, emp_name, emp_birthday.
    from emp.
    where emp_birthday like ‘[0-1][0-9]/[0-3][0-9]]/[1-2][0-9][0-9][0-9]‘ –use whatewer format you need.
    ) a
    where cast(emp_birthday as date) < '1/1/2006'.


  2. Joey Blue
    82 days ago

    That would be interesting. I can think of many different ways to attack this problem.

    As we start moving toward the issue of scale and if the column starts to become important, we will want to consider changing the column datatype to a date.

About Me

Joey BlueI'm .
I am here to help you with SQL, Reporting, BigData, and all things Database...
Read More
Link to myFacebook Page
Link to myPinterest Page
Link to myRss Page
Link to myTwitter Page
Link to myYoutube Page
FREE SQL Training Programs.  I will send you online videos on SQL queries.