Get NULL value in MYSQL for TIMEDATE - mysql

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.

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

MySQL. Start new row in case of end of month

I was wondering if there is any way to solve this.
So my row has an column of type date which increments with 1 day daily ( untill the end of the respective month ). At the beggining of a new month a new row has to be generated and the update will start again untill the and of that month, and so on..
Here's a way to think about the problem in MySQL's dialect of SQL.
First, you need a function that changes a datestamp into a value that's unique for each month. That is LAST_DAY(datestamp). It generates DATETIME values like 2017-09-30 00:00:00 from arbitrary inputs.
Next, you can exploit MySQL's INSERT ... ON DUPLICATE KEY UPDATE capability. You will create a table months with, say, these columns
month_ending DATETIME
category VARCHAR(20)
sum_of_input INT
Then you make month_ending, category into a unique compound index.
Then you do something like this
INSERT INTO months /* warning! not debugged! */
(month_ending, category, sum_of_input)
VALUES (LAST_DAY(?date), ?category, ?value)
ON DUPLICATE KEY
UPDATE months
SET sum_of_input = sum_of_input + ?value
WHERE month_ending=LAST_DAY(?date)
AND category=?category
However, this has the hallmarks of a big, hard to debug, pain in the neck. It make make more sense to use features inside your ETL system to do this summarizing work.

MySQL Function SEC_TO_TIME not working in UPDATE clause

Some of my columns have duration values for company phone calls, in which the duration is stored in seconds. I wanted to convert these values to a DD:HH:MM:SS format, and I intended to use MySQL's Sec_to_Time function, which worked well when used in a SELECT statement, in an UPDATE statement in order to convert the seconds values to DD:HH:MM:SS values permanently.
However, I tried it on a couple tables with an UPDATE command, but the update either multiplied the value in the column (ex.: 19212 changed to ~32000) or truncated the column.
So I tried the following code, just to see what was happening.
CREATE TEMPORARY TABLE QueueTime_Snapshot (QueueTime int);
INSERT INTO QueueTime_Snapshot (Queuetime)
SELECT QueueTime FROM CDB_Call_and_Agent_Data;
UPDATE QueueTime_Snapshot
SET QueueTime = SEC_TO_TIME(QueueTime);
SELECT QueueTime FROM QueueTime_Snapshot;
The SELECT statement returned the exact values that I had inserted into the temp table; nothing had changed (which is strange, since the other two update statements had effected massive changes to the data). When I executed
SELECT SEC_TO_TIME(QueueTime) FROM QueueTime_Snapshot;
I received the expected values, converted to the format I had wanted. Is this function (or are functions in general) simply not allowed to be used in an UPDATE statement, or is there another reason the values aren't being converted in the way I want them to be?
Is there a reason you are storing a time datatype value as an int? It seems you are running into data conversion issues.
UPDATE AgentSummaryTable SET total_logged_in_time = SEC_TO_TIME(total_logged_in_time)
That statement is converting 1 datatype (int, datatype of the column) into another datatype (time) and then storing in back into an int. Generally, you should avoid attempting to store multiple data types into one data type.
If you plan on having a int column, you should store the time values in seconds, and convert to a time value as needed. Otherwise, store your time values as a time column. The time value 05:20:12 converted to an int results in 052012 which is certainly not the seconds of that time. The functions TIME_TO_SEC and SEC_TO_TIME should be used to convert from time to seconds and vice versa.
Consider:
create table t(t int);
insert into t values (sec_to_time(19212));
select sec_to_time(19212),
cast(sec_to_time(19212) as unsigned integer) i,
sec_to_time(19212) + 0 s,
t,
sec_to_time(t)
from t;
The actual results may vary across versions, but notice the difference in values.

Insert from tableA into tableB where some datetime values are null

[tableB] was created from scripting [tableA], but with columns rearranged, which is the primary reason for this task.
I now want to INSERT INTO [tableB] SELECT (column list) FROM [tableA].
[tableA] has several NULL values in a datetime2(0) column.
I get the following error when running the INSERT:
Conversion failed when converting date and/or time from character string.
Most likely this has been answered before, but I cannot seem to word my searches in a way that finds the answer. This site has been very helpful to me. I am hopeful for a simple solution, and appreciate any help.

MySQL: retrieving the newest inserted data

After inserting new data into a table, I need to select some of the new data straight after, so I can use it for inserting into another table.
The only way I can think of doing this is using the 'datetime' field I have in my row, but how would I retrieve the latest date/time inserted.
INSERT statement with NOW() value for datetime
society_select = SELECT socID, creator, datetime FROM societies.society WHERE datetime='[..datetime is the newest...]';
Hope that makes sense. Thank you
There are a number of ways to do this.
Why not make use of a trigger for this?
When a trigger creates a record you can get the id's of the records inserted. You can then do a select and insert new values into the relevant table.
MYSQL has loads of resources on using triggers.
http://dev.mysql.com/doc/refman/5.0/en/triggers.html
Or you can get the number of rows affected then use this to get the required result set in a select statement.
Get the last inserted ID?
If you are inserting one row into the database at a time then you would be able to get the last inserted id from MYSQL. This will be the Primary Key value of the record you last inserted into the database.
You would basically do something like this in mysql:
SET #inserted_id = LAST_INSERT_ID();
Or in PHP you can use the function:
mysql_insert_id(&mysql);
http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
Sort the results by their datetime in descending order, and select the first of them.
society_select = SELECT socID, creator, datetime FROM societies.society ORDER BY datetime DESC LIMIT 1;
you can use this with an auto increment filed. after inserting data you can retrieve the list inserted id from the table. and use that id to get the latest record.
A trigger as suggested is an option. If you don't want to use that for some kind of reason you can:
Add an integer primary key with auto_increment as ID and sort it DESC (e.g. INT(11))
Sort descending on a timestamp column (ofcourse with an index on it)
Use a trigger after inserting the data. This is for sure the cleaner way.
Another option is to use a method like mysql_insert_id. Assumed that you use PHP. There are of course equivalent methods in other languages as well.
Sorting is not an option(if not wrapped smart in transaction) - If you have multiple writes and reads on the table this might end up pretty ugly.