exercise question
I got '61678125784' using 1997-01-01 without the quotation mark whereas the answer shows 31909143195 from '1997-01-01'. Why is it so? Please help. Thanks.
Hi Angela!
Thanks for reaching out.
You can use quotes for both numbers and strings. But usually quotes are for strings. The numbers can be without quotes and in this way there is a better readability.
On the other side, dates should be with quotes! If you skip the quotes, the result set will be different and incorrect. Let me show you an example:
If you skip the quotes from your query and you have:
...BETWEEN 2000-01-01 AND 1995-05-04...
it will be the same as:
...BETWEEN 1986 AND 1998...
(1995-05-04=1995-5-4=1986 and 2000-01-01=2000-1-1=1998)
which is very different from:
...BETWEEN '2000-01-01' AND '1995-05-04'...
The first example has a period of 17 years and the second one with only 6 years. Thus, the result set will be different.
So, you should use quotes for dates.
Hope this helps.
Best,
Tsvetelin
I am interested to know where the answers came from for this statement:
(1995-05-04=1995-5-4=1986 and 2000-01-01=2000-1-1=1998)
Hi Ahmed!
Thanks for reaching out and please excuse us for the belated answer.
The obtained values come after using the code Angela shared with us:
1) First query:
SELECT
SUM(salary)
FROM
salaries
WHERE
from_date > '1997-01-01';
meaning
SELECT
SUM(salary)
FROM
salaries
WHERE
from_date > 1995;
Please note that the latter relates to the conversion in MySQL of date values into UNIX timestamps. It doesn't refer to the 1st of January 1995 (which would be '1995-01-01'), but to a different date; more precisely - the 1st of January 1970. In that case, since in our database we have data from 19856 to 2002, which means a time span of 17 years.
2) Second query:
SELECT
SUM(salary)
FROM
salaries
WHERE
from_date > '1997-01-01';
As Tsvetelin suggests, the two queries refer to records from a different amount of years. The first query refers to a period of 17 years (*corrected in the previous answer), while the second - for a period of 6 years. Hence the difference in the values obtained.
Hope this helps.
Kind regards,
Martin
P.S. If you are interested in the conversion of date values into integers and vice-versa in MySQL, please consider using the UNIX_TIMESTAMP()
and FROM_UNIXTIME()
functions. Execute the following two queries as an example:
SELECT UNIX_TIMESTAMP('1995-01-01');
SELECT FROM_UNIXTIME(788914800);