Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 34

Delta Lake CRUD Operations

This lesson is built with resources from youtube.com, docs.databricks.com and 1 more site.

Hello! Welcome back to our hands-on exploration of the data lakehouse.

In the last lesson, we uncovered the "magic" behind Delta Lake's reliability: the transaction log. You learned that every change to a table is an atomic operation that adds a new commit file to the _delta_log directory. We saw that operations like an UPDATE don't change data files in place; instead, they perform a "copy-on-write," creating new files with the updated data and logically marking the old files for removal.

Today, we move from theory to practice. Our goal is to learn how to use Delta Lake to perform basic Create, Read, Update, and Delete (CRUD) operations on data in a lakehouse. You'll see the SQL and programmatic commands that leverage the transactional power we just discussed. As an architect, you'll recognize the DML (Data Manipulation Language) patterns from your relational database experience, but you'll now understand the very different mechanics that execute them reliably in a data lake environment.

1. Creating and Reading Delta Tables

Let's start with the basics: creating a table (the "C" in CRUD) and reading from it (the "R"). There are several ways to create a Delta table. You can define an empty table with a specific schema, or you can create a table directly from a data source like a CSV file or an existing Spark DataFrame.

The official Databricks documentation provides a clear, concise tutorial for these fundamental steps.

Tutorial: Create and manage Delta Lake tables

The Databricks tutorial 'Create and manage Delta Lake tables' provides excellent code examples for the foundational operations of creating and reading tables. It shows how you can use familiar SQL syntax as well as programmatic APIs in Python.

Please review the code examples in the following sections of this tutorial: 'Create a table': Observe the different methods shown, particularly the SQL CREATE TABLE AS SELECT and the Python df.writeTo(...).createOrReplace() methods. Notice how you can create a table from an existing file source. 'Read a table': Note that reading a Delta table is as simple as a standard SELECT query in SQL or using spark.read.table() in Python. From a user's perspective, it feels just like querying any other table. Focus on the SQL and Python examples.

As you can see, the user experience is straightforward. Behind the scenes, the CREATE TABLE command reads the source data, writes it out as Parquet files, and creates the _delta_log directory with the initial commit file (000000.json) that lists all the newly added Parquet files.


2. Updating and Deleting Data

Now we get to the operations that truly differentiate Delta Lake from a standard data lake: UPDATE and DELETE (the "U" and "D" in CRUD). In a traditional data lake, these are complex and risky. In Delta Lake, they are ACID-compliant, atomic operations.

Let's watch a segment from a Databricks tech talk that explains and demonstrates exactly what happens when you run these commands.

Tech Talk | Diving into Delta Lake Part 3: How do DELETE, UPDATE, and MERGE work

The video 'Diving into Delta Lake Part 3' offers a fantastic look under the hood at DML operations. It connects the high-level commands to the file-level actions in the transaction log that you learned about in our previous lesson.

Please watch the following segments: UPDATE Mechanics & Demo (04:23 - 12:40): This section details how an UPDATE works. It first finds the files containing the rows to be updated and then rewrites just those files. The demo in the notebook makes this process very concrete. DELETE Mechanics & VACUUM (16:56 - 20:17): This part explains the DELETE operation and introduces the crucial VACUUM command. Pay close attention to the distinction between logically marking a file as deleted in the log versus physically removing it from storage.

Key Points on UPDATE and DELETE

  • UPDATE: As the video demonstrated, an UPDATE statement identifies the Parquet files containing the rows that match your WHERE clause. It then rewrites these files, copying the unchanged rows and writing the new versions of the updated rows. The transaction log atomically records the removal of the old files and the addition of the new ones.
  • DELETE: Similarly, a DELETE operation identifies the relevant files, rewrites them without the rows you wanted to delete, and commits the change to the log.
  • Logical vs. Physical Deletion: A crucial concept is that DELETE does not immediately remove the old data files from storage. It only marks them as "removed" in the transaction log for the current and future versions of the table. This is what enables "time travel"—querying older versions of the table. To physically delete these old, unreferenced files (e.g., for cost savings or compliance), you must run the VACUUM command.
Test your understanding!

You run a DELETE command to remove all records from 2022. Afterwards, you run VACUUM my_table RETAIN 7 DAYS. A colleague immediately realizes they needed to query the 2022 data one last time. Can they still access the data? Why or why not?

Show answer

No, they cannot access the data. The DELETE operation created a new version of the table without the 2022 data. The VACUUM command then physically removed all data files that were no longer referenced by any table version within the last 7 days. Since the files containing the 2022 data were immediately unreferenced by the DELETE, the VACUUM command would have permanently deleted them from storage. This is why the default retention for VACUUM is a safeguard against such mistakes.

For a quick reference on the syntax, the Delta Lake documentation page "Table deletes, updates, and merges" is an excellent resource. You can review the DELETE and UPDATE sections at your convenience.

Table deletes, updates, and merges

This official documentation from Delta.io provides the definitive syntax for DML operations. It's a great reference to bookmark.

Briefly scan the sections 'Delete from a table' and 'Update a table'. Notice the simple, standard SQL syntax. The page provides examples for SQL, Python, and Scala, showing the versatility of the API.


3. The MERGE Operation: Upserts Made Easy

The MERGE statement is arguably the most powerful DML operation for data engineering pipelines. It allows you to efficiently perform "upserts"—updating existing records and inserting new ones in a single, atomic command. This is the workhorse of the Medallion Architecture, used to move data from Bronze to Silver or Silver to Gold.

A typical MERGE operation involves:

  1. A target table (the one you want to modify).
  2. A source table or query containing the new data/changes.
  3. A join condition (e.g., ON target.id = source.id).
  4. Clauses defining what to do:
    • WHEN MATCHED THEN UPDATE ...
    • WHEN NOT MATCHED THEN INSERT ...
    • WHEN NOT MATCHED BY SOURCE THEN DELETE ... (an optional, powerful clause)

Let's watch a practical demonstration of how to build a MERGE statement from the ground up.

15 Delta Tables MERGE and UPSERTS | SCD1 in Delta | Soft Delete with Incremental data using Merge

This video from 'Ease With Data' provides a very clear, SQL-focused walkthrough of the MERGE statement. It's perfect for seeing the syntax in a real notebook environment and understanding its different clauses.

Please watch from the beginning to 13:43. The video covers: The core concept of MERGE (UPSERT) (00:00 - 01:56). A basic MERGE to update existing records and insert new ones (01:56 - 07:30). Extending MERGE to delete records in the target that are missing from the source (07:30 - 09:06). A practical example of a 'soft delete' by adding and updating an is_active flag, which also showcases schema evolution (09:06 - 13:43).

The MERGE operation elegantly handles the complex logic of synchronizing two datasets. From an architectural perspective, it replaces what would have been a complex, multi-stage, non-atomic process in a traditional ETL framework with a single, reliable, and declarative command.

The Delta.io documentation provides further details on advanced MERGE semantics, including how to handle schema evolution automatically and common ETL patterns like data deduplication and Slowly Changing Dimensions (SCD) Type 2. Skimming these will give you a sense of its full power.


Conclusion

In this lesson, you've translated the theory of the transaction log into the practical language of data manipulation. You now have the fundamental toolkit for modifying data within a lakehouse reliably.

Key Takeaways:

  • CRUD in Delta Lake: Standard SQL syntax (CREATE, SELECT, UPDATE, DELETE) provides a familiar interface for manipulating data.
  • Copy-on-Write in Action: UPDATE and DELETE are not in-place operations. They rewrite affected data files and atomically commit the changes to the transaction log.
  • Logical vs. Physical Deletes: DELETE marks data as removed but VACUUM is required to physically delete old files from storage.
  • MERGE is the Workhorse: The MERGE statement is the cornerstone of modern data engineering pipelines, enabling efficient and atomic upserts, which are critical for tasks like building your Silver and Gold data layers.

You now understand the what, how, and why of Delta Lake tables and their manipulation. The next logical step is to get your hands on the keyboard. In our next lesson, you will set up a Databricks workspace, create a cluster, and execute notebooks, preparing you to run these very commands in a live environment.