SQL: How To Select Earliest Date - sql

I have a date column & I am simply trying to know the earliest date. I use the command:
select Min(Install_date) From PocketGemsSchema.pocketgemstable2;
This returns 1-Dec-17
But the minimum date from my sample data is actually 1-Nov-17.
Can anyone help please?

Try this:
If your Install_date contain datatype varchar than
SELECT MIN(CAST(Install_date AS DATE))
FROM PocketGemsSchema.pocketgemstable2
SELECT FORMAT(MIN(CAST(Install_dateAS DATE)), 'dd-MMM-yy ')
FROM PocketGemsSchema.pocketgemstable2
If your Install_date contain datatype date or datetime than your query will work

I think its the data type issue , you can try two approach
convert the field to datatime and your query should work
cast it on the run time like below
Mysql
SELECT Min(Str_to_date(Install_date, '%m/%d/%Y'))
FROM pocketgemsschema.pocketgemstable2;
SQL server
SELECT Min(Cast(Install_date as datetime))
FROM pocketgemsschema.pocketgemstable2;

I would change the column to a date or a datetime type and sort out any bugs that arise.

Related

date time stored as varchar in sql how to filter on varchar

I am working on a project in which dates and times ar stored as a varchar e.g. "30-11-2017,7:30" first date in dd-mm-yyy format and then time separated with a comma. I am trying to filter on it but it is not working correctly kindly guide me how to filter data on date.
select *
from timetrack
where startDateAndTime >= '30-11-2017,7:30'
In attached image records have been shown. When I apply above query it shows no records
You can easily convert your date to SQL datatype datetime uisng parse function, for example select parse('30-11-2017,7:30' as datetime using 'it-IT').
So, in your case, you can apply this function in where clause, so you can easily apply comparison between dates:
select *
from timetrack
where parse(startDateAndTime as datetime using 'it-IT') >= '2017-11-30 07:30:00.000'
Your format is apparently italian :) But you have to specify your own date in the format convertable to datetime, as I have done in above example.
NOTE: parse is available starting with SQL Management Studio 2012.
Unless you are using ISO date format (yyyy-MM-dd HH:mm:ss or close) applying ordering (which inequalities like greater than or equal use) will not work: the date order is disconnected from the string ordering.
You'll need to parse the date and times into a real date time type and then compare to that (details of this depend on which RDBMS you are using).
If, you want to just filter out the date then you could use convert() function for SQL Server
select *
from timetrack
where startDateAndTime >= convert(date, left(#date, 10), 103)
Else convert it to datetime as follow
select *
from timetrack
where startDateAndTime >= convert(datetime, left(#date, 10)+' ' +
reverse(left(reverse(#date), charindex(',', reverse(#date))-1)), 103)
You need the date in a datetime column, Otherwise you can't filter with your current varchar format of your date.
Without changing the existing columns, this can be achieved by making a computed column and making it persisted to optimize performance.
ALTER TABLE test add CstartDateTime
as convert(datetime, substring(startDateAndTime, 7,4)+ substring(startDateAndTime, 4,2)
+ left(startDateAndTime, 2) +' '+ right(startDateAndTime, 5), 112) persisted
Note: this require all rows in the column contains a valid date with the current format
Firstly, you need to check what is the data that is entered in the 'startDateAndTime' column,then you can convert that varchar into date format
If the data in 'startDateAndTime' column has data like '30-11-2017,07:30', you would then have to convert it into date:
SELECT to_date('30-11-2017,07:30','dd-mm-yyyy,hh:mm') from dual; --check this
--Your query:
SELECT to_date(startDateAndTime ,'dd-mm-yyyy,hh:mm') from timetrack;

Convert date to varchar in SQL Server

How do I convert a column which is date type to varchar?
Sample data:
ENDDATE (DATE TYPE)
'1947-12-01 00-00-00'
Requested results:
ENDDATE (VARCHAR)
121947
If I understand the question correctly, you need the ENDDATE of value '1947-12-01 00-00-00' as 121947. You can use the below query
SELECT RIGHT(MONTH(ENDDATE)*1010000+YEAR(ENDDATE),6)
If you are working with 2012 version or higher, you can use format. For earlier versions you can use convert with some string manipulations:
DECLARE #D as date = '1947-12-01'
SELECT REPLACE(RIGHT(CONVERT(char(10), #d, 103), 7), '/', '') As charValue2008,
FORMAT(#d, 'MMyyyy') as charValue2012
Results:
charValue2008 charValue2012
121947 121947
Please note that Format runs relativley slow, so if you have a lot of rows you might want to choose another way to do that.

COALESCE db2 date

I am trying to query on 2 different date fields and one date field (datefield2) has null values. My date field is CCYYDDD and I usually convert this to mm/dd/yyyy by date(digits(datefield)) as NewDate.
This fails
SELECT type, date(digits(datefield1)) AS DateEntered, coalesce(varchar(datefield2),'') as Renewed
FROM MYDATA
WHERE date(digits(datefeld1)) between '06/01/2015' and '6/30/2015' OR date(digits(coalesce(varchar(rendt7),''))) between '06/01/2015' and '06/30/2015'
The following succeeds
SELECT type, date(digits(datefield1)) AS DateEntered, coalesce(varchar(datefield2),'') as Renewed
FROM MYDATA
WHERE date(digits(datefeld1)) between '06/01/2015' and '6/30/2015' OR coalesce(varchar(rendt7),'') between '2015152' and '2015181
How can I query where my date fields contain null values? I plan on passing parameters in for the date range values and would rather just pass mm/dd/yyyy.
I'm a little confused by your question, but I think what you're really looking for is the TIMESTAMP_FORMAT function. I think it would be something like this:
SELECT
type
,DATE(TIMESTAMP_FORMAT(datefield1,'YYYYDDD')) AS DateEntered
,DATE(COALESCE(TIMESTAMP_FORMAT(datefield2,'YYYYDDD'),'0001-01-01')) AS Renewed
FROM MYDATA
WHERE DATE(TIMESTAMP_FORMAT(COALESCE(datefield1, rendt7),'YYYYDDD'))
BETWEEN #date1 AND #date2

finding data lying between a specific date range in sql

I want to find records from my database which lie between any user input date range(say between 10/2/2008 to 26/9/2024). I tried using
SELECT NAME
,TYPE
,COMP_NAME
,BATCH_NO
,SHELF
,MFG_DATE
,EXP_DATE
,QTY
,VAT
,MRP
FROM STOCK_LOCAL
WHERE
convert(VARCHAR(20), EXP_DATE, 103)
BETWEEN convert(VARCHAR(20), #MEDICINEEXP_DATE, 103)
AND convert(VARCHAR(20), #MEDICINEEXPDATE, 103)
but with this query i need to enter perfect date range which is available in my database, it is not giving me data lying in between any date entered.
Thanks in advance
Since it is a poolr designed schema there isnt going to be any decent/Efficient solution for this.
In sql server if you are storing Date or Date & Time data. Use the Data or DATETIME datatypes for your columns.
In your case you are trying to compare a string with passed date. and even when you tried to convert the string (Date) into date datatype you didnt do it correctly.
My suggestion would be Add new columns to your table with Date datatype and update these columns with existing date/string values.
For now you can convert the Date(string) into date datatype using the following code.
DECLARE #MEDICINEEXP_DATE DATE = 'SomeValue1'
DECLARE #MEDICINEEXPDATE DATE = 'SomeValue1'
SELECT query....
FROM TableName
WHERE
CAST(
RIGHT(EXP_DATE, 4)
+SUBSTRING(EXP_DATE,CHARINDEX('/',EXP_DATE)+1,2)
+LEFT(EXP_DATE,2)
AS DATE) >= #MEDICINEEXP_DATE
AND CAST(
RIGHT(EXP_DATE, 4)
+SUBSTRING(EXP_DATE,CHARINDEX('/',EXP_DATE)+1,2)
+LEFT(EXP_DATE,2)
AS DATE) <= #MEDICINEEXPDATE
Note
This solution will get you the expected results but very inefficient method. It will not make use of any indexses on your EXP_DATE Column even if you have a very buffed up index on that column.

Convert String to date in select statement

I have a column which contains data but the problem is that this column has data type of varchar(50) and it has to be this due to some reasons,now what i want to do is while selecting data from table , i want to treat this column as date so that i can use it in where clause. i am using the code below for converting it yo date , but it converts some values and then gives an error
this is my sample data
8/1/2002
6/9/2001
14/9/2001
26/7/2001
14/12/2001
21/1/2002
29/4/2001
7/5/2001
9/11/2001
16/7/2001
select CONVERT(date,sowingDate,103) from tblAgriculture_staging
I have tried which differnt version of date format e.g 103,105 etc
but still it converts some values but error comes on some values and query execution stops
Try this:
SET DATEFORMAT dmy;
select case when isdate(sowingDate) = 1 then CONVERT(date,sowingDate,103) end [date] from tblAgriculture_staging
or (if you are using sql 2012)
SET DATEFORMAT dmy;
select case when TRY_CONVERT(date, sowingDate) IS NOT NULL then CONVERT(date,sowingDate,103) end [date] from tblAgriculture_staging
but this solution hides (convert to NULL) all dates that are wrong. You can reverse the condition first and find/fix all rows with incorrect date (i.e. 31/02/2013) and then use this queries to show only valid dates
SQLFiddle
but it converts some values and then gives an error this is my sample
data
because some data are in invalid format or contains incorrect symbols.
Try this:
select CONVERT(date,ltrim(rtrim(sowingDate)), 103) from tblAgriculture_staging
or examine your values:
select ISDATE(sowingDate) as IsDate, sowingDate, CASE WHEN ISDATE(sowingDate)=1 THEN CONVERT(date,ltrim(rtrim(sowingDate)), 103) ELSE NULL END from tblAgriculture_staging
This is slightly crappy, but so is storing dates as varchar.
this is code that has worked for me in the past where i had some dates with 4 digit years and some with 2 digit years.
where (TRY_CONVERT(Datetime2,LTRIM(RTRIM([INVC DTE])),1)>=#From
AND TRY_CONVERT(Datetime2,LTRIM(RTRIM([INVC DTE])),1)<=#To)
OR (TRY_CONVERT(Datetime2,LTRIM(RTRIM([INVC DTE])),101)>=#From
AND TRY_CONVERT(Datetime2,LTRIM(RTRIM([INVC DTE])),101)<=#To)
SQL Server 2012 + Only
This assumes you have cleaned up anything that actually just isn't a date...
This will return all the dates that are not actually dates.
select sowingDate from tblAgriculture_staging where isdate(sowingDate)=0