I have a table in which the first column is auto_increment. I want to insert data into the table, but skip the first column as it is updated automatically when a new row is begun.
so:
INSERT INTO table VALUES (NULL,"lady","gaga","rulz");
But NULL cannot be inserted into a column as I specified earlier. What do I need to replace NULL with so that the column doesn't get anything inserted into it?
Just make sure you specify the respective column names
INSERT INTO table (col1, col2, col3) VALUES ("lady","gaga","rulz");
You don't even need to fill all columns (if they are not required), Ie.
INSERT INTO table (col2) VALUES ("gaga");
insert into table(field1, field2, field3) values('lady', 'gaga', 'sucks')
You need to explicitly specify the column names and order. In other words
INSERT INTO table (field2, field3, field4) VALUES ("lady","gaga","rulz");
BTW it is typically a good idea to avoid the implicit insert syntax (but maybe for the simplest / debug time snippets), lest you get surprised when/if the underlying table schema was somehow changed.
Also, so you know, something, will get inserted into the (here) field1 column. When you define or alter the schema of a table, a given field can either be nullable or not, and/or it can have a default value or not. In the SQL provided above, you can only omit the values for fields that are either nullable or have a default value; SQL will otherwise return an error and won't insert any part of the new record.
Related
Since IF EXISTS isn't supported by MySQL I am struggling to think of the syntax for doing something like the following pseudo in MySQL:
IF ((select count(*) from table where col1='var1' AND col2='var2' AND col3='var3' AND col4='var4' AND col5='var5')>0) then
combination of vars exist in record - do a thing;
ELSE
combination of vars does not exist in record - insert record;
END IF;
I should have thought CASE would suit this but for life of me I'm unable to think of the correct syntax. I'd use unique indexes but every one of the columns needs to allow duplicates, it's only a matching combination of all the columns that needs to be unique, not the fields themselves.
I'm told using a composite key across all the columns would avoid duplicate inserts but from what I gather I need to use a different insert then.
Short version: In MySQL, how do I insert new row only if an exact specified match of columns is not found in an existing row.
Any advice or suggestions would be greatly appreciated.
Create a composite unique index. This will allow any number of duplicates in the individual fields, but the combination needs to be unique.
CREATE UNIQUE INDEX ix_uq ON test (field1, field2, field3);
...and use INSERT IGNORE to insert if the unique index is not violated. If it is, just ignore the insert.
INSERT IGNORE INTO test (field1,field2,field3) VALUES (1,1,1);
An SQLfiddle for testing.
If you want to insert unless there's a duplicate, and update if there is, you can also use INSERT INTO ... ON DUPLICATE KEY UPDATE;
INSERT INTO test (field1, field2, field3) VALUES (1,1,1)
ON DUPLICATE KEY UPDATE field4=field4+1;
Another SQLfiddle.
If I have a table like this:
CREATE TABLE Person (id INT AUTO_INCREMENT PRIMARY KEY, age INT);
Is there a simpler method than rewriting the attributes of the column like that ?
INSERT INTO Person (age) VALUES (18);
I know that for the DEFAULT values there is the keyword DEFAULT, but is there a similar one for AUTO_INCREMENT? I work with pretty long tables and I don't want to rewrite all the column names each time I make an INSERT.
Thank you for your help.
https://dev.mysql.com/doc/refman/5.7/en/example-auto-increment.html says:
No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign 0 to the column to generate sequence numbers, unless the NO_AUTO_VALUE_ON_ZERO SQL mode is enabled. If the column is declared NOT NULL, it is also possible to assign NULL to the column to generate sequence numbers.
So any of the following will work:
INSERT INTO Person VALUES (0, 18);
INSERT INTO Person VALUES (NULL, 18);
INSERT INTO Person VALUES (DEFAULT, 18);
However, it's considered good practice to list all columns explicitly when you write any INSERT statement. If someone changes the order of columns in the table, your VALUES might not get inserted into the right columns unless you list the column names explicitly. Also if someone adds or drops a column.
I am using MYSQL in my application development as my DB.
I want to clarify a thing.
Imagine There is a table called test.
Columns are col1,col2,col3,col4.
these columns have separate indexes. that mean 4 indexes.
I am inserting a record just to col1 and col2.
When you have a index in a column insert operation have a cost.
My question is. ----
So when I insert records only to one and two Do I have an affect from col3 and col4 ?
Will indexes will fire for every insert or will it fire if I do insert to those columns?
Let's get a basic fact straight: in an RDBMS there is no such thing that you insert a record for only a selected number fields in a table. If you insert a record, then all fields within that table will have a value for that record. That value may be a null value, but it is there.
Not to mention another fact, that columns may have non-null default values, so executing an insert that does not specify value for them will still result a non-null value to be stored.
Mysql indexes even null values, so if you have separate indexes for each column, then mysql has to update all indexes when a new record is inserted into the table, regardless how many fields are specifically assigned value within the insert.
I am doing the following SQL tutorial: http://sql.learncodethehardway.org/book/ex11.html
and in this exercise the author says in the second paragraph:
In this situation, I want to replace my record with another guy but
keep the unique id. Problem is I'd have to either do a DELETE/INSERT
in a transaction to make it atomic, or I'd need to do a full UPDATE.
Could anyone explain to me what the problem is with doing an UPDATE, and when we might choose REPLACE instead of UPDATE?
The UPDATE code:
UPDATE person SET first_name = "Frank", last_name = "Smith", age = 100
WHERE id = 0;
Here is the REPLACE code:
REPLACE INTO person (id, first_name, last_name, age)
VALUES (0, 'Frank', 'Smith', 100);
EDIT: I guess another question I have is why would you ever do a DELETE/INSERT instead of just an UPDATE as is discussed in the quoted section?
According to the documentation, the difference is:
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.
So what it does:
Try to match the row using one of the available indexes;
If the row doesn't exist already: add a new one;
If the row exists already: delete the existing row and add a new one afterwards.
When might using this become useful over separate insert and update statements?
You can safely call this, and you don't have to worry about existing rows (one statement vs. two);
If you want related data to be removed when inserting / updating, you can use replace: it deletes all related data too);
When triggers need to fire, and you expect an insert (bad reason, okay).
First Replace isn't widely understood in all database engines.
Second replace inserts/updates a record based on the primary key. While with update you can specify more elaborate conditions:
UPDATE person SET first_name = 'old ' + first_name WHERE age > 50
Also UPDATE won't create records.
UPDATE will have no effect if the row does not exist.
Where as the INSERT or REPLACE will insert if the row doesn't exists or replace the values if it does.
Update will change the existing records value in table based on particular condition. So you can change one or many records in single query.
Insert or Replace will insert a new record if records is not present in table else will replace. Replace will only work if and only if you provide the primary key value in the insert or replace query. If you forget to add primary key field value than a new record will created in table.
Case example:-
Update: You have a calculation of wages to be done based on a formula using the column values. In this case you will always use update query as using one single query you can update multiple records.
Insert or Replace: Already mentioned in the link you shared.
How the REPLACE INTO statement works:
AS INSERT:
REPLACE INTO table_name (column1name, column2name, ...)
VALUES (value1, value2, ...);
AS UPDATE:
REPLACE INTO table_name SET column1name = value, column2name = value, ... ;
The REPLACE statement checks whether the intended data record's unique key value already exists in the table before inserting it as a new record or updating it.
The REPLACE INTO statement attempts to insert a new record or modify an existing record. In both cases, it checks whether the unique key of the proposed record already exists in the table. Suppose a value of NO or FALSE is returne. In that case, the REPLACE statement inserts the record similar to the INSERT INTO statement.
Suppose the key value already exists in the table (in other words, a duplicate key). In that case, the REPLACE statement deletes the existing record of data and replaces it with a new record of data. This happens regardless of whether you use the first or the second REPLACE statement syntax.
Once the REPLACE INTO statement is used to insert or modify data, it determines first whether the new data record already exists in the table. It checks if the PRIMARY or the UNIQUE KEY matches one of the existing records.
If there is no matching key, the REPLACE works like a normal INSERT statement. Otherwise, it deletes the existing record and replaces it with the new one. This is considered a sort of modification or update of an existing record. However, it would be best if you were careful here. Suppose you do not specify a value for a column in the SET clause. In that case, the REPLACE statement uses the default value (if a default value has been set). Otherwise, it's set as NULL.
i want to insert in a table using columns order not name
insert into tableName(1,2,5) values('val1','val2','val3');
i dont want to use
insert into tableName values('val1','val2','val3');
because the table does not contain just 3 columns
how can i do it
because columns name are encrypted so I can not rely on this
insert into tableX("cCGSvKJVQXnt8A==","aDOlOQrPfg==","qsdcx112")
values('val1','val2','val3');
is there any idea how can i deal with this
thank
You can't use the ordinal number of a column in an insert statement. However, you can accomplish what you're trying to do (insert values into specific columns in a table) using the column names instead.
Presume your table has five columns; I'm going to call them "Alpha", "Bravo", "Charlie", "Delta", and "Echo", since you haven't given us the schema for your table, but replace these names with the names of the columns actually in your table. I'm guessing that your third and fourth column (my "Charlie" and "Delta") are nullable. You can then insert a tuple/row in your table with the other three columns filled using syntax like this:
INSERT INTO TableName(Alpha, Bravo, Echo) VALUES ("val1", "val2", "val3");
If, per your comments above, your column names are unprintable characters (which is a terrible, terrible idea), you can explicitly insert NULLs into the missing columns:
INSERT INTO TableName VALUES ("val1", "val2", NULL, NULL, "val3");
but the weakness here is that, if additional columns are subsequently added to your table's schema, the insert statement will start failing.
You need to put the column names where you have the 1,2,5. You can't use the column number.
insert into tableName(1,2,5) values("val1","val2","val3");