darkphantom500
darkphantom500

Reputation: 63

Deleting value using SQlite while doing an INNER JOIN

I am trying to delete all voters from a voters table where they are not registered as a democrat or republican AND only voted once. I have a database with three tables, congress_members, voters, and votes and have to JOIN votes with voters in order to delete the right data.

This code finds the data I want to delete:

SELECT voters.*
FROM voters JOIN votes ON voters.id = votes.voter_id
WHERE party = 'green' OR party = 'na' OR party = 'independent'
GROUP BY votes.voter_id
HAVING COUNT(*) = 1;

But I am unable to delete it because I am getting an error everytime I try to delete with a JOIN statement

Upvotes: 5

Views: 5604

Answers (2)

yxre
yxre

Reputation: 3704

You are getting the error because the join will query your database and create a temporary table that will hold your newly queried data. The delete staements are used to remove data that is stored inside your database on your disk and not inside your memory.

The delete statement syntax is "DELETE FROM table WHERE conditions". The table value will need to be one of the three tables in your database, and your target is voters. As of right now, you have half of your delete statement complete.

The where clause needs to evaluate to a boolean value for each row. There is a function called EXISTS (). This function can be used to delete this data. Essentially, you will place your select statement from your post inside of the EXISTS (). The function will compare each of your rows in the target delete table to a row in your table inside of exists. If there is a match, then the row exists, the function evaluates to true for that row, and it is deleted.

DELETE FROM voters WHERE (party = 'green' OR party = 'na' OR party = 'independent') AND EXISTS ( SELECT 1 FROM votes WHERE votes.id = voters.id HAVING COUNT(*) = 1 )

Upvotes: 5

Gordon Linoff
Gordon Linoff

Reputation: 1269603

You can phrase this as a delete with a where clause:

delete from voters
    where votes.party not in ('democrat', 'republican') and
          voters.id in (select id from votes group by id having count(*) = 1);

Upvotes: 8

Related Questions