I normally found three ways of using MYSQL insert Command
INSERT INTO `table` (field1, field2, field3) VALUES ('value1', 'value2', 'value3');
or
INSERT INTO `table` VALUES ('value1', 'value2', 'value3');
or
INSERT INTO `table` SET `field1`='value1', `field2`='value2', `field3`='value3';
Is there any differences among these?
The first two are standard SQL; the third one is non-standard and specific to MySQL, derived from the standard syntax for UPDATE.
The difference between the first two is that one specifies the fields that you want to insert, which is more flexible because you can miss out fields if you're happy with them being set to NULL. Also specifying the fields means that the statement will still work if the table layout changes; if you don't specify the fields you're relying on the table never changing.
You are looking for differences in terms of what? In terms of usage, the first and third insert statements let you to set only those columns which you need whereas the second statement always tries to insert the values to all columns in order of table structure.
Only one difference, pretty obvious to me: the second one don't let you specify your own field set to insert.
Related
For example i have table with a different field names(column), lets say 5 columns and all of them are empty. And i wanted to insert data in one specific column. Is it possible? I'm looking for example of this, but unlucky to find one. Most of insert into statements examples required all columns to be filled. If possible, can you give me the correct syntax? I'm sorry if i'm lacking research or it's already been asked, it's ok if you will redirect me to the link.
If you want insert on column3, leaving empty the other:
INSERT INTO table_name (column1,column2,column3,column4,column5)
VALUES ("","","VALUE","","");
The other part of program would UPDATE the other columns:
UPDATE table_name
SET column1=value1,column2=value2,column4=value4,column5=value5
WHERE some_column=some_value;
The documentation on how to construct an INSERT INTO statement is here: INSERT INTO Statement (Microsoft Access SQL).
But basically, you just need to be explicit about which columns you want to insert values for, and omit the other ones, like this:
INSERT INTO table (colname) VALUES ('colvalue')
What happens to the fields you omit? The documentation says:
When you do not specify each field, the default value or Null is inserted for missing columns.
I've got a table with two columns that links a row id from one table to a row id of another, basically I need to be able to insert multiple rows on this table where one column is a fixed value for the insert and the other changes. The insert is done in php using prepared statements and there is an unknown number of rows to be inserted (I've solved this part using call_user_func_array).
Here is an example of what I need to do:
example_table (column_A, column_B)
The insert:
INSERT INTO example_table (column_A, column_B) VALUES(a, b), VALUES(a, c), VALUES(a, d);
Translated to prepared statement:
INSERT INTO example_table (column_A, column_B) VALUES(?, ?), VALUES(?, ?), VALUES(?, ?);
values on bind_param:
('ssssss', 'a', 'b', 'a', 'c', 'a', 'd')
As you can see the repetition of 'a'. is there a way to store 'a' and default it to column_A for the current insert only?
example of what i would like to do on bind_param:
('ssss', 'a', 'b', 'c', 'd')
Where 'a' above is used for column_A on all rows inserted (3 rows in the example). Any help would be appreciated
No, it's not possible to "alias" a value multiple times. Each placeholder is unique and must be bound to exactly one value. (It is not even possible to do this reliably with named parameters in PDO.)
If automatically building SQL dynamically (with placeholders) and associated data array, then there is no issue with such "duplication" as it's already handled by the generator.
If transactions are correctly used - which they should be anyway! - then simply calling INSERT in a loop, once for each pair, will likely have similar performance. This avoids needing to build the dynamic SQL (with placeholders) itself, but can increase latency as each command needs to round-trip to the SQL server.
If finding a bunch of such repetition, it might be time to use a Data Access Layer to hind such details; write it, test it, move onto something interesting.
In response to the comment about using SQL variables:
While the following will not improve performance, excepting possibly for ridiculously large values of #v, and makes the code more difficult to understand - it ought to be possible to use user-defined variables in a single insert statement. For instance, consider:
INSERT INTO t VALUES (#v := ?, ?), (#v, ?), (#v, ?)
This is "valid" in MySQL (and is also MySQL-specific), where the placeholders are valid expressions; if it works will depend on how/if such a binding is allowed in a prepared statement.
You may try making a temporary table:
$query='CREATE TEMPORARY TABLE tempTable(column_B VARCHAR(50));';
$mysqli->query($query);
then insert unique values of column_B into this table
and finally
$query="INSERT INTO example_table (column_A, column_B) select $a , column_B from tempTable";
$mysqli->query($query);
I recently started hosting my own site and mySQL db. Everything works fine, but whenever I do an insert or update to any of tables, it errors out if I do not call out each and every column. Is there a setting for the table or the DB that controls this? I never had to do this with my previous DB host.
Thanks.
There are several ways to write an INSERT query.
INSERT INTO tablename (col1, col2, ...) VALUES (val1, val2, ...)
INSERT INTO tablename (col1, col2, ...) SELECT ...
INSERT INTO tablename VALUES (val1, val2, ...)
INSERT INTO tablename SELECT ...
In the first two methods, you don't have to list all the columns, since you specify the columns to be filled in explicitly. The columns that aren't in the (col1, col2, ...) list will get their default values. The VALUES list or the SELECT query must return as many columns as you specified in the list.
In methods 3 and 4, MySQL requires the VALUES list or the SELECT query to return as many columns as the table contains, and they must be in the same order as the table definition. I can't find any setting that disables the column count check in these methods.
In methods 1 and 3, you can put the keyword DEFAULT in place of any of the column values to insert its default value.
If your server is in STRICT mode, you also have to explicitly set any columns that do not have a DEFAULT option in the schema. If it's not in strict mode, automatic defaults will be used.
It probably doesn't fail if you UPDATE the values of some, but not all, columns in particular rows.
When you create your table, you need to set a default value for each column which you may choose to omit in your INSERT statements.
The below sql query i require to run an update instead of an insert due to duplicates.
Insert into test_reports (Table_Name, Total_Count) SELECT "West Midlands", COUNT(1) FROM table1 where location = 'West Midlands'
Thanks
A good way to deal with this problem is to differentiate between when there's no previous record and when there is a previous record. For that, you can use the ON DUPLICATE KEY phrase of an INSERT:
INSERT INTO **INSERT-PHRASE** ON DUPLICATE KEY **UPDATE-PHRASE**
Use REPLACE INTO instead.
More here: http://dev.mysql.com/doc/refman/5.0/en/replace.html
Note though that it deletes before it inserts, so any fields not in the query will be set to their defaults. If you do not want that behaviour, use UPDATE.
I there a way to update a row without mentioning fields name ?
I mean something like:
UPDATE table SET VALUES(1, 'name', 'family')
instead of:
UPDATE table SET id=1, name='name', family='family'
update
I'm using INSERT ON DUPLICATE KEY UPDATE and don't want to use REPLACE function because REPLACE function will cause a record to be removed, and inserted at the end, which will cause the indexing to get broken apart, decreasing the efficiency of the table.
If you specify the values in the same order as the table definition you could use
REPLACE INTO table VALUES(1, 'name', 'family');
Note that this will replace the entire row, so you must specify all the values you need!
You cannot do like that with mysql, as set clause indicates which columns to modify and the values they should be given
FYI: http://dev.mysql.com/doc/refman/5.0/en/update.html