Executing CRUD Operations

CRUD stands for:

Create
Read
Update
Delete

These are the four basic operations performed on a database.

CRUD operations are fundamental in:

Web applications
Backend systems
Data engineering
Database management

Almost every software system uses CRUD functionality.

1. Create (Insert Data)

Create operation is used to insert new records into a database.

Example SQL:

INSERT INTO users (name, email)
VALUES ('Ali', 'ali@email.com');

Using Python (Example with PostgreSQL or MySQL):

query = "INSERT INTO users (name, email) VALUES (%s, %s)"
values = ("Ali", "ali@email.com")cursor.execute(query, values)
connection.commit()

Always use parameterized queries to prevent SQL injection.

2. Read (Retrieve Data)

Read operation retrieves data from the database.

Example SQL:

SELECT * FROM users;

With condition:

SELECT * FROM users WHERE id = 1;

Using Python:

cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()for row in rows:
print(row)

Other fetch methods:

fetchone() → One record
fetchmany(n) → Limited records

3. Update (Modify Data)

Update operation changes existing records.

Example SQL:

UPDATE users
SET name = 'Ahmed'
WHERE id = 1;

Using Python:

query = "UPDATE users SET name = %s WHERE id = %s"
values = ("Ahmed", 1)cursor.execute(query, values)
connection.commit()

Always use WHERE clause to avoid updating all rows.

4. Delete (Remove Data)

Delete operation removes records from a table.

Example SQL:

DELETE FROM users WHERE id = 1;

Using Python:

query = "DELETE FROM users WHERE id = %s"
values = (1,)cursor.execute(query, values)
connection.commit()

Be careful when using DELETE without WHERE.

CRUD Flow in Real Application

Example: User Management System

Create:
Add new user

Read:
Display users on dashboard

Update:
Edit user information

Delete:
Remove inactive users

Every web form and admin panel relies on CRUD.

CRUD in REST APIs

In web APIs:

POST → Create
GET → Read
PUT/PATCH → Update
DELETE → Delete

Example:

POST /users
GET /users
PUT /users/1
DELETE /users/1

Best Practices

Always use parameterized queries
Use transactions for critical operations
Validate input data
Handle exceptions
Use proper indexing for performance
Avoid DELETE or UPDATE without WHERE clause

Common Mistakes

Forgetting to commit changes
Not handling errors
Hardcoding user input in queries
Updating all rows accidentally
Not closing database connection

Key Takeaway

CRUD operations are the foundation of database interaction.

Every application that stores and manages data depends on Create, Read, Update, and Delete operations to function properly.

Home » PYTHON FOR DATA ENGINEERING (PYDE) > SQL and Databases with Python > Executing CRUD Operations