Search code examples
mysqlunix-timestamp

select data by unix timestamp


Below are the table I've created and its records:

CREATE TABLE students (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  gender TEXT NOT NULL,
  created_at datetime
);

INSERT INTO students VALUES (1, 'Ryan', 'M', '2012-11-03 00:00:00');
INSERT INTO students VALUES (2, 'Joanna', 'F', '2013-11-03 00:00:00');

To fetch the records by time, I use the following SQL statement:

SELECT * FROM students WHERE created_at > 1620489600000;

and both records can be returned, which confuses me because 1620489600000 (Sat May 08 2021 16:00:00 GMT+0000) should be a timestamp way later than the create_at fields of both records.

Indeed I know this can also be achieved by specifying a time formatted as 2012-11-03 00:00:00, but I just wonder:

  • whether we can effectively query a datetime column in where clause with unix timestamp?
  • if not, why does the above select statement return both records?

Solution

  • To compare two different data types MySQL automatically converts one of them to the other. In this case it tries to make numbers of the dates. What is the result? See here

    The date gets converted to

    20121103000000
    

    which is bigger than

    1620489600000
    

    So the result in your WHERE clause is true and returns all records.

    If you need to go from a Unix Timestamp you could use this:

    WHERE created_at > FROM_UNIXTIME(1620489600000 / 1000)
    

    Notice that I divided by 1000 because Unix time has to be in seconds and not milli seconds.