Insert Data into a MySQL Database Table
Insert Data into a MySQL Database Table
We can use the INSERT statement to insert data into the MySQL database table. Steps to create a table can be found here:
INSERT Statement Syntax
https://www.testingdocs.com/mysql-insert-statement/
Populate Data
To insert a single row into the table, we can run the INSERT statement.
Example
In this example, we will insert a row into the supplier table. String values are enclosed with ‘ ‘ characters. We can execute the statement at the MySQL prompt, SQL Editor in MySQL workbench, etc.
mysql> INSERT INTO supplier VALUES(10,’FooSupplier’);
Statements
mysql> DESC supplier;
+—————+————-+——+—–+———+——-+
| Field | Type | Null | Key | Default | Extra |
+—————+————-+——+—–+———+——-+
| supplier_id | int | NO | PRI | NULL | |
| supplier_name | varchar(40) | NO | | NULL | |
+—————+————-+——+—–+———+——-+
2 rows in set (0.20 sec)
mysql> INSERT INTO supplier VALUES(10,’FooSupplier’);
Query OK, 1 row affected (0.41 sec)
mysql> SELECT * FROM supplier;
+————-+—————+
| supplier_id | supplier_name |
+————-+—————+
| 10 | FooSupplier |
+————-+—————+
1 row in set (0.00 sec)
mysql>
supplier_id is the PRIMARY KEY for the table. This column value should be unique and should not contain duplicate values. When running multiple INSERT statements we have to make sure that this CONSTRAINT is met. So, another INSERT statement with the same supplier_id 10 would throw an error. For example, the below statement would run without violating the constraint.
INSERT INTO supplier VALUES(20,’AnotherUniqueSupplier’);
We can also run multiple INSERT statements to populate the table with multiple rows. For Example, MYSQL script files can contain multiple INSERT statements in a *.sql script file.
That’s it. We have successfully populated the table with sample data.
MySQL Tutorials
MySQL Tutorials on this website:
https://www.testingdocs.com/mysql-tutorials-for-beginners/
For more information on MySQL Database: