Understanding CRUD Operations

Understanding CRUD Operations

·

5 min read

Introduction

CRUD stands for Create, Read, Update, and Delete. These four operations make up the basics of persistent storage and database interactions. Understanding how to perform CRUD operations is key for any developer working with databases or other forms of data storage.

What are CRUD Operations?

As mentioned above, CRUD stands for the four basic functions of persistent storage:

  • Create - Adding new data to the storage system. This might involve SQL INSERT statements, NoSQL database set() commands, or writing data to files.

  • Read - Retrieving data from the storage system. This typically involves SQL SELECT statements or NoSQL find() operations.

  • Update - Modifying existing data in the storage system. SQL UPDATE statements or NoSQL update() commands are examples.

  • Delete - Removing data from the storage system. SQL DELETE statements or NoSQL remove() methods accomplish this.

Most applications require all four CRUD functions. For example, a contact management system needs to allow users to add new contacts (Create), view existing contacts (Read), modify contacts (Update), and remove contacts (Delete).

Without the full set of CRUD capabilities, an application would be severely limited in functionality. Understanding how to implement these core operations is foundational for any developer working with persistent data.

CRUD in SQL Databases

In relational SQL databases like MySQL, PostgreSQL, and SQL Server, the primary statements for performing CRUD operations are:

  • INSERT - add new rows to a table

  • SELECT - retrieve rows from a table

  • UPDATE - modify existing rows in a table

  • DELETE - remove rows from a table

For example:

-- Create  
INSERT INTO users (name, email) VALUES ('John', 'john@email.com');

-- Read
SELECT * FROM users;

-- Update  
UPDATE users SET name='Jane' WHERE id=1; 

-- Delete 
DELETE FROM users WHERE id=1;

SQL provides additional statements like JOIN and complex WHERE clauses to retrieve and modify data in more advanced ways. But the core CRUD operations are enabled through the basic INSERT, SELECT, UPDATE, and DELETE statements.

Mastering these is critical for working effectively in SQL.

CRUD in NoSQL Databases

NoSQL databases like MongoDB and Cassandra also require CRUD operations, but implement them differently than SQL.

For example, in MongoDB the main statements are:

  • insertOne() - insert a new document

  • find() - query documents

  • updateOne() - update a document

  • deleteOne() - delete a document

Example MongoDB CRUD:

// Create
db.users.insertOne({
  name: 'John',
  email: 'john@email.com'  
});

// Read  
db.users.find();

// Update
db.users.updateOne(
  { name: 'John' }, 
  { $set: { name: 'Jane' } }  
);

// Delete  
db.users.deleteOne({ name: 'Jane' });

The MongoDB methods provide a similar CRUD functionality to SQL statements. The syntax is different, but the core ability to create, query, update, and delete data is the same.

Other NoSQL databases have similar methods that provide CRUD operations using their own API and query languages.

CRUD Operations with Object-Oriented Programming

CRUD principles also apply to object-oriented code working with classes. Typical CRUD operations for classes include:

  • Constructors - Create instances of a class

  • Getters - Read values from a class

  • Setters - Update values in a class

  • Destructors - Delete class instances

For example:

class User {

  constructor(name, email) {
    this.name = name;
    this.email = email;
  }

  getName() {
    return this.name;
  }

  setName(name) {
    this.name = name;
  }

}

// Create  
let user = new User('John', 'john@email.com');

// Read
user.getName();

// Update
user.setName('Jane');

// Delete
user = null; // destructor

This demonstrates the CRUD pattern even when working with classes and objects, not just with databases. The same principles apply.

CRUD with REST APIs

CRUD operations are also core aspects of REST API design. REST APIs typically utilize HTTP request methods to perform CRUD functions:

  • POST - Create new resources

  • GET - Read resources

  • PUT/PATCH - Update existing resources

  • DELETE - Delete resources

For example:

// Create
POST /users  

// Read
GET /users/1

// Update 
PUT /users/1

// Delete
DELETE /users/1

REST leverages HTTP methods to provide a consistent and standard way to implement CRUD functionality.

Benefits of CRUD

Why is CRUD important? What benefits does properly implementing CRUD operations provide?

  • Simplicity - CRUD provides a straightforward mental model for working with persistent data. The simple verbs of create, read, update, and delete clearly convey what operations are occurring.

  • Standardization - CRUD defines a standard set of data operations across different storage systems like databases and APIs. This provides consistency and portability.

  • Separation of concerns - CRUD separates data manipulation from business logic. Code focuses on CRUD while separate application code handles processing.

  • Flexibility - CRUD is not rigidly defined. There are many ways to implement the basic principles while optimizing for specific technologies and use cases.

In summary, by providing simple, standard and flexible functions for basic data operations, CRUD improves code organization, scalability, and maintenance. It encapsulates core data access concepts for easy reuse across projects and teams.

CRUD Example: Todo Application

Let's look at a simple Todo application to demonstrate implementing CRUD operations:

// Todo class
class Todo {

  constructor(text) {
    this.text = text;
    this.completed = false; 
  }

  updateText(text) {
    this.text = text;
  }

  markCompleted() {
    this.completed = true;
  }

}

// TodoService handles CRUD operations  
class TodoService {

  constructor() {
    this.todos = []; 
  }

  addTodo(text) {
    const todo = new Todo(text);
    this.todos.push(todo);
  }

  getTodos() {
   return this.todos;
  }

  updateTodo(index, text) {
    this.todos[index].updateText(text);
  }

  deleteTodo(index) {
    this.todos.splice(index, 1);
  }

}

// Usage
const service = new TodoService();

// Create  
service.addTodo('Buy groceries');

// Read
console.log(service.getTodos()); 

// Update
service.updateTodo(0, 'Buy food');

// Delete 
service.deleteTodo(0);

This shows the TodoService isolating the CRUD logic from the Todo class and application code. The service exposes simple methods for creating, retrieving, updating and deleting todos without complex logic.

This is a common and effective pattern for CRUD apps - extract the data persistence logic into a dedicated service.

Conclusion

In summary, CRUD operations provide foundational and flexible patterns for interacting with persistent data in apps.

CRUD enables simplicity, standardization and separation of concerns. Mastering these core operations unlocks the ability to effectively implement durable storage and databases for all types of applications.