Use date in mysql database instead ID - mysql

How is smart to use date as primary value instead ID?
Where I can get better search mysql database performace:
to use timestamp: 1394319600
or to format date and use it as: 09032014
09032014 = 1394319600 = 9.Mart 2014

You likely should not be using a datetime type of data field as a primary key to begin with. I would suggest using autoincrementing integer field to guarantee uniqueness.
Now with regards to the datetime/timestamp field itself it is almost always better to use a native datetime or timestamp data type for these columns rather than string representations such a unix timestamps or other formatted date strings.
Why? Because when people put in timestamp data into their database base, they typically get to the point of wanting to run queries against that data. If you store your data in a non-native datetime format, you will typically need to convert it to such a format before you can use it in typical date/time functions that would be used in this sort of query. This usually means you lose the ability to leverage any index on the field for the query.
For example, say you wanted to run a query to see all records for the current day. With unix timestamp field that query may look like:
SELECT * FROM table
WHERE FROM_UNIX_TIMESTAMP(timestamp_field)
BETWEEN CONCAT(CURRENT_DATE(), ' 00:00:00') AND CONCAT(CURRENT_DATE(), ' 23:59:59')
whereas with a datetime/timestamp filed it would look like:
SELECT * FROM table
WHERE timestamp_field
BETWEEN CONCAT(CURRENT_DATE(), ' 00:00:00') AND CONCAT(CURRENT_DATE(), ' 23:59:59')
Here the simple requirement to use FROM_UNIX_TIMESTAMP() on the left hand side of the WHERE condition in the first query prevents use of an index since FROM_UNIX_TIMESTAMP(timestamp_field) does not exist in memory like timestamp_field would if properly indexed. This means you now need to do a full table scan to execute that query. If you have a large table, this could be very problematic.

Related

How to insert date in a new table in YYYY-MM-DD' format?

CREATE TABLE ORDERS (
ORD_NUM NUMERIC(6,0) NOT NULL PRIMARY KEY,
ORD_AMOUNT NUMERIC(12,2) NOT NULL,
ORD_DATE DATE NOT NULL,
INSERT INTO ORDERS VALUES('200100', '1000.00', '08/01/2008');
INSERT INTO ORDERS VALUES('200110', '3000.00', '04/15/2008');
INSERT INTO ORDERS VALUES('200107', '4500.00', '08/30/2008');
Since I have large number of rows with date in the above format, how can I convert the into yyyy-mm-dd format?
The below solution does not work as the values are not inserted into the ORDERS table.
So, nothing to update.
UPDATE ORDERS
SET ORD_DATE = DATE_FORMAT(ORD_DATE, '%Y-%m-%d');
Executing the code gives error, which I learned to be due to the date format, which MySQL does not allow.
The question misunderstands how dates work in SQL. The Date type does not have ANY human-readable format at all. The values in this column will be stored as binary data, which has significant benefits over string formats for memory/storage use, date math, and indexing.
Now we insert a value like '08/01/2008' into a date column. I will interpret this to mean August 1st based on the other values in the question (this isn't a universal or even majority interpretation!). This value provides the month first, then the day, then the year... but MySQL will not store it that way and does not preserve the original format.
Therefore it makes no sense at all to UPDATE the column to set a specific format. You can't do it, because dates are not stored in a way that preserves any write-able format.
What you can do is format the value at output time, as part of a SELECT query, to use whatever format you need. Additionally, you can use the Str_To_Date() function to control how string values will be interpreted when creating or comparing to native SQL dates.
One thing to keep in mind: thanks to cultural/internationalization issues, converting dates (and numbers!) to and from strings is much slower and more error-prone for a computer than you likely expect. It's something to avoid. Therefore, converting to the native date format early, and leaving it that way as long as possible, is usually the best option.
You just need to convert the string to a date in your insert statements:
INSERT INTO ORDERS VALUES('200100', '1000.00', TO_DATE('08/01/2008', 'mm/dd/yyyy');

How to apply index for datetime field in sql

I am trying to delete the record from the specific date range .
So I have used the below query
delete from `table_name` where `date`<1580947200
I have used datetime as data type for the date column
It takes long time to execute and sometimes it gets stuck while executing this query.
Can anyone say how to apply index for this query
Your issue is not indexing. Your issue is that your telling MySQL to numerically compare a non-numeric (DATETIME) column against a numeric value (Unix timestamp).
i have used datetime as datatype for date column
This means the column is a DATETIME column. But;
1580947200
looks to me like a Unix Timestamp value.
Unix Timestamp is not the same as a MySQL DateTime entity.
Therefore; you need to CAST these two types to the same for the comparison; To do this you can use the UNIX_TIMESTAMP() MySQL Function.
DELETE FROM `table_name` WHERE UNIX_TIMESTAMP(`date`) < 1580947200
If you do wish to add an index to the date column you can read this Q&A.

Best practice index for date and time?

For date and time indexing purposes, of the following, which is the best/best practice/fastest?
keep a type date and another for time and have index on type date column
keep a single datetime column and simply put an index on type datetime column
have two, a datetime column and a date column, but put a single index on date
keep a type date and another for time and have index on both , first date and then time
any other approach?
I want to query a table for detecting changes, so I need both date and time.
UPDATE : I thought datetime indexing would take much more space than a date, so it would effect systems performance, is it true?
Assuming you are trying to save the date and the time that is on the same day as the date:
A datetime column can be used by date queries as well as time based queries. I can't see a reason why you would want another field.
I'd suggest using a unix timestamp in a int field, easiest to add, subtract and compare. You can convert to different formats for display.

Selecting all records entered in a particular day - MySQL

I am currently working on a Mailbox for a website, holding a large number of messages within a database, where there is an option to filter the mails according to the date. I am in a confusion as of which method to use and how to.
Method 1:
To use a TIMESTAMP column and select the records based on the DATE part only. This seems to be better considering that the TIMESTAMP is the datatype meant to do this. But when filtering, wouldn't the splitting (to date and time) and comparisons be more expensive. If better, how to perform the comparison? (Input : yyyy-mm-dd)
Method 2:
To use a column each for TIME and DATE. Then compare the date field value to the filter param (of the format : yyyy-mm-dd). This seems expensive at inserting a new record (mail), which happens only one at a time. But the filtering requires comparison of a large number of records. So, seems to be more straight forward.
Also in method two, I am having a problem setting the default value as the CURRENT_DATE and CURRENT_TIME!
This is the Table creation code:
CREATE TABLE mailbox (
Mid INT NOT NULL AUTO_INCREMENT,
FromId INT NOT NULL,
ToId INT NOT NULL,
Subject VARCHAR(256) DEFAULT 'No Subject',
Message VARCHAR(2048) DEFAULT 'Empty Mail',
SDate DATE DEFAULT CURRENT_DATE,
STime TIME DEFAULT CURRENT_TIME,
PRIMARY KEY (Mid),
);
Please help...
I would use method 1 and do the filtering with
WHERE
your_timestamp >= search_date
AND
your_timestamp < search_date + INTERVAL 1 DAY
assuming your search_date is of type DATE.
MySQL can use an index in this case.
See this fiddle.
Have a look at the execution plan to verify the use of the index.
I suggest first that you maintain the records in the table sorted by date. Doing so, allows you to not need to compare every value, but you can use binary search to find the two boundaries (begin and end) of records with the desired date.
I would also use the time stamp. If you store is as timesstamp and not as text, it will be number, and its very fast at doing the comparison.

Select Date(String Date)<DATE(Text Column with Date)

I have a table with a column of the type text where I store various settings, including dates, using NOW() in the insert query.
Now I want to get all rows from this table where this column is before a specific date (e.g. 2012-09-19).
Comparing via DATE(date_column)<DATE(NOW()) is easy, but I don't know how to pass a specific date instead of NOW(), because date formats of the input string may differ.
Here's a sample code:
INSERT INTO table (date_column) VALUES (NOW())
And when selecting:
SELECT * FROM table WHERE DATE(date_column)<DATE('2012-09-19');
EDIT: The above code actually works. I was missing the quotes around the date initially.
Avoid placing functions around your column types (WHERE FUNCTION(col) ...). This decreases performance. You want to have a table that has domain integrity, meaning if you are storing a date, it is a date type.
To select records that match your date, simply encase your YYYY-MM-DD date in quotes:
SELECT * FROM table WHERE date_column < '2012-09-19'
If date_column truly is of type DATE, you don't need to run DATE() on it.
Also note that running DATE() on date_column will prevent MySQL from using any indexes, so you'll be doing a table scan.
Try:
WHERE date_column < '2012-09-19'