Is it possible to get the timestamp of a SQL datetime column? - sql

I am using Microsoft SQL Server and I have a table with a datetime column.
When I run a query SELECT END_DATE FROM CUSTOMER I get 2007-12-03 10:15:30.000
I would like to run a query that returns a unix timestamp like 1543357818 representing the date and time. Is this possible through SQL?

Just use datediff():
SELECT DATEDIFF(second, '1970-01-01', END_DATE)
FROM CUSTOMER

As an alternative, convert to float and do a subtract, then convert to seconds. Obviously you can change some of this to constants, but this illustrates what I'm doing:
select floor((convert(float,getdate())-convert(float,convert(datetime,'1970-01-01')))*24*60*60)

Related

Getting not valid month in Oracle sql

I have a table called Transactions that has a column called trans_date. I am just trying to do a simple query in the SQL*Plus command window
The query is
SELECT * FROM transactions WHERE
trans_date BETWEEN to_date('09/11/2021','mm/dd/yyyy') AND to_date('09/12/2021','mm/dd/yyyy');
When I run this query I get not valid month and there is a little * under trans_date. Most of what I have read suggests the query is right but I am not sure what the problem is. The data type is varchar2(20).
Since trans_date is a varchar and you're trying to query whether it's between two dates, you need to convert it to a date too. Assuming it has the same format as the literals in your query:
SELECT *
FROM transactions
WHERE to_date(trans_date, 'mm/dd/yyy') BETWEEN
to_date('09/11/2021','mm/dd/yyyy') AND to_date('09/12/2021','mm/dd/yyyy');
Seems like problem is columns data type, Try convert it to date,
SELECT * FROM transactions
WHERE to_date(trans_date,'mm/dd/yyyy') BETWEEN to_date('09/11/2021','mm/dd/yyyy') AND to_date('09/12/2021','mm/dd/yyyy');
You need to convert trans_date to a date. However, you can use date constants for the comparisons:
SELECT *
FROM transactions
WHERE to_date(trans_date, 'mm/dd/yyyy') BETWEEN DATE '2021-09-11' AND DATE '2021-09-12';
You should fix your data model so the dates are stored correctly, using Oracle's built-in data type.

How can I return data in a SQLite result set based on date range? [duplicate]

I can't seem to get reliable results from the query against a sqlite database using a datetime string as a comparison as so:
select *
from table_1
where mydate >= '1/1/2009' and mydate <= '5/5/2009'
how should I handle datetime comparisons to sqlite?
update:
field mydate is a DateTime datatype
To solve this problem, I store dates as YYYYMMDD. Thus,
where mydate >= '20090101' and mydate <= '20050505'
It just plain WORKS all the time. You may only need to write a parser to handle how users might enter their dates so you can convert them to YYYYMMDD.
SQLite doesn't have dedicated datetime types, but does have a few datetime functions. Follow the string representation formats (actually only formats 1-10) understood by those functions (storing the value as a string) and then you can use them, plus lexicographical comparison on the strings will match datetime comparison (as long as you don't try to compare dates to times or datetimes to times, which doesn't make a whole lot of sense anyway).
Depending on which language you use, you can even get automatic conversion. (Which doesn't apply to comparisons in SQL statements like the example, but will make your life easier.)
I had the same issue recently, and I solved it like this:
SELECT * FROM table WHERE
strftime('%s', date) BETWEEN strftime('%s', start_date) AND strftime('%s', end_date)
The following is working fine for me using SQLite:
SELECT *
FROM ingresosgastos
WHERE fecharegistro BETWEEN "2010-01-01" AND "2013-01-01"
Following worked for me.
SELECT *
FROM table_log
WHERE DATE(start_time) <= '2017-01-09' AND DATE(start_time) >= '2016-12-21'
Sqlite can not compare on dates. we need to convert into seconds and cast it as integer.
Example
SELECT * FROM Table
WHERE
CAST(strftime('%s', date_field) AS integer) <=CAST(strftime('%s', '2015-01-01') AS integer) ;
I have a situation where I want data from up to two days ago and up until the end of today.
I arrived at the following.
WHERE dateTimeRecorded between date('now', 'start of day','-2 days')
and date('now', 'start of day', '+1 day')
Ok, technically I also pull in midnight on tomorrow like the original poster, if there was any data, but my data is all historical.
The key thing to remember, the initial poster excluded all data after 2009-11-15 00:00:00. So, any data that was recorded at midnight on the 15th was included but any data after midnight on the 15th was not.
If their query was,
select *
from table_1
where mydate between Datetime('2009-11-13 00:00:00')
and Datetime('2009-11-15 23:59:59')
Use of the between clause for clarity.
It would have been slightly better. It still does not take into account leap seconds in which an hour can actually have more than 60 seconds, but good enough for discussions here :)
I had to store the time with the time-zone information in it, and was able to get queries working with the following format:
"SELECT * FROM events WHERE datetime(date_added) BETWEEN
datetime('2015-03-06 20:11:00 -04:00') AND datetime('2015-03-06 20:13:00 -04:00')"
The time is stored in the database as regular TEXT in the following format:
2015-03-06 20:12:15 -04:00
Right now i am developing using System.Data.SQlite NuGet package (version 1.0.109.2). Which using SQLite version 3.24.0.
And this works for me.
SELECT * FROM tables WHERE datetime
BETWEEN '2018-10-01 00:00:00' AND '2018-10-10 23:59:59';
I don't need to use the datetime() function. Perhaps they already updated the SQL query on that SQLite version.
Below are the methods to compare the dates but before that we need to identify the format of date stored in DB
I have dates stored in MM/DD/YYYY HH:MM format so it has to be compared in that format
Below query compares the convert the date into MM/DD/YYY format and get data from last five days till today. BETWEEN operator will help and you can simply specify start date AND end date.
select * from myTable where myColumn BETWEEN strftime('%m/%d/%Y %H:%M', datetime('now','localtime'), '-5 day') AND strftime('%m/%d/%Y %H:%M',datetime('now','localtime'));
Below query will use greater than operator (>).
select * from myTable where myColumn > strftime('%m/%d/%Y %H:%M', datetime('now','localtime'), '-5 day');
All the computation I have done is using current time, you can change the format and date as per your need.
Hope this will help you
Summved
You could also write up your own user functions to handle dates in the format you choose. SQLite has a fairly simple method for writing your own user functions. For example, I wrote a few to add time durations together.
My query I did as follows:
SELECT COUNT(carSold)
FROM cars_sales_tbl
WHERE date
BETWEEN '2015-04-01' AND '2015-04-30'
AND carType = "Hybrid"
I got the hint by #ifredy's answer. The all I did is, I wanted this query to be run in iOS, using Objective-C. And it works!
Hope someone who does iOS Development, will get use out of this answer too!
Here is a working example in C# in three ways:
string tableName = "TestTable";
var startDate = DateTime.Today.ToString("yyyy-MM-dd 00:00:00"); \\From today midnight
var endDate = date.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss"); \\ Whole day
string way1 /*long way*/ = $"SELECT * FROM {tableName} WHERE strftime(\'%s\', DateTime)
BETWEEN strftime('%s', \'{startDate}\') AND strftime('%s', \'{endDate}\')";
string way2= $"SELECT * FROM {tableName} WHERE DateTime BETWEEN \'{startDate}\' AND \'{endDate}\'";
string way3= $"SELECT * FROM {tableName} WHERE DateTime >= \'{startDate}\' AND DateTime <=\'{endDate}\'";
select *
from table_1
where date(mydate) >= '1/1/2009' and date(mydate) <= '5/5/2009'
This work for me

SQL datetime LIKE select - why do I need an extra %?

Can someone explain to me why when I perform a LIKE select in SQL (T-SQL) on a varchar column I can do the following:
SELECT *
FROM Table
WHERE Name LIKE 'Th%'
to get names beginning with Th, but when I do the same on a datetime column I need a % before the year, like:
SELECT *
FROM Table
WHERE Date LIKE '%2013%'
to get dates in 2013. The datetimes are stored in yyyy-MM-dd hh:mm:ss format. I know I could use a DATEPART style query but I was just interested in why I need the extra % here.
The DATETIME is converted to a VARCHAR before the comparison, and there definitely is no guarantee that the conversion will be in the pattern you mention. DATETIME is not stored internally as a VARCHAR but as a FLOAT.
You should stop wondering because the syntax is not useful.
SELECT *
FROM Table
WHERE Date LIKE '%2013%'
Will give you a full table scan because the date will be converted to a varchar when comparing. In other words, don't do it !
Use this syntax instead:
SELECT *
FROM Table
WHERE Date >= '2013-01-01T00:00:00'
and Date < '2014-01-01T00:00:00'
If the Date field is in timestamp:-
SELECT *
FROM Table
WHERE year(Date) = '2013'
The sql server converts datetime to this format (Jan 1, 1900 9:20AM.)Because of that reason We need to use an extra %.
If you want to search the records start with month Jan
you can use following query for date time
SELECT *
FROM Table
WHERE Date LIKE 'Jan%'.
No need of extra '%'.

Select where date without time

I am using SQLite, now how can I Select a query if I have a timestamp column that has this value for example 07:00 06/03/13 but I want only to select where timestamp 06/03/13.
This is my example of my query..
select
timestamp, pname
from
attendance
where
timestamp between `06/01/13` and `06/10/13`
Use date
select timestamp, pname
from attendance
where date(timestamp) = '2013-03-06'
When filtering on a timestamp column, you want this logic.
where YourField >= TheStartOfYourRange
and YourField < TheDayAfterTheEndOfYourRange
This is equivalent to the two answers that use the date() function, but will generally perform faster. Using functions in the where clause usually slows down production, especially on indexed fields.
SQLite support function date, which can be used to get the date part of a timestamp. For example:
SELECT * FROM mytable WHERE date(timestamp_col) = '2013-05-20'
See SQLite date and time functions documentation for more info.

how to skip sql timestamp to get records for specific date

I want to compare the date in my sql query and get the records for a specific date, but it is stored in timestamp format in postgres.
What kind of query could compare only date parts, since I want and skip the time part.
This Query will give you date like '2012/11/22' which you can use for date comparison.
SELECT CONVERT(VARCHAR(10),GETDATE(),111)
//OR simply
select CAST(GETDATE() as DATE)
You can see more formats here :- CAST and CONVERT (Transact-SQL)
Try this:
SELECT *
FROM tab
where date_col::DATE BETWEEN '2012-01-01'::DATE AND '2012-01-05'::DATE
SQL Fiddle DEMO