How do I delete data safely from a SQL table?

Removing data from a database sounds simple, but a single missing clause can wipe out an entire table. In this tutorial, you will learn how to use the SQL DELETE statement safely: how to target the exact rows you want to remove, how to verify your target before deleting, and how to use transactions to recover from mistakes.

By the end, you will be able to confidently delete rows without risking accidental data loss.

Prerequisites

To follow along, you should:

  • Have a working SQL database (PostgreSQL, MySQL, MariaDB, SQL Server, Oracle, or SQLite).
  • Know how to run SQL statements in a client such as psql, MySQL Workbench, DBeaver, or the command line.
  • Be familiar with SELECT and WHERE from earlier tutorials.

If you are new to SQL, start with How do I retrieve data using a SELECT statement? and How do I filter SQL query results using WHERE?

Sample Database

We will use an online bookstore as our sample domain. Create a customers table and insert a few rows so you can practice deletions safely.

CREATE TABLE customers (
    customer_id   INTEGER PRIMARY KEY,
    customer_name VARCHAR(100) NOT NULL,
    email         VARCHAR(150) NOT NULL,
    status        VARCHAR(20)  NOT NULL,
    created_at    DATE         NOT NULL
);

INSERT INTO customers (customer_id, customer_name, email, status, created_at) VALUES
    (1, 'Alice Johnson',   '[email protected]',   'active',   '2024-01-15'),
    (2, 'Bob Smith',       '[email protected]',     'inactive', '2023-06-20'),
    (3, 'Carol Davis',     '[email protected]',   'active',   '2024-03-10'),
    (4, 'David Miller',    '[email protected]',   'inactive', '2022-11-05'),
    (5, 'Eva Thompson',    '[email protected]',     'active',   '2025-02-28');

This gives us five customers with a mix of active and inactive statuses.

Warning: Run every example in this tutorial in a disposable learning database, never in production.

Basic Syntax

The general form of a DELETE statement is:

DELETE FROM table_name
WHERE condition;

Key points:

  • DELETE FROM table_name names the table you want to remove rows from.
  • WHERE condition decides which rows are removed.
  • Without a WHERE clause, every row in the table is deleted.

DELETE removes rows but keeps the table structure (columns, indexes, constraints) intact.

Step 1: Verify the Target Rows First

Before running any DELETE, always run a SELECT with the same WHERE clause. This is the single most important habit to prevent data loss.

Suppose we want to remove the customer with customer_id = 4. First, check exactly which rows match:

SELECT customer_id, customer_name, email, status
FROM customers
WHERE customer_id = 4;

Expected Result

customer_id customer_name email status
4 David Miller [email protected] inactive

The result shows exactly one row, which is what we expect. Now the DELETE is safe to run.

Step 2: Perform the Delete

Reuse the same WHERE clause you just verified:

DELETE FROM customers
WHERE customer_id = 4;

The database will report the number of rows affected (for example, 1 row deleted). Confirm the row is gone:

SELECT customer_id, customer_name
FROM customers
ORDER BY customer_id;

Expected Result

customer_id customer_name
1 Alice Johnson
2 Bob Smith
3 Carol Davis
5 Eva Thompson

Additional Examples

Deleting Multiple Rows with a Condition

Remove all customers whose status is inactive:

SELECT customer_id, customer_name, status
FROM customers
WHERE status = 'inactive';

If the result matches the rows you intend to delete, run:

DELETE FROM customers
WHERE status = 'inactive';

Deleting Rows That Match a Date Condition

Remove customers created before 2024:

DELETE FROM customers
WHERE created_at < DATE '2024-01-01';

Handling NULL in Delete Conditions

If a column allows NULL, remember that NULL is not a value you can compare with =. To delete rows where email is missing:

DELETE FROM customers
WHERE email IS NULL;

Never write WHERE email = NULL. That condition is never true, so no rows are deleted, and you might incorrectly assume the table has no such rows.

Using a Transaction to Stay Safe

A transaction lets you delete rows and then decide whether to keep the change (COMMIT) or undo it (ROLLBACK).

BEGIN;

DELETE FROM customers
WHERE status = 'inactive';

-- Inspect the effect before committing
SELECT customer_id, customer_name, status
FROM customers;

-- If something looks wrong:
ROLLBACK;

-- If everything looks correct:
-- COMMIT;

Explanation:

  1. BEGIN starts a transaction.
  2. The DELETE removes matching rows, but the change is not yet permanent.
  3. You verify the result with a SELECT.
  4. ROLLBACK reverts the deletion. COMMIT makes it permanent.

Transaction behavior varies between database systems and storage engines. In MySQL, for example, the underlying engine must be transactional (InnoDB) for ROLLBACK to work.

Using Parameters from Application Code

When you delete from Java, always use parameterized queries instead of string concatenation:

String sql = """
        DELETE FROM customers
        WHERE customer_id = ?
        """;

try (PreparedStatement statement = connection.prepareStatement(sql)) {
    statement.setLong(1, customerId);
    int rowsDeleted = statement.executeUpdate();
    System.out.println(rowsDeleted + " row(s) deleted.");
}

Parameters protect against SQL injection and correctly handle data types.

Common Mistakes

Forgetting the WHERE Clause

Incorrect:

DELETE FROM customers;

This removes every row in the customers table. Unless you truly intend that, always include a WHERE clause.

Comparing to NULL with =

Incorrect:

DELETE FROM customers
WHERE email = NULL;

Correct:

DELETE FROM customers
WHERE email IS NULL;

NULL represents missing information, so equality comparisons with NULL always return unknown, not true.

Confusing DELETE with TRUNCATE and DROP

  • DELETE removes rows and can be rolled back inside a transaction.
  • TRUNCATE removes all rows quickly but is usually non-transactional and may reset auto-increment counters.
  • DROP TABLE removes the entire table, including its structure.

Do not use TRUNCATE or DROP TABLE when you only want to remove selected rows.

Ignoring Foreign Key Constraints

If another table references the row you are deleting (for example, an orders table with a customer_id foreign key), the database may:

  • reject the delete;
  • cascade the delete to related rows (ON DELETE CASCADE);
  • set related columns to NULL (ON DELETE SET NULL).

Understand the constraints before deleting parent rows.

Database Compatibility

The basic DELETE ... WHERE ... syntax is standard SQL and works in:

  • PostgreSQL
  • MySQL
  • MariaDB
  • SQL Server
  • Oracle Database
  • SQLite

Differences to be aware of:

  • DELETE with JOIN: MySQL, MariaDB, and SQL Server support multi-table delete syntax. PostgreSQL uses DELETE ... USING. Oracle and SQLite require subqueries.
  • RETURNING clause: PostgreSQL and Oracle (RETURNING INTO) support returning deleted rows. MySQL and SQLite do not.
  • Auto-commit: Some clients auto-commit each statement. Explicitly use BEGIN / COMMIT when you need transactional safety.

When in doubt, consult the documentation for your database version.

Best Practices

  • Always run SELECT first with the same WHERE clause you plan to use in DELETE.
  • Never omit WHERE unless you deliberately want to empty the table.
  • Wrap risky deletes in a transaction so you can ROLLBACK on mistakes.
  • Back up important data before large or irreversible deletions.
  • Use parameterized queries in application code to avoid SQL injection.
  • Understand foreign keys and cascading rules before deleting parent rows.
  • Prefer a soft delete (for example, status = 'inactive' or a deleted_at timestamp) when you may need to recover the data later.
  • Use least-privilege accounts: application users should only have DELETE rights on tables where it is necessary.

Conclusion

You learned how to delete data safely from a SQL table by verifying the target rows with SELECT, applying DELETE with a precise WHERE clause, and using transactions to guard against mistakes. The most important rule is simple: never run a DELETE you have not first previewed with SELECT.

How do I send requests using different HTTP Methods with HttpClient?

Java 11 introduced the HttpClient API to simplify and modernize HTTP communications. This API supports sending requests using different HTTP methods (GET, POST, PUT, DELETE, etc.). Below is an explanation and example of how to perform these operations.

1. Setup

You will use the HttpClient and related classes from java.net.http package:

  • HttpClient – To execute HTTP requests.
  • HttpRequest – To construct and describe HTTP requests.
  • HttpResponse – To handle HTTP responses.

2. Example Code

Here’s how you can send HTTP requests with different methods using HttpClient in Java 11.

package org.kodejava.net.http;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse.BodyHandlers;

public class HttpClientMethodExample {
   public static void main(String[] args) {
      try {
         // Create an HttpClient instance
         HttpClient httpClient = HttpClient.newHttpClient();

         // Example: GET Request
         HttpRequest getRequest = HttpRequest.newBuilder()
                 .uri(new URI("https://jsonplaceholder.typicode.com/posts/1"))
                 .GET() // Default is GET, this is optional
                 .build();
         HttpResponse<String> getResponse = httpClient.send(getRequest, BodyHandlers.ofString());
         System.out.println("GET Response: " + getResponse.body());

         // Example: POST Request
         HttpRequest postRequest = HttpRequest.newBuilder()
                 .uri(new URI("https://jsonplaceholder.typicode.com/posts"))
                 .POST(BodyPublishers.ofString("{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}"))
                 .header("Content-Type", "application/json")
                 .build();
         HttpResponse<String> postResponse = httpClient.send(postRequest, BodyHandlers.ofString());
         System.out.println("POST Response: " + postResponse.body());

         // Example: PUT Request
         HttpRequest putRequest = HttpRequest.newBuilder()
                 .uri(new URI("https://jsonplaceholder.typicode.com/posts/1"))
                 .PUT(BodyPublishers.ofString("{\"id\":1,\"title\":\"updated\",\"body\":\"new content\",\"userId\":1}"))
                 .header("Content-Type", "application/json")
                 .build();
         HttpResponse<String> putResponse = httpClient.send(putRequest, BodyHandlers.ofString());
         System.out.println("PUT Response: " + putResponse.body());

         // Example: DELETE Request
         HttpRequest deleteRequest = HttpRequest.newBuilder()
                 .uri(new URI("https://jsonplaceholder.typicode.com/posts/1"))
                 .DELETE()
                 .build();
         HttpResponse<String> deleteResponse = httpClient.send(deleteRequest, BodyHandlers.ofString());
         System.out.println("DELETE Response Code: " + deleteResponse.statusCode());

      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

3. Explanation

  1. HttpClient Creation: The HttpClient instance is reusable for making multiple requests.
  2. GET Request:
    • Use .GET() method to send a GET request.
    • Response is parsed as a String using BodyHandlers.ofString().
  3. POST Request:
    • Use .POST(BodyPublishers.ofString(content)) to send a POST request with a payload.
    • Set the Content-Type header for JSON or other content types.
  4. PUT Request:
    • Use .PUT(BodyPublishers.ofString(content)) for PUT requests with a payload.
    • Similar to POST, set the proper headers.
  5. DELETE Request:
    • Use .DELETE() to send DELETE requests.
    • Rarely includes a body; that’s why no publisher is used.
  6. Error Handling:
    • Be sure to include error handling for exceptions such as IOException and InterruptedException.

4. Output Example

If you run the code using the example endpoints, the output might look something like this:

GET Response: {
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
POST Response: {
  "title": "foo",
  "body": "bar",
  "userId": 1,
  "id": 101
}
PUT Response: {
  "id": 1,
  "title": "updated",
  "body": "new content",
  "userId": 1
}
DELETE Response Code: 200

5. Notes

  • You’ll need an API endpoint that supports CRUD operations for realistic testing.
  • Avoid hardcoding URIs in production; keep them configurable.
  • Handle response status codes appropriately for error cases (like 404, 500).

This approach provides a clean and modern way to work with HTTP in Java!

How do I create and delete a file in JDK 7?

In this example you’ll learn how to create and delete a file. Using the new Files class helper from the JDK 7 you can create a file using the Files.createFile(Path) method. To delete a file you can use the Files.delete(Path) method.

Before create a file and delete a file we can check to see if the file exists or not using the Files.exists(Path) method. In the code snippet below we’ll create a file when the file is not exist. And we’ll delete the file if the file exists.

package org.kodejava.io;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CreateDeleteFile {
    public static void main(String[] args) {
        try {
            // Create a config.cfg file under D:Temp directory.
            Path path = Paths.get("F:/Temp/config.cfg");
            if (!Files.exists(path)) {
                Files.createFile(path);
            }

            // Delete the path.cfg file specified by the Path.
            if (Files.exists(path)) {
                Files.delete(path);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

How do I delete entity object in JPA?

The following code example show you how to delete or remove entity object from database using JPA. The first class that we are going to create is ArtistDaoImpl which implements ArtistDao. This DAO class handles the delete process either by the entity ID or by the entity object itself. We define the delete process in deleteById(Long id) and delete(Artist artist) methods.

In those methods we call the EntityManager.remove() method. This method of EntityManager will take care of removing the entity object from our database. Let’s see the DAO code below:

package org.kodejava.jpa.dao;

import org.kodejava.jpa.entity.Artist;

import java.util.List;

public interface ArtistDao {
    Artist findById(Long id);

    void save(Artist artist);

    void update(Artist artist);

    List<Artist> getArtists();

    void deleteById(Long id);

    void delete(Artist artist);
}
package org.kodejava.jpa.dao.impl;

import org.kodejava.jpa.dao.ArtistDao;
import org.kodejava.jpa.entity.Artist;

import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import java.util.List;

public class ArtistDaoImpl implements ArtistDao {
    private final EntityManager manager;

    public ArtistDaoImpl(EntityManager manager) {
        this.manager = manager;
    }

    /**
     * Find Artist based on the entity id.
     *
     * @param artistId the artist id.
     * @return Artist.
     * @throws EntityNotFoundException when no artist is found.
     */
    public Artist findById(Long artistId) {
        Artist artist = manager.find(Artist.class, artistId);
        if (artist == null) {
            throw new EntityNotFoundException("Can't find Artist for ID "
                    + artistId);
        }
        return artist;
    }

    @Override
    public void save(Artist artist) {
        manager.getTransaction().begin();
        manager.persist(artist);
        manager.getTransaction().commit();
    }

    /**
     * Update Artist information.
     *
     * @param artist an Artist to be updated.
     */
    @Override
    public void update(Artist artist) {
        manager.getTransaction().begin();
        manager.merge(artist);
        manager.getTransaction().commit();
    }

    @Override
    @SuppressWarnings(value = "unchecked")
    public List<Artist> getArtists() {
        Query query = manager.createQuery("select a from Artist a", Artist.class);
        return query.getResultList();
    }

    /**
     * Delete artist by their id.
     *
     * @param id the artist id.
     */
    @Override
    public void deleteById(Long id) {
        Artist artist = manager.find(Artist.class, id);
        if (artist != null) {
            manager.getTransaction().begin();
            manager.remove(artist);
            manager.getTransaction().commit();
        }
    }

    /**
     * Delete artist entity.
     *
     * @param artist the object to be deleted.
     */
    @Override
    public void delete(Artist artist) {
        manager.getTransaction().begin();
        manager.remove(artist);
        manager.getTransaction().commit();
    }
}

After defining the delete methods in the ArtistDao class we create a simple program to demonstrate both of them. In this program we start by create the EntityManagerFactory object from the defined persistence unit in the persistence.xml file. Then we create the EntityManager object, and we pass it to our ArtistDaoImpl object. And then we call the delete methods to remove entity from the database.

To show you the result of the delete process we print out the artist data before and after the delete method is called.

package org.kodejava.jpa;

import org.kodejava.jpa.dao.ArtistDao;
import org.kodejava.jpa.dao.impl.ArtistDaoImpl;
import org.kodejava.jpa.entity.Artist;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.util.List;

public class EntityRemoveDemo {
    public static final String PERSISTENCE_UNIT_NAME = "music";

    public static void main(String[] args) {
        EntityManagerFactory factory =
                Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
        EntityManager manager = factory.createEntityManager();

        ArtistDao dao = new ArtistDaoImpl(manager);
        System.out.println("Before Delete:");
        printArtists(dao.getArtists());

        // Remove artist with ID = 1.
        dao.deleteById(1L);

        // Remove artist with ID = 2.
        Artist artist = dao.findById(2L);
        dao.delete(artist);

        System.out.println("After Delete:");
        printArtists(dao.getArtists());
    }

    private static void printArtists(List<Artist> artists) {
        for (Artist artist : artists) {
            System.out.println("Artist = " + artist);
        }
    }
}

Here is the result of our code snippet. It shows the number of records before and after the delete process.

Before Delete:
Artist = Artist{id=1, name='Bon Jovi'}
Artist = Artist{id=2, name='Mr. Big'}
Artist = Artist{id=3, name='Metallica'}
After Delete:
Artist = Artist{id=3, name='Metallica'}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>javax.persistence</groupId>
        <artifactId>javax.persistence-api</artifactId>
        <version>2.2</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.6.9.Final</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.1.0</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central

How do I remove some characters from a StringBuffer?

The example below show you to remove some elements of the StringBuffer. We can use the delete(int start, int end) method call to remove some characters from the specified start index to end end index. We can also remove a character at the specified index using the deleteCharAt(int index) method call.

package org.kodejava.lang;

public class StringBufferDelete {
    public static void main(String[] args) {
        String text = "Learn Java by Examples";

        // Creates a new instance of StringBuffer and initialize
        // it with some text.
        StringBuffer buffer = new StringBuffer(text);
        System.out.println("Original text  = " + buffer);

        // We'll remove a sub string from this StringBuffer starting
        // from the first character to the 10th character.
        buffer.delete(0, 10);
        System.out.println("After deletion = " + buffer);

        // Removes a char at a specified index from the StringBuffer.
        // In the example below we remove the last character.
        buffer.deleteCharAt(buffer.length() - 1);
        System.out.println("Final result   = " + buffer);
    }
}

Output of the program is:

Original text  = Learn Java by Examples
After deletion =  by Examples
Final result   =  by Example