In this tutorial we will learn Insert Into A MySQL Table Or Update If Exists there is a command to insert the data in a table that is insert into table and to update the table we use update command to update it.
Insert A New Record In to Table
Insert is a command which is used for inserting a new record in an existing table where we know the dimensions of and all the coloumn and the enter the data as per the data type described while creating the table.
To insert a new record in table follow the code given below and enter a new record in table.
INSERT INTO users (id, username, email) VALUES (1, "Prakhar", "radheradhe @syammilade.aaj")
where the name of table is users and we enterthe data of Id and name and username.
There is another way to enter the data or adding a new record in table by following way.
INSERT INTO users VALUES (1, "Prakhar", "radheradhe @syammilade.aaj")
Where we do not required to put the name of columns in the insert commant provided we enter the values (Data) in same order as we created the columns. otherwise it will show error.
Update The Record If Already exist.
There is a way by which we can update if there is already a record with same username exist in that case it is going to simply update the table instet of creating a new record.
To understand and get the code done follow the code given below with some changes .
INSERT INTO users (id, username, email) VALUES (1, "johndoe", "email@example.com") ON DUPLICATE KEY UPDATE email = VALUES(email);
Here the record will be added only when the email is not exist already in the table as we applied duplicate key update so it is going to update the record if already exist that was what we required exectly.
To learn More about it insert a new record or update if exist.
Also visit MySQL Problems And Tutorials to learn more about MySQL and keep leaning.