I am using the INSERT function to try and add new values to a table. While there is no error when I run the query, it is not showing the new attributes added to the table. I have no idea why. I also have safe updates turned off. The values entered also match the value type for each column of the table.
CODE ENTERED:
INSERT INTO productlines
VALUES
('Jet Packs', 'Futuristic flying machines that only exist in prototype.', NULL, NULL),
('Jet Skis', 'Much more realistic things that very much exist already.', NULL, NULL),
('Wheelbarrows', 'I cannot believe we actually stock these.', NULL, NULL);
SELECT *
FROM productlines;
CREATE TABLE `productlines` (
`productLine` varchar(50) NOT NULL,
`textDescription` varchar(4000) DEFAULT NULL,
`htmlDescription` mediumtext,
`image` mediumblob,
PRIMARY KEY (`productLine`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
INSERT INTO
[name of your **TABLE**](col1, col2, col3)#NAME OF YOUR COLUMNS
VALUES
('value for col1','value for col2','value for col3'),
You didn't add the column names for which you are performing the insert
Related
I'm new to MySQL & I try to enter records to mysql table. I'm getting following error
INSERT INTO advertising.discountauthorizationrequst SET DARDateTime=cast('2003-01-13 16:50:32' as datetime), `DARPubCode`=trim('DD'), `DARPubDate`=cast('2022-05-08' as date), `DARAutUser`=trim("U0001"), `DARDeviceID`=trim('123456789ABCDEFGHIJKL987456'), `DARMessage`=trim("This Is Test Message"), `DARGranted`=("0"), `DARUser`=trim("DATAENTRYUSERNAME") Error Code: 1054. Unknown column 'DARDateTime' in 'field list'
I listed my INSERT statement below. Someone please help me to solve this issue. I'm using mysql workbench 8.0.
Columns:
DARDateTime datetime PK
DARPubCode varchar(3) PK
DARPubDate date PK
DARAutUser varchar(5)
DARDeviceID varchar(50)
DARMessage varchar(100)
DARGranted varchar(1)
DARUser varchar(50) PK
Here is script
INSERT INTO `advertising`.`discountauthorizationrequst`
SET
`DARDateTime`=cast('2003-01-13 16:50:32' as datetime),
`DARPubCode`=trim('DD'),
`DARPubDate`=cast('2022-05-08' as date),
`DARAutUser`=trim("U0001"),
`DARDeviceID`=trim('123456789ABCDEFGHIJKL987456'),
`DARMessage`=trim("This Is Test Message"),
`DARGranted`=("0"),
`DARUser`=trim("DATAENTRYUSERNAME");
Edited..
Table Inspactor - DDL
CREATE TABLE `discountauthorizationrequst` (
`DARDateTime` datetime NOT NULL,
`DARPubCode` varchar(3) NOT NULL,
`DARPubDate` date NOT NULL,
`DARAutUser` varchar(5) DEFAULT NULL,
`DARDeviceID` varchar(50) DEFAULT NULL,
`DARMessage` varchar(100) DEFAULT NULL,
`DARGranted` varchar(1) DEFAULT NULL,
`DARUser` varchar(50) NOT NULL,
PRIMARY KEY (`DARDateTime`,`DARPubCode`,`DARPubDate`,`DARUser`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
You are actually confusing the SQL commands and coming up with a hybrid of them. The INSERT command most commonly is done in two ways..
insert into SomeTable
( these, columns )
values
( oneValue, anotherValue)
or
insert into SomeTable( these, columns )
select oneColumn, secondColumn
from SomeOtherTable
where SomeCondition
The UPDATE command is based on an EXISTING record that you want to change
Update SomeTable set
thisColumn = SomeValue,
anotherColumn = SomeOtherValue
where SomeCondition
So, what you appear to be doing would be written as
INSERT INTO advertising.discountauthorizationrequst
( DARDateTime,
DARPubCode,
DARPubDate,
DARAutUser,
DARDeviceID,
DARMessage,
DARGranted,
DARUser
)
values
(
cast('2003-01-13 16:50:32' as datetime),
'DD',
'2022-05-08',
'U0001',
'123456789ABCDEFGHIJKL987456',
'This Is Test Message',
'0',
'DATAENTRYUSERNAME'
)
Notice the readability with formatting, you can see each column that is needed followed by the explicit values (which could be parameterized during code later) are in the same ordinal context. So, if you ever needed to add a new column to the insert, easy to do with the same ordinal position in the values provided secondarily to it.
As for the 3rd column, by providing a string in YYYY-MM-DD, SQL typically auto-converts to a date format. Other fields, you dont need to explicitly TRIM() everything. If parameterized, you would pass the trimmed VALUE, when you get to that point in your development.
I found the mistake that I made. I created triggers for the above table. After I deleted those triggers its working.
I have a query like
INSERT INTO support_users VALUES("1",,"2","1","4",,,"2017-05-06 20:24:36");
but new MySQL not inserting given error Error Code: 1064
but I changed it to
INSERT INTO support_users VALUES("1","","2","1","4",,,"2017-05-06 20:24:36");
working
but previous MySQL not having such an issue.how to solve that. without changing query
table definition
CREATE TABLE support_users (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`client` int(11) DEFAULT NULL,
`user` int(11) DEFAULT NULL,
`ticket` int(11) DEFAULT NULL,
`scope` int(11) DEFAULT NULL,
`notify` tinyint(1) DEFAULT NULL,
`email` tinyint(1) DEFAULT NULL,
`added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=46 DEFAULT CHARSET=utf8;
Firstly, respect the Datatype. If its Integer don't use quotes.
The right way to approach your problem will be use of NULL. So this works across any version of MySQL.
INSERT INTO support_users VALUES(1,NULL,2,1,4,NULL,NULL,'2017-05-06 20:24:36');
1)
Integer column values should not be quoted.
So "1" becomes 1
2)
Auto Increment values should not be manally given to the SQL -- let it work it out itself.
3)
Inserting NULL using the NULL keyword.
4)
Your date-time column is set in its definition to show the current date-time of the row being inserted when it is inserted. As you are inserting (rather than updating, etc.) you therefore do not need to include this data.
5)
It is easier for your sanity to also list which columns are being added to with the INSERT instruction.
6)
Use single quotes ' around string data not double quotes ("), when working directly with MySQL.
Result:
INSERT INTO support_users( `id`, `ticket`, `scope` , `notify`)
VALUES (1, 2,1,4);
This will cause errors if you try to insert twice, because you are forcing the Primary Key (id) to be 1. To avoid this, skip the Auto Increment (id) column value.
Or for clarity only; the full SQL:
INSERT INTO support_users VALUES (1, NULL, 2, 1, 4, NULL, NULL, '2017-05-06 20:24:36');
Skipping the Auto Increment (id) column value (as referenced above):
INSERT INTO support_users VALUES (NULL, NULL, 2, 1, 4, NULL, NULL, '2017-05-06 20:24:36');
I got a MySQL database with some tables.
In one of these tables i want to insert by a SQL script some new rows.
Unfortunately i have to insert in two columns an empty string and the two columns are part of an unique key for that table.
So i tried to set UNIQUE_CHECKS before and after the insert, but i'm getting errors because of duplicate entries.
Here is the definition of the table:
CREATE TABLE `Table_A` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`number` varchar(25) DEFAULT NULL,
`changedBy` varchar(150) DEFAULT NULL,
`changeDate` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`,`number`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
And the INSERT statement which causes error:
SET UNIQUE_CHECKS = 0;
INSERT INTO `Table_A`
(`name`, `number`, `changedBy`, `changeDate`)
SELECT DISTINCT '', 'myUser', CURRENT_TIMESTAMP
FROM Table_A
AND id NOT IN
(
SELECT DISTINCT id
FROM Table_A
);
SET UNIQUE_CHECKS = 1;
As You can see, i'm using UNIQUE_CHECKS.
But as i said this doesn't work properly.
Any help or suggestion would be appreciated.
Patrick
Switching off Unique Keys for the insert operation doesn't indicate that it will check uniqueness only for the operations that happen after you switch it on again. It just means that database will not waste time to check the constraint during the time it is switch off but it will check the constraint when you switch it on again.
What it measn is that you nead to ensure that column has unique value in a columns with Unique Keys before you can turn it on. Which you don't do.
If you want to maintain Uniqueness somehow for new records you insert after some point in time you would need to create trigger and manually check the new records against already existing data. The same possibly goes for updates. But I don't recommend it - you should probably redesign data so either the Unique Key is not there or the data is truly unique for all the records there are and will be.
I have two MySQL tables and want to insert multiple records instead of creating one by one, get id and insert related records
here are the tables:
CREATE TABLE `visit` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ip_address` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
)
CREATE TABLE `visitmeta` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`page_visit_id` int(11) NOT NULL,
`key` varchar(255) NOT NULL,
`value` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
)
Currently I insert one record on visit, get its id and insert records on visit meta. Is there a way to create a new record into visit and in the same query create visit meta records?
It's not possible to insert records in two tables with a single query, but you can do it in just two queries using MySQL's LAST_INSERT_ID() function:
INSERT INTO visit
(ip_address)
VALUES
('1.2.3.4')
;
INSERT INTO visitmeta
(page_visit_id, key, value)
VALUES
(LAST_INSERT_ID(), 'foo', 'bar'),
(LAST_INSERT_ID(), 'baz', 'qux')
;
Note also that it's often more convenient/performant to store IP addresses in their raw, four-byte binary form (one can use MySQL's INET_ATON() and INET_NTOA() functions to convert to/from such form respectively).
I have a form on a website which has a lot of different fields. Some of the fields are optional while some are mandatory. In my DB I have a table which holds all these values, is it better practice to insert a NULL value or an empty string into the DB columns where the user didn't put any data?
By using NULL you can distinguish between "put no data" and "put empty data".
Some more differences:
A LENGTH of NULL is NULL, a LENGTH of an empty string is 0.
NULLs are sorted before the empty strings.
COUNT(message) will count empty strings but not NULLs
You can search for an empty string using a bound variable but not for a NULL. This query:
SELECT *
FROM mytable
WHERE mytext = ?
will never match a NULL in mytext, whatever value you pass from the client. To match NULLs, you'll have to use other query:
SELECT *
FROM mytable
WHERE mytext IS NULL
One thing to consider, if you ever plan on switching databases, is that Oracle does not support empty strings. They are converted to NULL automatically and you can't query for them using clauses like WHERE somefield = '' .
One thing to keep in mind is that NULL might make your codepaths much more difficult. In Python for example most database adapters / ORMs map NULL to None.
So things like:
print "Hello, %(title)s %(firstname) %(lastname)!" % databaserow
might result in "Hello, None Joe Doe!" To avoid it you need something like this code:
if databaserow.title:
print "Hello, %(title)s %(firstname) %(lastname)!" % databaserow
else:
print "Hello, %(firstname) %(lastname)!" % databaserow
Which can make things much more complex.
Better to Insert NULL for consistency in your database in MySQL. Foreign keys can be stored as NULL but NOT as empty strings.
You will have issues with an empty string in the constraints.
You may have to insert a fake record with a unique empty string to satisfy a Foreign Key constraint. Bad practice I guess.
See also: Can a foreign key be NULL and/or duplicate?
I don't know what best practice would be here, but I would generally err in favor of the null unless you want null to mean something different from empty-string, and the user's input matches your empty-string definition.
Note that I'm saying YOU need to define how you want them to be different. Sometimes it makes sense to have them different, sometimes it doesn't. If not, just pick one and stick with it. Like I said, I tend to favor the NULL most of the time.
Oh, and bear in mind that if the column is null, the record is less likely to appear in practically any query that selects (has a where clause, in SQL terms) based off of that column, unless the selection is for a null column of course.
If you are using multiple columns in a unique index and at least one of these columns are mandatory (i.e. a required form field), if you set the other columns in the index to NULL you may end up with duplicated rows. That's because NULL values are ignored in unique columns. In this case, use empty strings in the other columns of the unique index to avoid duplicated rows.
COLUMNS IN A UNIQUE INDEX:
(event_type_id, event_title, date, location, url)
EXAMPLE 1:
(1, 'BBQ', '2018-07-27', null, null)
(1, 'BBQ', '2018-07-27', null, null) // allowed and duplicated.
EXAMPLE 2:
(1, 'BBQ', '2018-07-27', '', '')
(1, 'BBQ', '2018-07-27', '', '') // NOT allowed as it's duplicated.
Here are some codes:
CREATE TABLE `test` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`event_id` int(11) DEFAULT NULL,
`event_title` varchar(50) DEFAULT NULL,
`date` date DEFAULT NULL,
`location` varchar(50) DEFAULT NULL,
`url` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `event_id` (`event_id`,`event_title`,`date`,`location`,`url`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
Now insert this to see it will allow the duplicated rows:
INSERT INTO `test` (`id`, `event_id`, `event_title`, `date`, `location`,
`url`) VALUES (NULL, '1', 'BBQ', '2018-07-27', NULL, NULL);
INSERT INTO `test` (`id`, `event_id`, `event_title`, `date`, `location`,
`url`) VALUES (NULL, '1', 'BBQ', '2018-07-27', NULL, NULL);
Now insert this and check that it's not allowed:
INSERT INTO `test` (`id`, `event_id`, `event_title`, `date`, `location`,
`url`) VALUES (NULL, '1', 'BBQ', '2018-07-28', '', '');
INSERT INTO `test` (`id`, `event_id`, `event_title`, `date`, `location`,
`url`) VALUES (NULL, '1', 'BBQ', '2018-07-28', '', '');
So, there is no right or wrong here. It's up to you decide what works best with your business rules.