I have a SQL statement to insert a record into a table. The table is defined as;
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| title | varchar(255) | NO | | NULL | |
| description | text | NO | | NULL | |
| filename | varchar(255) | NO | | NULL | |
| type | varchar(255) | NO | | NULL | |
| size | int(11) | NO | | NULL | |
+-------------+--------------+------+-----+---------+----------------+
The SQL statement is;
INSERT INTO photos
(title, description, filename, type, size)
VALUES
('Title D', 'Description D', 'Filename_D', 'BMP', '2000');
I was always taught that if you did not match column type to the type of data you were trying to insert or update, SQL would throw an error.
To my surprise the SQL statement worked in MySQL and MS Access even though the "size" column is defined as integer and the size data in the SQL statement is enclosed in quotes making it a string ('2000').
Is this a MySQL and MS Access feature or is this how SQL works across all SQL compliant databases?
String to number conversion is automatic in most databases. So, you can express your query this way:
INSERT INTO photos (title, description, filename, type, size)
VALUES ('Title D', 'Description D', 'Filename_D', 'BMP', '2000');
This is a bad idea, because implicit conversion can generate conversion errors -- and you have no clue where they come from. I strongly advocate using the right types or explicit conversion:
INSERT INTO photos (title, description, filename, type, size)
VALUES ('Title D', 'Description D', 'Filename_D', 'BMP', 2000);
Thank you Gordon Linoff for the answer.
Eric Brandt, I will open a fresh question on this. I'm also interested in seeing the response.
Related
I have table with data on old game characters. I'd like to add a gender column.
If I do
ALTER TABLE characters
ADD gender ENUM('m','f') AFTER char_name
then I get a column full of NULLs. How do I get the values in?
Using an INSERT statement tries to tag them all into new rows, instead of replacing the NULLs.
Using an UPDATE statement requires a new statement for every single entry.
Is there any way to just drop a "VALUES ('m'),('f'),('f'),('m'),('f') etc" into the ALTER statement or anything else and update them all efficiently?
There is no way to fill in specific values during ALTER TABLE. The value will be NULL or else a default value you define for the column.
You may find INSERT...ON DUPLICATE KEY UPDATE is a convenient way to fill in the values.
Example:
CREATE TABLE characters (
id serial primary key,
char_name TEXT NOT NULL
);
INSERT INTO characters (char_name) VALUES
('Harry'), ('Ron'), ('Hermione');
SELECT * FROM characters;
+----+-----------+
| id | char_name |
+----+-----------+
| 1 | Harry |
| 2 | Ron |
| 3 | Hermione |
+----+-----------+
Now we add the gender column. It will add the new column with NULLs.
ALTER TABLE characters
ADD gender ENUM('m','f') AFTER char_name;
SELECT * FROM characters;
+----+-----------+--------+
| id | char_name | gender |
+----+-----------+--------+
| 1 | Harry | NULL |
| 2 | Ron | NULL |
| 3 | Hermione | NULL |
+----+-----------+--------+
Now we update the rows:
INSERT INTO characters (id, char_name, gender) VALUES
(1, '', 'm'), (2, '', 'm'), (3, '', 'f')
ON DUPLICATE KEY UPDATE gender = VALUES(gender);
It looks strange to use '' for the char_name, but it will be ignored anyway, because we don't set it in the ON DUPLICATE KEY clause. The original char_name is preserved. Specifying the value in the INSERT is necessary only because the column is defined NOT NULL and has no DEFAULT value.
SELECT * FROM characters;
+----+-----------+--------+
| id | char_name | gender |
+----+-----------+--------+
| 1 | Harry | m |
| 2 | Ron | m |
| 3 | Hermione | f |
+----+-----------+--------+
DBFiddle
Insert into the App.settings table the following values:
(99, DEFAULT, "horizontal", "2015-09-15 04:01:04")
I have a DATABASE called App with a settings table. I am trying to insert into the table but I can not seem to get it right.
My statement:
INSERT INTO App.settings
VALUES(99, DEFAULT, "horizontal", "2015-09-15 04:01:04");
Am I doing it right? It says my answer is wrong.
mysql> DESC App.settings;
+-----------------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+---------------------+------+-----+---------+-------+
| user_id | int(7) | NO | | NULL | |
| email_frequency | tinyint(2) unsigned | YES | | NULL | |
| layout | varchar(70) | YES | | NULL | |
| updated_at | datetime | YES | | NULL | |
+-----------------+---------------------+------+-----+---------+-------+
4 rows in set (0.01 sec)
When you use insert, always list the columns in the table. Second, the default string delimiter is the single quote in SQL rather than the double quote.
So I would expect to see:
INSERT INTO App.settings (col1, col3, col4) -- your real column names here
VALUES (99, 'horizontal', '2015-09-15 04:01:04');
Note that col2 was removed from the INSERT and the VALUES because you seem to want a DEFAULT value. Not all databases support that syntax.
you are sure that all the fields of the tuple are there and if so, they are in the correct order if you are not entering all the fields of the tuple you should use the following form: INSERT INTO App.settings(value, config, position, date ) VALUES(99, "DEFAULT", "horizontal", "2015-09-15 04:01:04");
In the same order
this is only an example i dont know the fields names you must be change for the you are using
Like #GordonLinoff said, you should include the columns in your query. That way, you can also skip entering the DEFAULT value for email_frequency.
As for the mistake, it's most likely the double quotes that you're currently using instead of single quotes.
Try the following:
INSERT INTO App.settings (user_id, layout, updated_at)
VALUES (99, 'horizontal', '2015-09-15 04:01:04');
I got tables like below and I am trying to INSERT data.
mysql> desc subscribers
-> ;
+---------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+----------------+
| id | smallint(6) | NO | PRI | NULL | auto_increment |
| email | varchar(32) | NO | | NULL | |
| comment | text | NO | | NULL | |
+---------+-------------+------+-----+---------+----------------+
Data insert
INSERT INTO `subscribers` VALUES (1, ‘someone#gmail.com’, ‘thanks’);
But It gives me an error.
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '#gmail.com’, ‘ thanks’)' at line 1
Does anybody see an error??
You are surrounding your strings to be inserted with some sort of apostrophe instead of a single quote. Use this instead (and copy it verbatim from this answer):
INSERT INTO `subscribers`
VALUES (1, 'someone#gmail.com', 'thanks');
Your problem is the curly single quote. But, to prevent future errors, you should always include the column list in the insert:
INSERT INTO `subscribers`(id, email, comment)
VALUES (1, 'someone#gmail.com', 'thanks');
In fact, a natural way to create the table is using an auto-incremented id. If you did then, then the INSERT would look like:
INSERT INTO `subscribers`(email, comment)
VALUES ('someone#gmail.com', 'thanks');
The id would be assigned automatically.
mysql> describe taps;
+-------------+-------------+------+-----+-------------------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+-------------------+-------+
| tag_id | int(11) | NO | | NULL | |
| time_stamp | timestamp | NO | | CURRENT_TIMESTAMP | |
| device_id | varchar(45) | YES | | NULL | |
| device_type | varchar(45) | YES | | NULL | |
+-------------+-------------+------+-----+-------------------+-------+
mysql> INSERT INTO `taps` (tag_id, time_stamp) VALUES(0, 1451610061);
ERROR 1292 (22007): Incorrect datetime value: '1451610061' for column 'time_stamp' at row 1
WHY?? I have found many similar questions, but not of them seem quite this black and white.
1451610061 is a valid timestamp. I checked it at http://www.unixtimestamp.com/ and it evaluates as expected.
So, why doesn't MySql like it?
The MySQL timestamp format is 2016-02-13 15:48:29 or Y-m-d H:i:s convert your timestamp to that format first, and then MySQL will accept it.
If you insert a new record without defining the timestamp, and then select the row from that table, you will notice that that's the format that it gives to the new default record.
if if you want to convert it directly in your query use:
INSERT INTO `taps` (tag_id, time_stamp) VALUES(0, from_unixtime('1451610061'));
Using this Q&A on StackOverflow as reference.
And from_unixtime documentation
Try this ->
$item->time_stamp = date('Y-m-d H:i:s', strtotime($request->time_stamp));
I have recently started to work with MySQL for my study job and now face following problem:
My predecessor created a textmining table of the following structure:
+------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| TokenId | int(11) | NO | PRI | 0 | |
| Value | varchar(255) | YES | | NULL | |
| Frequency | int(11) | YES | | NULL | |
| PMID | int(11) | YES | MUL | NULL | |
+------------+--------------+------+-----+---------+-------+
In the context of restructuring, I added the following column:
+------------+--------------+------+-----+---------+-------+
| NewTokenId | int(11) | YES | | NULL | |
+------------+--------------+------+-----+---------+-------+
If I now run the query:
insert into TitleToken(NewTokenId) select t.TokenId from Token as t, TitleToken as tt where t.Value = tt.Value
or even the query:
insert into TitleToken(NewTokenId) values(1);
I get following output:
ERROR 1062 (23000): Duplicate entry '0' for key 'PRIMARY'
As I said, I am relatively new to (hands-on) *SQL and it feels like a stupid mistake, but since the column NewTokenId is no primary key, not unique and even Null is YES, I thought I'd be able to insert basically anything I want.
Any hint would be appreciated... thanks in advance :)
The problem here is that you have a default value for the primary key "TokenID", if you do not insert a value for the key in your insert statement the system will automatically insert 0. However, if there is another tuple with the same value for this attribute (which is probable because the default is 0) you will get that error.
You are attempting to perform an insert into a table without providing a unique value for TokenId. By default, according to the table description, TokenId defaults to 0, you cannot have multiple identical values in that column.