Neo4j - Delete a Node using Cypher

To delete nodes and relationships using Cypher, use the DELETE clause.

The DELETE clause is used within the MATCH statement to delete whatever data was matched.

So, the DELETE clause is used in the same place we used the RETURN clause in our previous examples.

Example

The following statement deletes the Album node called Killers:

It's a good idea to check that you're about to delete the right data before actually deleting it.

To do this, construct your statement with a RETURN clause first, and then run it. This enables you to check whether you're going to delete the correct data or not. Once you're satisfied that you're matching the correct data, simply switch the RETURN clause into a DELETE clause.

Deleting Multiple Nodes

You can also delete multiple nodes in one go. Simply construct your MATCH statement to include all nodes you'd like to delete.

Deleting All Nodes

You can delete all nodes from the database simply by omitting any filtering criteria. Just like when we selected all nodes from the database, you can delete them too.

Deleting Nodes with Relationships

There's one small catch with deleting nodes. And that is, you can only delete nodes if they don't have any relationships. In other words, you must delete any relationships before you delete the node itself.

If you try to execute the above DELETE statement on nodes that have relationships, you will see an error message like this:

Screenshot of error message from trying to delete a node with relationships.

This error message is telling us that we have to delete any relationships before we delete the node.

Fortunately, there's a quick and easy way to do that. We'll cover it next in deleting relationships.