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

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');

Related

Convert 2021-1-01 to 2021-01-01 in SQL (YYYY-M-DD TO YYYY-MM-DD)

As title.
There is a way to convert a date from YYYY-M-DD to YYYY-MM-DD?
In db I have 2021-1-01 but I need to get 2021-01-01.
TY
EDIT
I have a value 2021-1-01 and i need to insert it in a db like date 2021-01-01, maybe before I not was clear.
If you have '2021-1-01', then you do not have a date. You have a string. That is a problem with your data model. You should fix the data to store dates using appropriate types -- which are not strings.
MySQL is pretty smart about converting dates, so you can just use:
select date(string_as_date_col)
You can change the type of the column in the table using:
alter table t modify column string_as_date_column date
Here is a db<>fiddle.

Changing Date Format in SQL Table

I currently have a Release_Date(Date) in my Songs table. I been trying to change the date format. The current format is yyyy-mm-dd. I want mm/dd/yyyy.
Error: Invalid Date value.
Release_Date is stored in the database as a Date, not as a string, so you don't need to call the str_to_date function. You are getting an error because you are calling the str_to_date function on something that is already a date, not a string.
Furthermore, as it is a date, you can't update that field to a string value. You would have to create a new column defined as a string and store the date there.
However, it is highly advantageous to keep the dates stored as Date fields, because comparisons, sorting, and the various date functions will all work as they should.
So if you want to use the date in a different format, you would just use DATE_FORMAT(Release_Date,'%m/%d/%Y') whenever you access it, and leave the field as a native date, as in
SELECT DATE_FORMAT(Release_Date,'%m/%d/%Y') FROM Songs WHERE Release_DATE IS NOT NULL;
It is not possible to "update" the internal format of a MySQL date. If you want to display your text as mm/dd/yyyy, then you should only need a single call to DATE_FORMAT, e.g.
SELECT DATE_FORMAT('2019-07-29', '%m/%d/%y')
which prints:
07/29/19
As Tim suggests, you don't need to change the existing date format & value but if you insists, you could add another column - datatype VARCHAR - in the table and then update the column according to your desired date format. Steps are below:
create new column
ALTER TABLE songs
ADD COLUMN `rls_date` VARCHAR(50) AFTER `release_date`;
Update new column with desired date format
UPDATE songs SET `rls_date`=DATE_FORMAT(`Release_Date`,'%m/%d/%Y');
Just remember, by doing this, you can't expect the column to identify any date format related function outright. Lets say you run a query like this SELECT * FROM songs WHERE rls_date=CURDATE(); won't work.

Use date in mysql database instead ID

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.

What datatype to use for ISO 8601 dates?

I am redesigning a database that currently imports ISO 8601 dates in the format of 2012-10-27T07:30:38+00:00 into a varchar field. The current database is hosted on a MySQL 5.5 server.
In searching through documentation and various SO posts, I have not found a definitive answer on what datatype I should use in MySQL for this purpose. The closest post is: MySQL insert to DATETIME: is it safe to use ISO::8601 format? where it provides a work around of sorts, however this is not a desirable option.
The MySQL documentation (http://dev.mysql.com/doc/refman/5.5/en/date-and-time-types.html) does not say, and the only reference I can find on official documentation is located on page: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
which states "The possible values for the first and second arguments result in several possible format strings (for the specifiers used, see the table in the DATE_FORMAT() function description). ISO format refers to ISO 9075, not ISO 8601."
Now the PostgreSQL documentation specifically mentions ISO8601 ( http://www.postgresql.org/docs/9.2/static/datetime-keywords.html and http://www.postgresql.org/docs/9.2/static/datatype-datetime.html ) which leads me to my question:
Does MySQL correctly support ISO 8601, or should I consider a database with native support?
--Edit--
Attempting to insert the example time stamp above into a datetime column gives the following error:
10:55:55 insert into test(date1) values('2012-10-27T07:30:38+00:00') Error Code: 1292. Incorrect datetime value: '2012-10-27T07:30:38+00:00' for column 'date1' at row 1 0.047 sec
Do not store date or timestamp values in a varchar column. You have no way of ensuring that a correct value is stored (no one prevents you from storing 2012-02-31 28:99:70 in there.
If you don't need the time part, use a date datatype (available in MySQL and PostgreSQL) if you do need the time use a timestamp (or datetime in MySQL) data type.
The formatting of the values should be done in your frontend or if you absolutely have to do it in SQL using e.g. to_char() (or the equivalent in MySQL) when retrieving the values.
Again: never store dates or timestamps in a varchar (just as you should never stored real numbers in a varchar column).
Here is the MySQL overview for date/time datatypes: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-types.html
Here is the PostgreSQL overview for date7time datatypes: http://www.postgresql.org/docs/current/static/datatype-datetime.html
Edit
If you are concerned about the literal format. Both DBMS support the standard ANSI Date and Timestamp literals:
insert into some_table
(ts_column, date_column)
values
(timestamp '2012-10-27T07:30:38+00:00', DATE '2012-12-30');
SQLFiddle for PostgreSQL: http://sqlfiddle.com/#!12/cdd39/1
Note the keywords timestamp and date in front of the character literal.
Edit 2
It seems MySQL cannot insert such a value, although it can use that literal in a SELECT statement:
Postgresql can handle that format:
without
select timestamp '2012-10-27T07:30:38+00:00';
timestamp
---------------------
2012-10-27 07:30:38
or with time zone:
select timestamptz '2012-10-27T07:30:38+00:00';
timestamptz
------------------------
2012-10-27 05:30:38-02
Whereas MySQL seems to not care much about the time zone part:
create table t (ts timestamp);
insert into t (ts) values
('2012-10-27T07:30:38+03:00'),
('2012-10-27T07:30:38-02:00');
select * from t;
+---------------------+
| ts |
+---------------------+
| 2012-10-27 07:30:38 |
| 2012-10-27 07:30:38 |
+---------------------+
The ISO 8601 date format, "YYYY-MM-DD", is what MySQL emits internally when displaying date values and it can import them just the same.
These are preferable to "American style" dates like "MM/DD/YY" where there's too much ambiguity to be automatically resolved.
ISO 9075 appears to refer to the entirety of the SQL standard, not a specific date format, though the standard itself does have standard formatting for dates and times.
Just another advantage of using datetime or timestamp for storing.
In phpMyAdmin or phpPgAdmin the value is displayed as a string e.g. 2015-01-22 11:13:42. So it's much easier to find a date as if it's stored as a varchar or int.
And I think it's important what timezone the server has.
I've see that a timestamp in MySql doesn't display microseconds.
I know MySQL use UTC-Time for timestamp and datetime-fields.
So provide the values as a UTC-timestamp.

Get NULL value in MYSQL for TIMEDATE

When I insert the codes as is I get NULL
INSERT INTO dates VALUES (date='12-11-20 11:30:11');
When I fire query
SELECT * FROM dates;
I get
|dates |
| NULL |
INSERT INTO dates (date) VALUES('12-11-20 11:30:11')
Your syntax is wrong.
Correct syntax is as shown below.
INSERT INTO dates (dates) VALUES ('12-11-20 11:30:11');
Your INSERT query is wrong. Use one of the following syntaxes:
INSERT INTO dates (date) VALUES ('12-11-20 11:30:11')
INSERT INTO dates SET date = '12-11-20 11:30:11'
The first one is preferred since that works in all databases while the latter is most likely not standard SQL.
You should also consider to use 2012-11-20 instead of 12-11-20. We all know what happened 12 years ago due to people not using 4-digit years.
Well, there are several interesting issues to note here.
First, it's safer in my opinion to explicitly state the fields which will be updated: otherwise the query becomes unusable after the table's structure changes. And it's not recommended to give the same name to the table's field and the table itself: it may confuse you later.
Second, your DATETIME literal is actually ok for MySQL - it accepts two numbers for a year, parsing it by a specific rule:
Year values in the range 70-99 are converted to 1970-1999.
Year values in the range 00-69 are converted to 2000-2069.
So you may still use '12-11-20' syntax... if, again, it won't become confusing to whoever will maintain your script later (even you, perhaps.. )).
Finally, INSERT expression can take any valid expression within the VALUES clause. In your case it's date = '...' expression, which is evaluated to NULL; that's why NULL gets inserted in your table. If you, however, want to insert only the DATETIME literal (and you probably do), drop the assignment sign (which is actually taken as 'equality operator') and use simply...
INSERT INTO dates (datetime_field) VALUES ('2012-11-20 12:12:12');
... or this, if you want to insert several rows with a single query:
INSERT INTO dates (datetime_field) VALUES ('2012-11-20 12:12:12'), ('2012-11-20 13:13:13');
Hope this helps. ) But even if you don't have any questions, I'd still recommend studying Insert syntax and Date and time literals topics anyway - it WILL be helpful.