In this post, we’re going to take a look at the D in CRUD: Delete.
We use the DBD::Oracle driver to delete some data in the database tables, using the connection object created in the Initial Setup section of the first post in this series.
PLEASE REVIEW ALL EXAMPLE CODE AND ONLY RUN IT IF YOU ARE SURE IT WILL NOT CAUSE ANY PROBLEMS WITH YOUR SYSTEM.
Helper Function
My helper function get_all_rows encapsulates a select statement used to verify that the deletes worked. The select functionality is covered in the R part of this series, so I won’t go into the details here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
sub get_all_rows { my $label = $_[0]; my $data_type = $_[1]; # Query all rows my $con = DBI->connect( 'dbi:Oracle:', $connectString, '') || die "Database connection not made: $DBI::errstr"; $con->{RaiseError} = 1; # set the connection to raise errors my $statement = 'select id, name, age, notes from lcs_people order by id'; if ($data_type eq "pets") { $statement = 'select id, name, owner, type from lcs_pets order by owner, id'; } my $sth = $con->prepare($statement); $sth->execute; #Adding some space around the results to make better screenshots. print "\n $label: \n"; while (my @row = $sth->fetchrow_array){ print " @row\n"; } print "\n"; $con->disconnect; } |
Add this function to the top of your file.
Resetting the data
To keep the examples clean and precise, I will reset the data at times.
Create a new file called reset_data.perl with the following code and run it whenever you would like to reset the data. (Notice this version adds people and pet data not included in other sections.)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
use strict; use DBI; my $connectString=$ENV{'db_connect'}; my $con = DBI->connect( 'dbi:Oracle:', $connectString, ''); $con->{RaiseError} = 1; # set the connection to raise errors # Delete rows my $sth = $con->prepare("delete from lcs_pets"); $sth->execute; # Reset Identity Coulmn my $sth = $con->prepare("alter table lcs_pets modify id generated BY DEFAULT as identity (START WITH 8)"); $sth->execute; # Delete rows my $sth = $con->prepare("delete from lcs_people"); $sth->execute; # Reset Identity Coulmn my $sth = $con->prepare("alter table lcs_people modify id generated BY DEFAULT as identity (START WITH 8)"); $sth->execute; # Insert default rows my @ids = (1, 2, 3, 4, 5, 6, 7); my @names = ("Bob", "Kim", "Cheryl", "Bob", "Stacey", "Pete", "Pat"); my @ages = (35, 27, 23, 27, 45, 23, 36); my @notes = ("I like dogs", "I like birds", "I like horses", "I like rabbits", "I like snakes", "I like cats", "I like dogs"); my $sth = $con->prepare("INSERT INTO lcs_people(id, name, age, notes) VALUES (?, ?, ?, ?)"); my $tuples = $sth->execute_array( { ArrayTupleStatus => \my @tuple_status }, \@ids, \@names, \@ages, \@notes,); if ($tuples) { print "Successfully inserted $tuples records\n"; } else { print "Insert failed\n"; } # Insert default rows my @ids = (1, 2, 3, 4, 5, 6, 7); my @names = ("Duke", "Dragon", "Sneaky", "Red", "Red", "Buster", "Fido"); my @owners = (1, 2, 5, 2, 3, 1, 7); my @types = ("dog", "bird", "snake", "bird", "horse", "dog", "cat"); my $sth = $con->prepare("INSERT INTO lcs_pets(id, name, owner, type) VALUES (?, ?, ?, ?)"); my $tuples = $sth->execute_array( { ArrayTupleStatus => \my @tuple_status }, \@ids, \@names, \@owners, \@types,); if ($tuples) { print "Successfully inserted $tuples records\n"; } else { print "Insert failed\n"; } $con->disconnect; |
Boilerplate template
The template we will be using is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
use strict; use DBI; my $connectString=$ENV{'db_connect'}; sub get_all_rows { my $label = $_[0]; my $data_type = $_[1]; # Query all rows my $con = DBI->connect( 'dbi:Oracle:', $connectString, '') || die "Database connection not made: $DBI::errstr"; $con->{RaiseError} = 1; # set the connection to raise errors my $statement = 'select id, name, age, notes from lcs_people order by id'; if ($data_type eq 'pets') { $statement = 'select id, name, owner, type from lcs_pets order by owner, id'; } my $sth = $con->prepare($statement); $sth->execute; #Adding some space around the results to make better screenshots. print "\n $label: \n"; while (my @row = $sth->fetchrow_array){ print " @row\n"; } print "\n"; $con->disconnect; } my $con = DBI->connect( 'dbi:Oracle:', $connectString, '') || die "Database connection not made: $DBI::errstr"; $con->{RaiseError} = 1; # set the connection to raise errors get_all_rows('Original Data', 'pets'); # Your code here get_all_rows('New Data', 'pets'); |
For each exercise, replace the “# Your code here” line with your code.
Reset the data
First, let’s run reset_data.perl to set up our data.
Simple delete
We will perform a simple delete that removes a single record from the lcs_people table. These are the steps performed in the code snippet below.
- Prepare a SQL DELETE statement, deleting the record with an id of 1.
- Bind the id value. (See the R part of this series for an explanation of bind variables.)
- Execute the statement.
1 2 3 |
my $sth = $con->prepare("delete from lcs_pets where id = :id"); $sth->bind_param( ":id",1); $sth->execute; |

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Original Data: <del>1 Duke 1 dog</del> 6 Buster 1 dog 2 Dragon 2 bird 4 Red 2 bird 5 Red 3 horse 3 Sneaky 5 snake 7 Fido 7 cat New Data: 6 Buster 1 dog 2 Dragon 2 bird 4 Red 2 bird 5 Red 3 horse 3 Sneaky 5 snake 7 Fido 7 cat |
Extra Fun 1
Delete all the birds .
Your results should be:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Original Data: 6 Buster 1 dog <del>2 Dragon 2 bird</del> <del>4 Red 2 bird</del> 5 Red 3 horse 3 Sneaky 5 snake 7 Fido 7 cat New Data: 6 Buster 1 dog 5 Red 3 horse 3 Sneaky 5 snake 7 Fido 7 cat |
Reset the data
Now is a good time to run reset_data.perl.
Boilerplate change
Change the boilerplate get_all_rows statements to get people and pet data.
1 2 3 4 5 6 7 |
get_all_rows('Original People Data', 'people'); get_all_rows('Original Pet Data', 'pets'); # Your code here get_all_rows('New People Data', 'people'); get_all_rows('New Pet Data', 'pets'); |
Deleting records referenced by Foreign Keys
If you are using integrity constraints in your database (of course you are, because then you let the database do some heavy lifting for you), you will sometimes need to change the way you process your changes.
In our design, we have a Foreign Key constraint in lcs_pets that ensures if a pet has an owner, that owner exists.
This is the statement that creates the constraint in the Creating the Database Objects section of the Initial Setup post.
1 2 |
ALTER TABLE LCS_PETS ADD CONSTRAINT FK_LCS_PETS_OWNER FOREIGN KEY ("OWNER") REFERENCES "LCS_PEOPLE" ("ID") / |
If we attempt to delete a record in lcs_people that is referenced in lcs_pets (Person has a pet,) we get an error.
1 2 3 |
my $sth = $con->prepare("delete from lcs_people where id = :id"); $sth->bind_param( ":id",1); $sth->execute; |
When I run this code in my Perl session, I see:
1 2 |
DBD::Oracle::st execute failed: ORA-02292: integrity constraint (BLAINE.FK_LCS_PETS_OWNER) violated - child record found (DBD ERROR: OCIStmtExecute) [for Statement "delete from lcs_people where id = :id" with ParamValues: :id=1] at delete2.perl line 41. DBD::Oracle::st execute failed: ORA-02292: integrity constraint (BLAINE.FK_LCS_PETS_OWNER) violated - child record found (DBD ERROR: OCIStmtExecute) [for Statement "delete from lcs_people where id = :id" with ParamValues: :id=1] at delete2.perl line 41. |
Before deleting the person you have to handle the pet (watch out for claws and teeth).
There are a few options here, depending on your database design:
- If: pets are not required to have an owner and you only want to delete the person, not the pets. Then: you can update the pets and set their owner to null.
- If: pets are required to have an owner. Then: you can delete the pets for the owner.
In either of the above scenarios, you can update the pets and set their owner to another person.
Bob is moving out of our area and his new apartment doesn’t allow pets, so he’s giving them to Kim. Let’s use that last option here.
- Prepare a SQL UPDATE statement, changing owner to 2 (Kim) for the records with an owner of 1 (Bob). Updating is covered in the U part of this series.
- Bind the new and old owner values.
- Execute the statement.
- Prepare a SQL DELETE statement, deleting records with an id of 1 (Bob).
- Bind the id value.
- Execute the statement.
1 2 3 4 5 6 7 8 |
my $sth = $con->prepare("update lcs_pets set owner = :newOwner where owner = :oldOwner"); $sth->bind_param(":newOwner",2); $sth->bind_param(":oldOwner",1); $sth->execute; my $sth = $con->prepare("delete from lcs_people where id = :id"); $sth->bind_param(":id",1); $sth->execute; |

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
Original People Data: <del>1 Bob 35 I like dogs</del> 2 Kim 27 I like birds 3 Cheryl 23 I like horses 4 Bob 27 I like rabbits 5 Stacey 45 I like snakes 6 Pete 23 I like cats 7 Pat 36 I like dogs Original Pet Data: 1 Duke 1 dog 6 Buster 1 dog 2 Dragon 2 bird 4 Red 2 bird 5 Red 3 horse 3 Sneaky 5 snake 7 Fido 7 cat New People Data: 2 Kim 27 I like birds 3 Cheryl 23 I like horses 4 Bob 27 I like rabbits 5 Stacey 45 I like snakes 6 Pete 23 I like cats 7 Pat 36 I like dogs New Pet Data: <strong>1 Duke 2 dog</strong> 2 Dragon 2 bird 4 Red 2 bird <strong>6 Buster 2 dog</strong> 5 Red 3 horse 3 Sneaky 5 snake 7 Fido 7 cat |
Extra Fun 2
Due to a zoning change, snakes are no longer allowed in our area. Stacey has decided to move and take Sneaky with her.
Let’s fix our data.
Your results should be:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
Original People Data: 2 Kim 27 I like birds 3 Cheryl 23 I like horses 4 Bob 27 I like rabbits <del>5 Stacey 45 I like snakes</del> 6 Pete 23 I like cats 7 Pat 36 I like dogs Original Pet Data: 1 Duke 2 dog 2 Dragon 2 bird 4 Red 2 bird 6 Buster 2 dog 5 Red 3 horse <del>3 Sneaky 5 snake</del> 7 Fido 7 cat New People Data: 2 Kim 27 I like birds 3 Cheryl 23 I like horses 4 Bob 27 I like rabbits 6 Pete 23 I like cats 7 Pat 36 I like dogs New Pet Data: 1 Duke 2 dog 2 Dragon 2 bird 4 Red 2 bird 6 Buster 2 dog 5 Red 3 horse 7 Fido 7 cat |
Some other things you could try
- Change the database constraints to delete or Null the child record on delete (a cascading delete). Delete a person and let the database handle the children.
- Remove the people who don’t have any pets.
Series sections
Initial Setup
Create records
Retrieve records
Update records
Delete records
You must be logged in to post a comment.