1

I'm using SQLite to play around and learn some more SQL. I have a SQLite 3 database populated like this:

create table playlist (id integer primary key autoincrement, name text);

create table playlistitem (id integer primary key autoincrement, 
    playlist_id integer, name text);

insert into playlist (name) values ("Moss");
insert into playlist (name) values ("Jen");

insert into playlistitem (playlist_id, name) values (1, "Roy");
insert into playlistitem (playlist_id, name) values (1, "Richmond");
insert into playlistitem (playlist_id, name) values (2, "Denholm");

Great, now I have two playlist items in the "Moss" playlist, "Roy" and "Richmond"; I have one item in the "Jen" playlist: "Denholm".

What I'd like to do is delete the "Moss" playlist and all of its items with a single query.

I saw something like this, which fails for me:

delete playlist, playlistitem from playlist
    inner join playlistitem on playlistitem.playlist_id = playlist.id
    where playlist.name = "Moss";

Failure:

Error: near "playlist": syntax error

What am I doing wrong?

1 Answer 1

2

sqlite doesn't support join in delete statement. You have to use separate query that deletes from second table based on playlist_id, making a delete trigger on playlist, or make that reference a foreign key with on delete cascade:

create table playlistitem (
    id integer primary key autoincrement,
    playlist_id integer, name text,
    foreign key(playlist_id) references playlist(id) on delete cascade);

and then just using delete from playlist where name='Moss'.

Don't forget to enable foreign keys - pragma foreign_keys=1 (you have to re-enable this on each sqlite connection, e.g. as the first command after connecting).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.