Jump to content

Recommended Posts

if i have autoincrement column like for example:

 

I have 3 columns : ID (auto increment), Name, city

Then if i want to insert some records, can i use

 

INSERT INTO TABLE1 VALUES('James','Japan') which mean ignoring the ID or i still have to create this INSERT INTO TABLE1 (Name,City)VALUES('James','Japan')

 

thanks

Link to comment
https://forums.phpfreaks.com/topic/199913-mysql-basic-question/
Share on other sites

In SQL if you do not name the columns in an INSERT statement, the data is applied to the columns in the order they are defined in the table.  So you first example INSERT INTO TABLE1 VALUES('James','Japan') would try to put 'James" into the ID column and 'Japan' into the Name column.  Of course this will fail because the ID column is an integer and 'James' is not.

 

So, yes, you would have to name the columns as in your second example: INSERT INTO TABLE1 (Name,City)VALUES('James','Japan') (by the way, you need a space before the VALUES clause).

 

As an alternative, you could order the columns in the table putting ID last, and then not have to name the columns in the INSERT (your first example would work).  Since there are only two values being inserted, the third (and any remaining columns) would be ignored and receive their default value.  I am not advocating this table layout.  I have never seen it done and it does not "feel" right to do it this way. But in theory it should work.

 

I recommend ALWAYS naming the columns in the INSERT statement so when you are reading the code you can see exactly what is happening without having to refer to the table layout when you (or someone else) has to modify the code later.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.