Inserting Data
Learn to insert data in databases.
We'll cover the following...
Imagine we are managing an online store and have just set up our database structure with tables for products, customers, and orders. The next crucial step is populating these tables with data so that our application can function effectively. Think of this step as stocking the shelves of a store. Without products being added to the inventory, customers wouldn't have anything to buy. In the same way, databases need data to function and be useful.
Let's explore the essential process of inserting data into a SQL database. We'll learn how to:
Use the
INSERT INTOstatement to add single and multiple rows of data.Use
AUTO_INCREMENTand understand its concept.
Using the INSERT INTO Statement
In SQL, we can insert data in our database tables using the INSERT INTO statement. Let's explore a couple of ways to insert data into tables.
Inserting a single record
If we need only a single record to be added into our tables, we can the INSERT INTO statement with the following syntax:
INSERT INTO TableName (Column1, Column2, ...)VALUES (Value1, Value2, ...);
In the SQL statement above:
TableNameis used to specify the name of the table we are inserting data into.Column1andColumn2are the table columns to be populated.Value1andValue2are the values for the defined columns.
For example, if we have to add a new product to the Products table in our OnlineStore database, we can use:
INSERT INTO Products (ProductID, ProductName, CategoryID, Price, Stock)VALUES (1, 'Smartphone', 1, 635.79, 50);
In the code above, we’re ...