INSERT, UPDATE, DELETE ✏️
Add, Modify, and Remove Data - Zero to Hero
Master INSERT, UPDATE, DELETE in 2 Steps! 🎯
PART 1: Learn INSERT, UPDATE, DELETE in SSMS (SQL Server Management Studio)
PART 2: Use INSERT, UPDATE, DELETE in C# (Visual Studio)
- ✅ INSERT - Add new data to your database
- ✅ UPDATE - Modify existing data
- ✅ DELETE - Remove data you no longer need
- ✅ Together they form CRUD (Create, Read, Update, Delete)
PART 1 - SQL Server Management Studio (SSMS)
Learn INSERT, UPDATE, DELETE in SSMS First!
SSMS Step 1: Create Our Sample Database
-- ===== CREATE DATABASE =====
CREATE DATABASE StoreDB;
GO
USE StoreDB;
GO
-- ===== CREATE PRODUCTS TABLE =====
CREATE TABLE Products (
ProductId INT IDENTITY(1,1) PRIMARY KEY,
Name NVARCHAR(100) NOT NULL,
Price DECIMAL(10,2) NOT NULL,
Quantity INT NOT NULL,
Category NVARCHAR(50)
);
GO
-- ===== INSERT SAMPLE PRODUCTS =====
INSERT INTO Products (Name, Price, Quantity, Category)
VALUES
('Laptop', 999.99, 10, 'Electronics'),
('Mouse', 25.50, 50, 'Electronics'),
('Keyboard', 45.00, 30, 'Electronics'),
('Monitor', 299.99, 15, 'Electronics'),
('Desk', 199.99, 5, 'Furniture'),
('Chair', 149.99, 8, 'Furniture');
GO
SSMS Step 2: INSERT - Adding New Data
💻 INSERT - Add One Product
Add a single new product:
-- Insert one product
INSERT INTO Products (Name, Price, Quantity, Category)
VALUES
('Headphones', 89.99, 20, 'Electronics');
✅ New product added!
📌 Important: Don't include ProductId - it auto-increments!
💻 INSERT - Add Multiple Products
Add multiple products at once:
-- Insert multiple products
INSERT INTO Products (Name, Price, Quantity, Category)
VALUES
('Webcam', 59.99, 15, 'Electronics'),
('Desk Lamp', 35.00, 25, 'Furniture'),
('Coffee Mug', 12.99, 100, 'Kitchen');
✅ 3 new products added at once!
💻 INSERT - With SELECT (Copy Data)
Copy data from another table:
-- Insert from another table
INSERT INTO Products (Name, Price, Quantity, Category)
SELECT ProductName, Price, Stock, 'New'
FROM TempProducts
WHERE Price > 50;
✅ Copies only expensive products to the main table!
SSMS Step 3: UPDATE - Modifying Existing Data
💻 UPDATE - Change Price
Update a specific product's price:
-- Update price of Laptop
UPDATE Products
SET Price = 899.99
WHERE Name = 'Laptop';
✅ Laptop price updated!
⚠️ Always use WHERE! Without it, ALL prices change!
💻 UPDATE - Multiple Columns
Update multiple fields at once:
-- Update both price and quantity
UPDATE Products
SET
Price = 27.99,
Quantity = 60
WHERE Name = 'Mouse';
✅ Both price and quantity updated!
💻 UPDATE - With Calculations
Update using calculations:
-- Increase all prices by 10%
UPDATE Products
SET Price = Price * 1.10
WHERE Category = 'Electronics';
✅ All electronics prices increased by 10%!
💻 UPDATE - With WHERE Conditions
Update with multiple conditions:
-- Update products with low stock
UPDATE Products
SET Quantity = 20
WHERE Quantity < 10
AND Category = 'Electronics';
✅ Low-stock electronics restocked!
SELECT first to see what you'll update!
SELECT * FROM Products WHERE Name = 'Laptop';
Then run UPDATE with the same WHERE clause!
SSMS Step 4: DELETE - Removing Data
💻 DELETE - Remove One Product
Delete a specific product:
-- Delete a specific product
DELETE FROM Products
WHERE Name = 'Desk Lamp';
✅ Desk Lamp removed!
⚠️ Always use WHERE! Without it, ALL rows are deleted!
💻 DELETE - With Conditions
Delete products with specific criteria:
-- Delete products with no stock
DELETE FROM Products
WHERE Quantity = 0
AND Category = 'Electronics';
✅ All out-of-stock electronics removed!
💻 Safe Practice - SELECT First!
Always test with SELECT before DELETE:
-- 1️⃣ First, see what will be deleted
SELECT * FROM Products
WHERE Category = 'Furniture'
AND Quantity < 5;
-- 2️⃣ If correct, run DELETE
DELETE FROM Products
WHERE Category = 'Furniture'
AND Quantity < 5;
✅ Safe! You know exactly what will be deleted!
Always SELECT first, then DELETE!
PART 2 - Using INSERT, UPDATE, DELETE in C#
Now Let's Use These Commands in C#!
C# Step 1: Create Your WinForms Project
📁 Create Project
- Open Visual Studio
- Create Windows Forms App
- Name it "ProductManager"
💻 Add NuGet Package
- Install Microsoft.Data.SqlClient
- Add using statements
- Add connection string
using System.Data;
using Microsoft.Data.SqlClient;
private string connString =
"Server=localhost;Database=StoreDB;Trusted_Connection=True;TrustServerCertificate=True;";
C# Step 2: INSERT in C#
// ===== INSERT - Add a New Product =====
private void btnAdd_Click(object sender, EventArgs e)
{
// 1️⃣ Get user input
string name = txtName.Text;
decimal price = decimal.Parse(txtPrice.Text);
int quantity = int.Parse(txtQuantity.Text);
string category = txtCategory.Text;
// 2️⃣ The INSERT query
string query = "INSERT INTO Products (Name, Price, Quantity, Category) " +
"VALUES (@Name, @Price, @Quantity, @Category)";
// 3️⃣ Run the query
using (var conn = new SqlConnection(connString))
using (var cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@Price", price);
cmd.Parameters.AddWithValue("@Quantity", quantity);
cmd.Parameters.AddWithValue("@Category", category);
conn.Open();
int rows = cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show($"✅ {rows} product added!");
LoadProducts(); // Refresh the list
}
}
C# Step 3: UPDATE in C#
// ===== UPDATE - Modify a Product =====
private void btnUpdate_Click(object sender, EventArgs e)
{
// 1️⃣ Get the product ID and new values
int id = (int)dgvProducts.CurrentRow.Cells["ProductId"].Value;
string name = txtName.Text;
decimal price = decimal.Parse(txtPrice.Text);
int quantity = int.Parse(txtQuantity.Text);
string category = txtCategory.Text;
// 2️⃣ The UPDATE query
string query = "UPDATE Products SET Name=@Name, Price=@Price, " +
"Quantity=@Quantity, Category=@Category WHERE ProductId=@Id";
// 3️⃣ Run the query
using (var conn = new SqlConnection(connString))
using (var cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@Price", price);
cmd.Parameters.AddWithValue("@Quantity", quantity);
cmd.Parameters.AddWithValue("@Category", category);
cmd.Parameters.AddWithValue("@Id", id);
conn.Open();
int rows = cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show($"✅ {rows} product updated!");
LoadProducts(); // Refresh the list
}
}
C# Step 4: DELETE in C#
// ===== DELETE - Remove a Product =====
private void btnDelete_Click(object sender, EventArgs e)
{
// 1️⃣ Confirm with user
DialogResult result = MessageBox.Show(
"Delete this product?",
"Confirm Delete",
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning);
if (result != DialogResult.Yes) return;
// 2️⃣ Get the product ID
int id = (int)dgvProducts.CurrentRow.Cells["ProductId"].Value;
// 3️⃣ The DELETE query
string query = "DELETE FROM Products WHERE ProductId = @Id";
// 4️⃣ Run the query
using (var conn = new SqlConnection(connString))
using (var cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("@Id", id);
conn.Open();
int rows = cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show($"✅ {rows} product deleted!");
LoadProducts(); // Refresh the list
}
}
C# Step 5: Complete CRUD Application
// ===== COMPLETE PRODUCT MANAGEMENT SYSTEM =====
public partial class ProductForm : Form
{
private string connString = "Server=localhost;Database=StoreDB;Trusted_Connection=True;TrustServerCertificate=True;";
public ProductForm()
{
InitializeComponent();
LoadProducts();
ClearFields();
}
// ===== READ - Load All Products =====
private void LoadProducts()
{
string query = "SELECT ProductId, Name, Price, Quantity, Category FROM Products";
using (var conn = new SqlConnection(connString))
using (var adapter = new SqlDataAdapter(query, conn))
{
DataTable dt = new DataTable();
adapter.Fill(dt);
dgvProducts.DataSource = dt;
lblStatus.Text = $"📊 {dt.Rows.Count} products loaded";
}
}
// ===== CREATE - INSERT =====
private void btnAdd_Click(object sender, EventArgs e)
{
if (!ValidateFields()) return;
string query = "INSERT INTO Products (Name, Price, Quantity, Category) " +
"VALUES (@Name, @Price, @Quantity, @Category)";
using (var conn = new SqlConnection(connString))
using (var cmd = new SqlCommand(query, conn))
{
AddParameters(cmd);
conn.Open();
int rows = cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show($"✅ Added {rows} product!");
LoadProducts();
ClearFields();
}
}
// ===== UPDATE - UPDATE =====
private void btnUpdate_Click(object sender, EventArgs e)
{
if (!ValidateFields()) return;
int id = (int)dgvProducts.CurrentRow.Cells["ProductId"].Value;
string query = "UPDATE Products SET Name=@Name, Price=@Price, " +
"Quantity=@Quantity, Category=@Category WHERE ProductId=@Id";
using (var conn = new SqlConnection(connString))
using (var cmd = new SqlCommand(query, conn))
{
AddParameters(cmd);
cmd.Parameters.AddWithValue("@Id", id);
conn.Open();
int rows = cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show($"✅ Updated {rows} product!");
LoadProducts();
ClearFields();
}
}
// ===== DELETE - DELETE =====
private void btnDelete_Click(object sender, EventArgs e)
{
if (dgvProducts.CurrentRow == null) return;
DialogResult result = MessageBox.Show(
"Delete this product?", "Confirm",
MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.No) return;
int id = (int)dgvProducts.CurrentRow.Cells["ProductId"].Value;
string query = "DELETE FROM Products WHERE ProductId = @Id";
using (var conn = new SqlConnection(connString))
using (var cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("@Id", id);
conn.Open();
int rows = cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show($"✅ Deleted {rows} product!");
LoadProducts();
ClearFields();
}
}
// ===== HELPERS =====
private void AddParameters(SqlCommand cmd)
{
cmd.Parameters.AddWithValue("@Name", txtName.Text);
cmd.Parameters.AddWithValue("@Price", decimal.Parse(txtPrice.Text));
cmd.Parameters.AddWithValue("@Quantity", int.Parse(txtQuantity.Text));
cmd.Parameters.AddWithValue("@Category", txtCategory.Text);
}
private bool ValidateFields()
{
if (string.IsNullOrWhiteSpace(txtName.Text))
{
MessageBox.Show("Please enter a name!");
return false;
}
if (!decimal.TryParse(txtPrice.Text, out decimal _))
{
MessageBox.Show("Please enter a valid price!");
return false;
}
if (!int.TryParse(txtQuantity.Text, out int _))
{
MessageBox.Show("Please enter a valid quantity!");
return false;
}
return true;
}
private void ClearFields()
{
txtName.Clear();
txtPrice.Clear();
txtQuantity.Clear();
txtCategory.Clear();
}
// ===== SELECT ROW =====
private void dgvProducts_SelectionChanged(object sender, EventArgs e)
{
if (dgvProducts.CurrentRow == null) return;
txtName.Text = dgvProducts.CurrentRow.Cells["Name"].Value?.ToString();
txtPrice.Text = dgvProducts.CurrentRow.Cells["Price"].Value?.ToString();
txtQuantity.Text = dgvProducts.CurrentRow.Cells["Quantity"].Value?.ToString();
txtCategory.Text = dgvProducts.CurrentRow.Cells["Category"].Value?.ToString();
}
}
Exercises: Test Your Skills!
1 Easy: INSERT a Product
Challenge: Write C# code to add a new product called "Tablet" with price 399.99, quantity 12, and category "Electronics".
// SOLUTION (3 lines)
string query = "INSERT INTO Products (Name, Price, Quantity, Category) VALUES (@Name, @Price, @Quantity, @Category)";
ExecuteQuery(query, new string[] { "@Name", "@Price", "@Quantity", "@Category" },
new object[] { "Tablet", 399.99, 12, "Electronics" });
MessageBox.Show("Product added!");
2 Medium: UPDATE Products
Challenge: Write C# code to increase the price of all Electronics products by 15%.
// SOLUTION (3 lines)
string query = "UPDATE Products SET Price = Price * 1.15 WHERE Category = @Category";
ExecuteQuery(query, new string[] { "@Category" }, new object[] { "Electronics" });
MessageBox.Show("Prices updated!");
3 Hard: Complete Product Management
Challenge: Build a WinForms app with:
- Add Product (INSERT)
- Update Product (UPDATE)
- Delete Product (DELETE)
- Search by Category (SELECT + WHERE)
- Sort by Price (ORDER BY)
// ===== COMPLETE SOLUTION =====
private void btnSearch_Click(object sender, EventArgs e)
{
string query = "SELECT * FROM Products " +
"WHERE Category LIKE @Category " +
"ORDER BY Price " + (chkAsc.Checked ? "ASC" : "DESC");
using (var conn = new SqlConnection(connString))
using (var cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("@Category", $"%{txtSearch.Text}%");
using (var adapter = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
adapter.Fill(dt);
dgvProducts.DataSource = dt;
lblStatus.Text = $"🔍 Found {dt.Rows.Count} products";
}
}
}
🎉 Mastery Summary
INSERT INTO Table VALUES (...)
UPDATE Table SET Column = Value WHERE ...
DELETE FROM Table WHERE ...
Write SQL directly
Learn the commandsExecuteNonQuery()
Create, Read, Update, Delete
Complete application!🎯 You're now a master of INSERT, UPDATE, and DELETE in SQL Server and C#!