TRIM function on Datefield in SQL Server - sql

I have written the following query:
select *
from employees
order by (CAST(LTRIM(RTRIM(JoingDate)) AS SMALLDATETIME)) desc
The query affects performance. Do we require to use TRIM on a DateTime column? How can we rewrite the above query to increase performance and to minimize execution time? Would we use CONVERT function instead of CAST?

Unless I am missing something, you should just do this:
select *
from employees
order by JoingDate desc
Not sure why you are converting your date to a string and then back to a date. If you want smalldatetime over datetime, you could just cast/convert it but why?
select *
from employees
order by CAST(JoingDate AS SMALLDATETIME) desc

Related

Error Conversion failed when converting date and/or time from character string: varchar(8000)

I have a column of type varchar(8000). We save all kinds of data in it like number, text, date etc.
I wrote a simple select query to get all "Date" values from the table all works, I can also use CAST or Convert to get my value in this format 2014-12-16 00:00:00.000.
Now I'm trying to add a where clause to filter this year's info, but I get an error:
Conversion failed when converting date and/or time from character string.
When I use TOP 10000 in my select query the error goes away. This is really strange
; WITH TempTable AS
(
SELECT
ID, CAST(Value AS DateTime) [SomeDate]
FROM
SampleTable
WHERE
ColType = 'Date'
)
SELECT *
FROM FROM TempTable
WHERE [SomeDate] BETWEEN '1/1/2017' AND '12/30/2017'
This throws
Conversion failed when converting date and/or time from character string.
; WITH TempTable AS
(
SELECT TOP 100000
ID, CAST(Value AS DateTime) [SomeDate]
FROM
SampleTable
WHERE
ColType = 'Date'
)
SELECT *
FROM FROM TempTable
WHERE [SomeDate] BETWEEN '1/1/2017' AND '12/30/2017'
This works fine. Please note I have only 25 some rows in my result. Top 100000 is just a big number I used. This is very strange how my TOP keyword is making my query good.
Update:
Here is how I ended up resolving without using TOP keyword. I have split my query little bit as seen below. Thank you all for your time and comments.
;WITH GetAllIDs
AS (
SELECT ID
FROM SampleTable
WHERE ColType = 'Date'
)
,FinalTable
AS (
SELECT ID
,(
SELECT Cast([Value] AS DATETIME)
FROM SampleTable dt
WHERE dt.ID = tt.ID
AND dd.ColType = 'Date'
) [SomeDate]
FROM GetAllIDs tt
)
SELECT *FROM FinalTable
WHERE [SomeDate] BETWEEN '1/1/2017' AND '12/30/2017'
There is no order of execution in a SQL statement. So, the where clause does (necessarily) filter the rows before the values are converted. Hence, your problem.
In SQL Server 2012+, there is a simple solution using try_convert():
With TempTable AS (
select ID, try_convert(datetime, Value) as SomeDate
from SampleTable
where ColType = 'Date'
)
Select *
from TempTable
Where SomeDate between '2017-01-01' and '2017-12-30';
Microsoft considers this behavior a feature of the optimizer, not a bug (I disagree). It provides more opportunities for optimizing the query. In this case, simple conversions are done when the data is being read, rather than further down the processing pipeline.
Notice that I also changed the date constants to YYYY-MM-DD format. You should always use YYYY-MM-DD or YYYYMMDD for the format.
The fact that this goes away when TOP is added is some strange artifact of the execution plan. For some reason, that would do the filtering before evaluating the expression. I know that TOP can have sometimes have this effect. I'm surprised in this case because the query is simple.
EDIT:
In SQL Server 2008, you can use case. Something like this:
With TempTable AS (
select ID, (case when isdate(value) = 1 then convert(datetime, Value) end) as SomeDate
from SampleTable
where ColType = 'Date'
)
Select *
from TempTable
Where SomeDate between '2017-01-01' and '2017-12-30';
The case expression guarantees the order of evaluation of the arguments. The when is evaluated only after the then.
Based on SQL 2008, you would have to change your pattern.
First, why it works with the TOP command. TOP selects all records matching the WHERE clause in the query up to the limit of the TOP. Since you have a WHERE clause, the version with the TOP only passes records with the Coltype of 'Date' on to the date check. Without the top, the optimizer thinks that checking the value of the Value column against the date range will be faster than filtering the column type, since only one data element retrieval is required to check that, "speeding up" (in this case, blowing up) the query.
One option that should work would be to change the TempTable definition code to this:
; WITH TempTable AS
(
SELECT TOP 100 PERCENT
ID, CAST(Value AS DateTime) [SomeDate]
FROM
SampleTable
WHERE
ColType = 'Date'
)
Your other obvious option would be to extract all of the values to an actual temp table, rather than using a CTE directly, then query that table.
Please see my update: This is how I ended up fixing my problem. Thank You Gordon, Laughing Vergil for your comments.

get date order by day and month in sql

I am storing the date as "14-02-2013" in date column of my table. Now when I get the date using "ORDER BY" then it should display the output as
14-02-2013
15-03-2013
24-05-2013
How to write the query for this. i.e getting order by day and month.
Any suggestion will be helpful.
Use DATE (or DATETIME) type in your column. Otherwise you will have to perform operations on string representation of date, which is not cool and will cost some extra time to perform
Try one of following:
Select * from Table1 order by date(dtcolumn) Asc
Select * from Table1 order by strftime('%d-%m-%Y', dtcolumn)
Try this query
Select * from Table1 Order By mydatecol Asc
Given you store your date as a temporal data type you can use
select * from your_date_table order by date(your_date_column) ASC
If you store it as a string(which you should not do), you can try
select * from your_date_table order by your_date_column ASC
Here is the doc for the sqlite date and time functions

Order by SQL timestamp

I have a timestamp field added to every of my records with an SQL timestamp, (yes, the format is actually TIMESTAMP). I want to display my records by date and time; can I just ORDER BY in an SQL statement?
SELECT * FROM table ORDER BY timestamp DESC
Assuming its MySQL,
SELECT *
FROM randomTable
ORDER BY timestampfield DESC;
is just perfect.
Yes, I tried it and it is working for me on Oracl SQL Developer

Sql Server 2005: Today's random records

I can easily get a random record with this:
SELECT * FROM MyTable ORDER BY NewId()
I can easily get a record with "today's date" with this:
SELECT * FROM MyTable WHERE MyDate = "2010-24-08" -- db doesn't store times
But how would I combind the two?
Get 1 random record... anything with today's date.
If none are found... get 1 random record from yesterday (today-1).
If none are found... get 1 random record from etc, etc, today-2
... until 1 record is found.
Just make the day date the primary order by condition:
select top(1) *
from Table
order by Date desc, newid();
If you store the dates as full day and time, you need to round them out to the day part only: cast (Date as DATE) in SQL 2008 or cast(floor(cast(Date as FLOAT)) as DATETIME) in pre-2008.
Use the TOP operator:
SELECT TOP 1 *
FROM MyTable
WHERE MyDate = "2010-24-08"
ORDER BY NEWID()
...combined with the ORDER BY NEWID(). Without the ORDER BY, you'd get the first inserted row/record of the records returned by the filteration in most cases typically, but the only way to ensure order is with an ORDER BY clause.
SQL Server 2005+ supports brackets on the TOP value, so you can use a variable in the brackets without needing to use dynamic SQL.
Does this give you what you want?
SELECT TOP 1 *
FROM MyTable
ORDER BY MyDate desc, NewId()
This assumes there are no dates later than today.

I want to show records from a table having a date column from sqldatabase in dates order. How should I?

I want to show records from a table having a date column from sqldatabase in dates order. How should I?
SELECT
*
FROM yourTable
ORDER BY yourDateColumn
you can use order by
select * from my_table t order by t.date_column
where date_column is a column name in your table.
SELECT * FROM `table_name` ORDER BY `dates_column`
optionally you can add DESC to reverse the order (newest to oldest):
SELECT * FROM `table_name` ORDER BY `dates_column` DESC
If I understand your question correctly, you want to use an ORDER BY clause on the column containing the dates.
The database engine should handle the proper sorting for a date or timestamp column using an ORDER BY clause. The only exception might be if your column is of type VARCHAR and holds a date of the form "mm/dd/yyyy". Then you've got a bit more work to do.