Lesson 4: Writing data

Inserting simple data

  • Insert clauses are used to insert data. They can be used alone, using just an insert clause, or after any other sequence of clauses, such as a match clause. Inserts are run using write transactions (or in a schema transaction).

    insert
    # insert clause
    match
    # match clause
    insert
    # insert clause
  • All attributes may be multivalued, depending on the set cardinality constraint, allowing an entity or relation to own any number of attributes of the same type, as long as they each have different values. The default is @card(0..1), which means 0 or 1 attributes

  • An Insert without a match clause inserts data once. An Insert query with a match clause may insert data multiple times, once for each match found.

Inserting polymorphic data

  • A polymorphic insert can be performed by using a polymorphic pattern in the match clause of an insert.

  • When inserting a relation, the roles can be omitted if they can be inferred unambiguously.

Deleting data

  • Delete clauses are used to delete data. They comprise a match clause (or any other sequence of clauses) and a delete clause. Deletes require using write transaction (or schema transaction).

    match
    # match clause
    delete
    # delete clause
  • Delete queries delete data per statement.

  • An inverted has statement is used to delete an entity or relation’s attribute: has <attribute var> of <owner

    delete
    has $attribute of $entity;
  • Deleting an entity or relation can be done with a simple deletion of the variable

    delete
    $entity;
  • When deleting a entity or relation playing a role in another relation that should also be removed, the relation must also be deleted manually. A relation is only deleted automatically if all of its role players are deleted (until @cascade is implemented as an annotation!).

Updating data

  • Chained delete and insert clauses are used to update data. They comprise a match clause, a delete clause, and an insert clause. Updates are using a write transaction (or a schema transaction).

    match
    # match clause
    delete
    # delete clause
    insert
    # insert clause

Data validation

  • All inserted data is validated against the schema.

  • Inserting data that does not conform to the schema will cause an exception to be thrown.

  • An exception will also be thrown if deleting or updating data leads to an invalid state.

Further learning

Learn how to define schemas for TypeDB, including type hierarchies, interfaces between types, value constraints, and functions.

Learn more about writing data to TypeDB, covering Insert queries, Delete queries, and Update queries.

Read the Insert query reference, including syntax, behaviour, and advanced usage.