LESSON 8 OF 14

Inserting, Updating, and Deleting Data with T-SQL

This lesson explains how to perform safe and controlled data modifications in SQL Server using INSERT, UPDATE, and DELETE, including bulk inserts, conditional updates, deletions, and transactions.

45 dk 86

Introduction

A database is not merely a passive structure containing tables and relationships. Applications must insert new information, update existing records, and remove records that are no longer needed. In T-SQL, these operations are primarily performed with the INSERT, UPDATE, and DELETE statements.

In this lesson, you will perform data modification operations in a controlled way on SQL Server. The examples use a table named dbo.Ogrenciler in the EgitimDB database. The goal is not only to learn statement syntax, but also to avoid common mistakes such as updating the wrong rows or accidentally deleting an entire table.

1. The role of data modification statements

T-SQL data modification statements are commonly considered part of DML, or Data Manipulation Language. The three fundamental statements have the following purposes:

  • INSERT: Adds one or more rows to a table.
  • UPDATE: Changes one or more column values in existing rows.
  • DELETE: Removes rows that satisfy a specified condition.

These statements do not change the table definition. Structural operations such as creating a table or adding a column use DDL statements such as CREATE TABLE and ALTER TABLE. Data modification statements are used after the table structure has been prepared.

2. Preparing the example environment

The following script selects the database and creates the example table. If you already created the table in an earlier lesson, do not run this section again. The script is written so that the table is created only when it does not already exist.

USE EgitimDB;
GO

IF OBJECT_ID(N'dbo.Ogrenciler', N'U') IS NULL
BEGIN
    CREATE TABLE dbo.Ogrenciler
    (
        OgrenciID INT IDENTITY(1,1) PRIMARY KEY,
        AdSoyad NVARCHAR(100) NOT NULL,
        Eposta NVARCHAR(150) NOT NULL UNIQUE,
        Sehir NVARCHAR(50) NULL,
        KayitTarihi DATE NOT NULL DEFAULT CONVERT(date, GETDATE()),
        AktifMi BIT NOT NULL DEFAULT 1
    );
END;
GO

The IDENTITY property allows SQL Server to generate OgrenciID values automatically. Therefore, a normal insert does not need to provide a value for this column. Values must be supplied for columns defined as NOT NULL. If a column has a DEFAULT definition and no value is supplied, SQL Server uses the default value.

3. Inserting data with INSERT

3.1. Inserting a single row

The safest approach is to specify the columns being populated explicitly. A column list prevents problems when a column is added to the table or when the physical column order changes.

INSERT INTO dbo.Ogrenciler
    (AdSoyad, Eposta, Sehir)
VALUES
    (N'Ayşe Demir', N'ayse.demir@example.com', N'Ankara');

The N prefix is used with text literals so that Unicode characters are stored correctly. Since no values are supplied for KayitTarihi and AktifMi, their default values are applied.

You can use the OUTPUT clause to display the identity of the inserted row:

INSERT INTO dbo.Ogrenciler
    (AdSoyad, Eposta, Sehir)
OUTPUT INSERTED.OgrenciID, INSERTED.AdSoyad
VALUES
    (N'Mehmet Kaya', N'mehmet.kaya@example.com', N'İzmir');

INSERTED provides access to values from the row produced by the insert operation. This is especially useful when application code needs to retrieve the newly generated identity value.

3.2. Inserting multiple rows

Several rows can be inserted with a single INSERT statement. This is practical for small or medium-sized sets of initial data with the same structure.

INSERT INTO dbo.Ogrenciler
    (AdSoyad, Eposta, Sehir)
VALUES
    (N'Elif Yılmaz', N'elif.yilmaz@example.com', N'Bursa'),
    (N'Can Arslan', N'can.arslan@example.com', N'İstanbul'),
    (N'Zeynep Çelik', N'zeynep.celik@example.com', N'Antalya');

The column order must be consistent for every row. Because the Eposta column has a UNIQUE constraint, attempting to insert an existing email address produces an error.

3.3. Inserting the result of a SELECT statement

Use the INSERT ... SELECT form to copy data from another table or query result. The following example transfers inactive students to an archive table.

IF OBJECT_ID(N'dbo.OgrenciArsivi', N'U') IS NULL
BEGIN
    CREATE TABLE dbo.OgrenciArsivi
    (
        ArsivID INT IDENTITY(1,1) PRIMARY KEY,
        OgrenciID INT NOT NULL,
        AdSoyad NVARCHAR(100) NOT NULL,
        ArsivTarihi DATETIME2 NOT NULL DEFAULT SYSDATETIME()
    );
END;
GO

INSERT INTO dbo.OgrenciArsivi (OgrenciID, AdSoyad)
SELECT OgrenciID, AdSoyad
FROM dbo.Ogrenciler
WHERE AktifMi = 0;

The number of columns and compatible data types returned by the source query must match the target column list. For larger data transfers, also check the number of affected rows and possible duplicate records.

4. Updating data with UPDATE

The UPDATE statement changes values in existing rows. Its basic form is as follows:

UPDATE dbo.Ogrenciler
SET Sehir = N'Konya'
WHERE OgrenciID = 2;

The WHERE condition limits the operation to the row whose ID is 2. Multiple columns can be changed in the same statement:

UPDATE dbo.Ogrenciler
SET Sehir = N'İstanbul',
    AktifMi = 1
WHERE Eposta = N'can.arslan@example.com';

4.1. Conditional updates

Comparison and logical conditions can be used to update rows according to business rules. The following example marks students in Ankara as inactive when their registration date is older than the specified date.

UPDATE dbo.Ogrenciler
SET AktifMi = 0
WHERE Sehir = N'Ankara'
  AND KayitTarihi < '2025-01-01';

Before running an update, test the same condition with a SELECT statement:

SELECT OgrenciID, AdSoyad, Sehir, KayitTarihi, AktifMi
FROM dbo.Ogrenciler
WHERE Sehir = N'Ankara'
  AND KayitTarihi < '2025-01-01';

This check helps prevent more rows from changing than expected. You can use @@ROWCOUNT to see how many rows were affected.

UPDATE dbo.Ogrenciler
SET AktifMi = 0
WHERE Sehir = N'Ankara';

SELECT @@ROWCOUNT AS UpdatedRowCount;

5. Deleting records with DELETE

The DELETE statement removes rows from a table. Use a primary key or another sufficiently specific condition when deleting a single record.

DELETE FROM dbo.Ogrenciler
WHERE OgrenciID = 5;

Multiple records can also be deleted:

DELETE FROM dbo.Ogrenciler
WHERE AktifMi = 0
  AND KayitTarihi < '2024-01-01';

Important warning: A DELETE statement without a WHERE clause removes every row in the table.

-- Warning: removes all records.
DELETE FROM dbo.Ogrenciler;

For this reason, verify the condition with a SELECT statement before deleting. In some situations, TRUNCATE TABLE may be more appropriate for removing all rows; however, the two commands differ in their restrictions, foreign key behavior, permissions, and transaction characteristics.

6. Protecting changes with a transaction

Use a transaction when several data modification statements must succeed or fail as one unit. For example, if you want to archive a student and then delete the original row, allowing only one of those operations to succeed could create inconsistent data.

SET XACT_ABORT ON;

BEGIN TRY
    BEGIN TRANSACTION;

    INSERT INTO dbo.OgrenciArsivi (OgrenciID, AdSoyad)
    SELECT OgrenciID, AdSoyad
    FROM dbo.Ogrenciler
    WHERE OgrenciID = 5;

    DELETE FROM dbo.Ogrenciler
    WHERE OgrenciID = 5;

    COMMIT TRANSACTION;
END TRY
BEGIN CATCH
    IF XACT_STATE() <> 0
        ROLLBACK TRANSACTION;

    SELECT ERROR_NUMBER() AS ErrorNumber,
           ERROR_MESSAGE() AS ErrorMessage;
END CATCH;

BEGIN TRANSACTION starts the transaction, COMMIT makes the changes permanent, and ROLLBACK undoes them. TRY...CATCH provides error handling. SET XACT_ABORT ON helps ensure that a transaction is safely terminated when a run-time error occurs.

7. Common mistakes

  • Omitting WHERE: An UPDATE or DELETE may affect every row in the table.
  • Providing an unnecessary identity value: An IDENTITY column should normally be omitted during inserts.
  • Omitting the column list: Changes to the table structure can break the insert statement or place values in unintended columns.
  • Ignoring unique constraints: Reusing a unique value such as an email address causes an error.
  • Skipping a pre-operation check: Run a SELECT with the same condition and inspect the target rows first.
  • Leaving a transaction open: An uncommitted transaction in SSMS can cause locks and waiting sessions.

8. Short practice exercise

Complete the following tasks in the EgitimDB database:

  1. Insert three new students using different email addresses.
  2. Set AktifMi to 1 for students whose city is İstanbul.
  3. Change the city of one student and inspect the target row with SELECT before updating it.
  4. Delete inactive students registered before 2023 inside a transaction.
  5. Verify the result using SELECT COUNT(*) and @@ROWCOUNT.

Conclusion

In this lesson, you learned the essential techniques for inserting, updating, and deleting data with T-SQL. Explicit column lists, testing conditions with SELECT, monitoring affected row counts, and grouping related changes inside a transaction are fundamental habits for safe database work.

In the next stage, you can examine these records in greater detail using SELECT queries, filtering, and sorting. Correctly identifying the target rows in every data modification statement is just as important as knowing the syntax.

Official resources

Sources