JDBC Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 2.11

"DELETE FROM" Statements

This section describes how to delete existing data rows with DELETE statements.

DELETE statements are used less frequently in database applications. They are used only when you want to remove data rows from a table permanently. DELETE statements should include a WHERE clause to identify the data rows to be deleted.

UPDATE statements should be executed with the executeUpdate() method. The Java tutorial program below shows you how to update

/**
 * DerbyDeleteRows.java
 * Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
 */
import java.sql.*;
public class DerbyDeleteRows {
  public static void main(String [] args) {
    Connection con = null;
    try {
      con = DriverManager.getConnection(
        "jdbc:derby://localhost/TestDB");
      Statement sta = con.createStatement(); 

// deleting multiple rows
      int count = sta.executeUpdate(
        "DELETE FROM Profile WHERE ID in (1, 3, 5, 7)");
      System.out.println("Number of rows deleted: "+count);

// getting the data back
      ResultSet res = sta.executeQuery("SELECT * FROM Profile");
      System.out.println("List of Profiles: "); 
      while (res.next()) {
         System.out.println(
           "  "+res.getInt("ID")
           + ", "+res.getString("FirstName")
           + ", "+res.getString("LastName")
           + ", "+res.getFloat("Point")
           + ", "+res.getDate("BirthDate")
           + ", "+res.getTimestamp("ModTime"));
      }
      res.close();

      sta.close();
      con.close();        
    } catch (Exception e) {
      System.err.println("Exception: "+e.getMessage());
    }
  }
}

The output confirms that 4 rows were deleted:

Number of rows deleted: 4
List of Profiles:
  2, Janet, Gates, 999.99, 1984-10-13, 2006-12-31 23:59:59.999
  4, 21d6, efd17, 289.4137, 1988-12-31, 2006-12-31 23:59:59.999
  6, 1002, e3873, 996.2754, 1988-12-31, 2006-12-31 23:59:59.999
  8, 11bd, 58ad0, 741.9156, 1988-12-31, 2007-04-01 23:59:59.999
  9, 1352, 17d9, 274.19855, 1988-12-31, 2007-04-01 23:59:59.999
  10, 13ba, 88356, 115.04227, 1988-12-31, 2007-04-01 23:59:59.999
  11, 1090, 3fb07, 767.21246, 1988-12-31, 2007-04-01 23:59:59.999
  12, 19c2, 8770b, 383.88382, 1988-12-31, 2007-04-01 23:59:59.999
  13, Keith, Harris, 0.0, 1980-02-29, 2007-04-01 23:59:59.999

Sections in This Chapter

Tables with Primary Key Column "GENERATED ... AS IDENTITY"

"INSERT INTO" Statements

"INSERT INTO" Statements with INDENTITY Columns

Handling Date and Timestamp Values

"UPDATE" Statements

"DELETE FROM" Statements

Dr. Herong Yang, updated in 2007
"DELETE FROM" Statements