Skip to main content

Posts

Showing posts with the label insert query

INSERT with LAST_INSERT_ID

The MySQL-specific option LAST_INSERT_ID(expr) can be used after an INSERT to   after the insert takes place; mysql> INSERT INTO City (name, countrycode) -> VALUES ('Sarah City', 'USA'); Query OK, 1 row affected (#.## sec) mysql> SELECT LAST_INSERT_ID(); +---------------------------+ | LAST_INSERT_ID() | +----------------------------+ | 4080                            | +-----------------------------+ If a table contains an AUTO_INCREMENT column and INSERT ... UPDATE inserts a row, the LAST_INSERT_ID() function returns the AUTO_INCREMENT value. If the statement updates a row  instead, LAST_INSERT_ID() is not meaningful. However, LAST_INSERT_ID(expr) can be used  to worked around this.

The INSERT Statement

Now that tables have been created, the next step is to populate them with data. Although there are a variety  of ways to get data into MySQL tables, the INSERT statement is the most common method for getting data  into a table. The INSERT statement uses the following general syntax; INSERT INTO table_name (column_list) VALUES(value_list); An insert can include a only the value(s) without a column list (if the exact column order, quantity and types  are known), as follows; INSERT INTO numbers VALUES(250); Row contents will be as follows; +------+ | n         | +------+ | 250    | +------+ To add multiple column data into a table (containing an inventory of used books) on a First Edition copy of  the book A Tale of Two Cities by Charles Dickens, the following would be used; I NSERT INTO used_books (author, title, edition) VALUES  ('Charles Dickens', 'A Tale of Two Cities', 'First Edition'); Row contents will be as follows; +----