I've got a script that's creating a table, and then inserting a row afterwards. Here is my SQL code executing to create the table:
CREATE TABLE polls (
id INT NOT NULL UNIQUE AUTO_INCREMENT,
name VARCHAR(255) NOT NULL UNIQUE,
author VARCHAR(255) NOT NULL,
created DATETIME NOT NULL,
expires DATETIME,
PRIMARY KEY(id)
)
And here is where I add a new row:
INSERT INTO polls
VALUES ('TestPoll'),('Billy Bob'),('2013-05-01 04:17:31'),('2013-05-01 04:17:31')
or
INSERT INTO polls
VALUES ('TestPoll','Billy Bob','2013-05-01 04:17:31','2013-05-01 04:17:31')
(I get the same error regardless)
I always get this error:
<class '_mysql_exceptions.OperationalError'>, OperationalError(1136, "Column count doesn't match value count at row 1"), <traceback object at 0x7f7bed982560>
Your syntax is wrong, try:
INSERT INTO polls
VALUES ('TestPoll','Billy Bob','2013-05-01 04:17:31','2013-05-01 04:17:31')
but if your table structure changes, your code will break, a safer version is:
INSERT INTO polls (name, author, created, expires)
VALUES ('TestPoll','Billy Bob','2013-05-01 04:17:31','2013-05-01 04:17:31')
Your INSERT query is not correctly formatted.
INSERT INTO polls (name, author, created, expires)
VALUES ('TestPoll','Billy Bob','2013-05-01 04:17:31','2013-05-01 04:17:31');
For more information, visit MySQL Reference Manual for the INSERT statement.
EDIT: It's always a good idea to explicitly type each column name, in case the table structure will change in some foreseeable future.
In mysql you have to pass column name in your insert query.After assigning column name your query will look like
INSERT INTO polls (name,author,created,expires) values ('TestPoll','Billy Bob','2013-05-01 04:17:31','2013-05-01 04:17:31');
Hope it helps.
Related
I created a table in MySql
CREATE TABLE newuser(id VARCHAR(10) PRIMARY KEY,sname VARCHAR(20));
When I INSERT record it works fine
INSERT INTO newuser VALUE('abc123','monika');
But sometimes I don't want to supply id in the INSERT query and sometimes I want to supply. In case I don't supply id MySql automatically generate one.
What can I do to get both below query works?
INSERT INTO newuser VALUE('abc123','monika');
INSERT INTO newuser VALUE('nikita');
'I don't understood ANYTHING' - very new then.
Firstly second insert statement is invalid please review https://dev.mysql.com/doc/refman/8.0/en/insert.html -
'If you do not specify a list of column names for INSERT ... VALUES or INSERT ... SELECT, values for every column in the table must be provided by the VALUES list, SELECT statement, or TABLE statement.'
Secondly uuid is a function in which 'A UUID is designed as a number that is globally unique in space and time.' https://dev.mysql.com/doc/refman/8.0/en/insert.html
You can easily select uuid() to see what it produces.
You will need to increase the id size
If you wish to use it in an insert
insert into users values (uuid(),<sname>);
I have a strange problem with my MariaDB database. I create an empty table with the following code:
drop table if exists Subject;
CREATE TABLE Subject (
id integer primary key auto_increment,
code varchar(100) unique not null,
name text not null
);
Query executed OK, 0 rows affected.
I try to insert some data into the table:
INSERT INTO Subject (id, code, name) VALUES
(0,'KMI/AIdb/PHW/15','Počítačový hardvér'),
(1,'KMI/AIdb/DBA/15','Tvorba databázových aplikácií'),
(2,'KMI/SPRVdb/INF/16','Informatika a základy správy databáz'),
(3,'KMI/AIdb/PR4/15','Programovanie 4 - Objektové programovanie'),
(4,'KMI/AIdb/DBS/15','Databázové informačné systémy');
Error in query (1062): Duplicate entry '1' for key 'PRIMARY'
If I run the same query one more time:
INSERT INTO Subject (id, code, name) VALUES
(0,'KMI/AIdb/PHW/15','Počítačový hardvér'),
(1,'KMI/AIdb/DBA/15','Tvorba databázových aplikácií'),
(2,'KMI/SPRVdb/INF/16','Informatika a základy správy databáz'),
(3,'KMI/AIdb/PR4/15','Programovanie 4 - Objektové programovanie'),
(4,'KMI/AIdb/DBS/15','Databázové informačné systémy');
Query executed OK, 5 rows affected.
I believe it has something to do with the auto_increment, but I have a huge database dump that I would like to insert. Is this a bug, or is this an expected behavior?
AUTO_INCREMENT attribute can be used to generate a unique identity for new rows.
You can also explicitly assign 0 to the column to generate sequence numbers unless the NO_AUTO_VALUE_ON_ZERO SQL mode is enabled.
Read here for more details
The first insert created id=1. This is because "0" (or NULL) is treated specially to mean "give me the next id". Then the second row tried to explicitly insert id=1 and got a "duplicate".
Did your dump include a row with id=0, as you imply in a Comment. That sounds wrong.
Using id autoincrement don't insert id
INSERT INTO Subject (code, name) VALUES
('KMI/AIdb/PHW/15','Počítačový hardvér'),
('KMI/AIdb/DBA/15','Tvorba databázových aplikácií'),
('KMI/SPRVdb/INF/16','Informatika a základy správy databáz'),
('KMI/AIdb/PR4/15','Programovanie 4 - Objektové programovanie'),
('KMI/AIdb/DBS/15','Databázové informačné systémy');
overall don't insert 0 for id
I wanted to add an entry inside a table in SQL database.
For example I have the following Database
CREATE TABLE `distributor_geneology` (
`distributor_gen_id` bigint(20) NOT NULL,
`user_id` varchar(24) NOT NULL,
`id` bigint(20) NOT NULL,
`sponsor_id` bigint(20) NOT NULL,
`rank` tinyint(4) NOT NULL
);
And I want to add an entry in sponsor_id or say id inside a database.
First, I imported the database in my SQL Workbench then In my SQL Workbench, I ran a command select * from distributor_geneology which gave me
Error Code: 1146. Table 'dba_db.distributor_genelogy' doesn't exist
[Question] How can I create/add Entry for ID (or sponsor ID or any other filed)?
One typical way which data would enter a MySQL database is via an INSERT statement:
INSERT INTO distributor_geneology (distributor_gen_id, user_id, id, sponsor_id, rank)
VALUES
(1, 1, 1, 1, 1);
I am inserting 1 everywhere, but you may alter the tuple with the values you want.
Another way to get data into a table is bulk loading via LOAD DATA.
For your first part of your question which is "Add an entry to inside table"
this operation called insertion in the database and the keyword database used to insert data is insert into
It is possible to write the INSERT INTO statement in two ways:
1- specifies both the column names and the values to be inserted
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
you can rearrange the columns orders as you want but must the values be the same order of the columns and you can let any column null if you don't want to insert any data in this column but be careful if you have not null column you must insert in you query
in your case, all the columns you have are not null.
2- if you do not need to specify the column names in the SQL query. make sure the order of the values is in the same order as the columns in the table
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
For your second part of your question which is "Error Code: 1146. Table 'dba_db.distributor_genelogy' doesn't exist"
First, ensure you imported the DB correctly and if yes > write try to use DB name in your query.
select * from DB_Name.Table_Name
Edit:
Try this query format
INSERT INTO distributor_geneology (distributor_gen_id, user_id, id, sponsor_id, rank)
VALUES
(10, '10', 10, 10, 10);
please note I put second value between 2 quotes because you are defining the user_id as varchar which means not an integer so we should put it between qouts
I am using the SQL feature phpMyAdmin to add 1 single record into my table. For simplicity, the record will be blank except for the 'symbol' field.
Table structure:
token_id = auto-increment, primary key
symbol = varchar(255)
every thing else is set to allow null entires, so should be irrelevant
I have tried the following queries, but all result in the same error:
unknown column 'symbol' in 'field list'
What I have tried:
INSERT INTO tokens (symbol) VALUES ('XYZ');
INSERT INTO tokens (symbol) VALUES ("XYZ");
INSERT INTO tokens (symbol) VALUES (XYZ);
INSERT INTO tokens.symbol VALUES ('XYZ');
INSERT INTO `tokens`.`symbol` VALUES ('XYZ');
Any suggestions?
Just for reference, trying the INSERT and using all columns and setting them to null results in the same exact error.
The correct format with backticks is
INSERT INTO tokens (symbol) VALUES ('XYZ');
FYI, I tried your first query on my server and worked fine so might be a problem with table structure.
Alright, i have revised the question to also include what i have so far, and what i want to do. So here goes it:
CREATE ORDER (
product_nat_id int(3) NOT NULL,
name VARCHAR(20),
PRIMARY KEY (product_nate_id)
)
INSERT INTO ORDER(product_nat_id, name) VALUES(1, 'Product 1');
INSERT INTO ORDER(product_nat_id, name) VALUES(2, 'Product 2');
INSERT INTO ORDER(product_nat_id, name) VALUES(3, 'Product 3');
CREATE TABLE INT_PRODUCT (
product_id INTEGER NOT NULL AUTO_INCREMENT,
product_nat_id INTEGER NOT NULL,
title TINYTEXT,
dateCreate TIMESTAMP CURRENT_TIMESTAMP,
CONSTRAINT INT_PRODUCT_PK PRIMARY KEY (product_id),
UNIQUE INT_PRODUCT_NK (product_nat_id));
But what i want is, whenever a record arrives with an updated value but duplicate key, i need to insert it (and not updated), but avoid duplicate constraint based on the difference in time inserted. Hope this makes sense now.
I would suggest the following:
Look up the previous record. I assume you should know what that would be
SELECT Count(*) FROM dim WHERE recordId = '$recordid'
If in step 1 the records returned are larger than 0 then invalidate the 'previous' record:
UPDATE dim SET datevalid = '$datevalue' where recordId = '$recordid' and status = 2
Continuing with step 1 where the ecords return in the check are larger than 0 now do the insert:
INSERT INTO dim (recordId,field1,field2,date,status) VALUES (1,'sad','123123','2013-03-26',1)
If step 1 was false then just do the insert:
INSERT INTO dim (recordId,field1,field2,date,status) VALUES (1,'sad','123123','2013-03-26',1)
I would add a status field just as an extra measure when you need to find records and distinguish between valid or invalid then you do not need to filter between dates. You can then use the status field. Also have a unique auto-increment key for every record even though the data might be the same for a set of valid and invalid records. recordId and unique key will not be the same in this case. You assign the recordId and the system will assign the unique key on the table. status = 1 is valid and status = 2 is invalid.
Hope this helps!
sample code of your post like as:
Insert query syntax looks like this:
INSERT INTO table (primarykeycol,col1,col2)
VALUES (1,2,3) ON DUPLICATE KEY UPDATE col1=0, col2=col2+1
If there is already a row with primarykeycol set to 1 this query is equal to:
UPDATE table SET col1=0, col2=col2+1 WHERE primarykeycol = 1
explanation as:
Ordinarily to achieve the same result you would have to issue an
UPDATE query, then check if there were affected rows and if not
issue an INSERT query.
This way, you can do everything in one step – first try insert and
then update if insert fails.
One situation for which this type of syntax is perfect is when you
work with daily counters. For example, you might have a table with
PostID, Date and Count columns.
Each day you’d have to check if you already created an entry for
that day and if so increase the count column – and this can be
easily substituted with one INSERT … ON DUPLICATE KEY UPDATE query.
Unfortunately there are some caveats. One being that when you have
multiple unique indexes it will act as if you had an OR condition in
WHERE clause of UPDATE query.
This means that multiple rows should be update, but INSERT … ON
DUPLICATE KEY UPDATE will update only one row.
MySQL manual: INSERT ON DUPLICATE KEY UPDATE Syntax