What are CRUD Operations: How CRUD Operations Work, Examples, Tutorials & More

By: Alexandra
  |  February 28, 2024
What are CRUD Operations: How CRUD Operations Work, Examples, Tutorials & More

If you’ve ever worked with a database, you’ve likely worked with CRUD operations. CRUD operations are often used with SQL, a topic we’ve covered in depth (see this article, this one, and this one for some of our recent SQL tips and tricks). Since SQL is pretty prominent in the development community, it’s crucial for developers to understand how CRUD operations work. So, this article is meant to bring you up to speed (if you’re not already) on CRUD operations.

The Definition of CRUD

Within computer programming, the acronym CRUD stands for create, read, update, and delete. These are the four basic functions of persistent storage. Also, each letter in the acronym can refer to all functions executed in relational database applications and mapped to a standard HTTP method, SQL statement, or DDS operation.

It can also describe user-interface conventions that allow viewing, searching, and modifying information through computer-based forms and reports. In essence, entities are read, created, updated, and deleted. Those same entities can be modified by taking the data from a service and changing the setting properties before sending the data back to the service for an update. Plus, CRUD is data-oriented and the standardized use of HTTP action verbs.

CRUD Operations

Screenshot Source: Oracle

Most applications have some form of CRUD functionality. In fact, every programmer has had to deal with CRUD at some point. Not to mention, a CRUD application is one that utilizes forms to retrieve and return data from a database.

The first reference to CRUD operations came from Haim Kilov in 1990 in an article titled, “From semantic to object-oriented data modeling.” However, the term was first made popular by James Martin’s 1983 book, Managing the Data-base Environment. Here’s a breakdown:

  • CREATE procedures: Performs the INSERT statement to create a new record in SQL databases.
  • READ procedures: Reads the table records based on the primary keynoted within the input parameter.
  • UPDATE procedures: Executes an UPDATE statement on the table based on the specified primary key for a record within the WHERE clause of the statement.
  • DELETE procedures: Deletes a specified row in the WHERE clause.

How CRUD Works: Executing Operations and Examples

Based on the requirements of a system, varying user may have different CRUD cycles. A customer may use CRUD to create an account and access that account when returning to a particular site. The user may then update personal data or change billing information. On the other hand, an operations manager might create product records, then call them when needed or modify line items.

During the Web 2.0 era, CRUD operations were at the foundation of most dynamic websites. However, you should differentiate CRUD from the HTTP action verbs. For example, if you want to create a new record you should use “POST.” To update a record, you would use “PUT” or “PATCH.” If you wanted to delete a record, you would use “DELETE.” Through CRUD, users and administrators had the access rights to edit, delete, create or browse online records.

An application designer has many options for executing CRUD operations. One of the most efficient of choices is to create a set of stored procedures in SQL to execute operations.

Here’s an example SQL procedure for CRUD operations on customer data.

-- CREATE PROCEDURE
CREATE PROCEDURE insert_customer (
    IN first_name VARCHAR(50),
    IN last_name VARCHAR(50),
    IN email VARCHAR(100),
    IN phone VARCHAR(20),
    IN address VARCHAR(200)
)
BEGIN
    INSERT INTO customers (first_name, last_name, email, phone, address)
    VALUES (first_name, last_name, email, phone, address);
END;
-- READ PROCEDURE
CREATE PROCEDURE select_customer (
    IN id INT
)
BEGIN
    SELECT * FROM customers
    WHERE customer_id = id;
END;
-- UPDATE PROCEDURE
CREATE PROCEDURE update_customer (
    IN id INT,
    IN first_name VARCHAR(50),
    IN last_name VARCHAR(50),
    IN email VARCHAR(100),
    IN phone VARCHAR(20),
    IN address VARCHAR(200)
)
BEGIN
    UPDATE customers
    SET first_name = first_name,
        last_name = last_name,
        email = email,
        phone = phone,
        address = address
    WHERE customer_id = id;
END;
-- DELETE PROCEDURE
CREATE PROCEDURE delete_customer (
    IN id INT
)
BEGIN
    DELETE FROM customers
    WHERE customer_id = id;
END;

You can check out a few more examples at the following resources:

Benefits of CRUD

Instead of using ad-hoc SQL statements, many programmers prefer to use CRUD because of its performance. When a stored procedure is first executed, the execution plan is stored in SQL Server’s procedure cache and reused for all applications of the stored procedure.

When a SQL statement is executed in SQL Server, the relational engine searches the procedure cache to ensure an existing execution plan for that particular SQL statement is available and uses the current plan to decrease the need for optimization, parsing, and recompiling steps for the SQL statement.

Many programmers prefer to use CRUD because of its performance.

If an execution plan is not available, then the SQL Server will create a new execution plan for the query. Moreover, when you remove SQL statements from the application code, all the SQL can be kept in the database while only stored procedure invocations are in the client application. When you use stored procedures, it helps to decrease database coupling.

Furthermore, using CRUD operations helps to prevent SQL injection attacks. By utilizing stored procedures instead of string concatenation to build dynamic queries from user input data for all SQL Statements means that everything placed into a parameter gets quoted.

CRUD Prevents Casual Browsing and Changes

Application roles are a SQL Server technique that lets code switch identities without informing the user. To work with ad hoc SQL statements, users must have the required permissions on the database tables. Once permission is granted, users can read and manipulate data in applications such as Excel, Word, and others. Users can even bypass the application’s business rules.

Yet, this is an unwanted situation that can be prevented through the Application Role. Through integrated security for database access and an Application Role, these types of loopholes can be closed. CRUD comes in since Application roles are added to the database using a stored procedure. It is also implemented by granting permission to execute the CRUD stored procedures and revoking direct access to the tables.

Once an Application Role is added, permissions are assigned, and a password is given. The password is also coded into the application, making it difficult to change. For manipulating data, CRUD is the method to use.

CRUD Operations using NodeJS

Many programmers instead use backend APIs to perform CRUD operations. APIs are flexible, enable API testing, and are much easier to maintain. Let’s build a sample NodeJS application to perform CRUD operations using MySQL DB.

1. Create a DB connection by installing mysql  NPM module.

const mysql = require('mysql');
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'yourusername',
  password: 'yourpassword',
  database: 'yourdatabase'
});
connection.connect((err) => {
  if (err) throw err;
  console.log('Connected to MySQL server!');
});

2. Create a function to add (CREATE), read (READ), update(UPDATE), and delete data (DELETE operation).

function createData(data) {
  connection.query('INSERT INTO your_table SET ?', data, (err, res) => {
    if (err) throw err;
    console.log('New data added:', res.insertId);
  });
}
function retrieveData(id) {
  connection.query('SELECT * FROM your_table WHERE id = ?', [id], (err, res) => {
    if (err) throw err;
    console.log(res[0]);
  });
}
function updateData(id, data) {
  connection.query('UPDATE your_table SET ? WHERE id = ?', [data, id], (err, res) => {
    if (err) throw err;
    console.log('Data updated:', res.affectedRows);
  });
}
function deleteData(id) {
  connection.query('DELETE FROM your_table WHERE id = ?', [id], (err, res) => {
    if (err) throw err;
    console.log('Data deleted:', res.affectedRows);
  });
}

3. Use the functions we just built to perform CRUD operations

const data = { name: 'John Doe', age: 30, email: '[email protected]' };
// create new data
createData(data);
// retrieve data
retrieveData(1);
// update data
updateData(1, { name: 'John Doe' });
// delete data
deleteData(1);

Using SQL Procedures with NodeJS

Developers can also use the SQL procedures directly with NodeJS. Let’s write a function to perform CREATE operation using the SQL procedure we just wrote.

function insertCustomer(first_name, last_name, email, phone, address) {
  return new Promise((resolve, reject) => {
    connection.query(
      'CALL insert_customer(?, ?, ?, ?, ?)',
      [first_name, last_name, email, phone, address],
      (error, results, fields) => {
        if (error) {
          return reject(error);
        }
        return resolve(results[0]);
      }
    );
  });
}

You can call this function (which uses SQL stored procedure) based on your use case.

insertCustomer('John', 'Doe', '[email protected]', '555-1234', '123 Main St.')
  .then(result => {
    console.log(result);
  })
  .catch(error => {
    console.error(error);
  });

Additional Resources and Tutorials on CRUD Operations

For more information on CRUD operations, including tutorials on using and executing CRUD operations effectively with different languages, visit the following links:

Try Stackify’s free code profiler, Prefix, to write better code on your workstation. Prefix works with .NET, Java, PHP, Node.js, Ruby, and Python.

Improve Your Code with Retrace APM

Stackify's APM tools are used by thousands of .NET, Java, PHP, Node.js, Python, & Ruby developers all over the world.
Explore Retrace's product features to learn more.

Learn More

Want to contribute to the Stackify blog?

If you would like to be a guest contributor to the Stackify blog please reach out to [email protected]