CRUD Operations

Master CQL's CRUD operations with comprehensive examples and best practices. Learn to Create, Read, Update, and Delete records using both Active Record and Repository patterns with type-safe, database

Create, Read, Update, Delete – The fundamental building blocks of database interactions in CQL

CQL provides powerful, type-safe CRUD operations that work seamlessly across PostgreSQL, MySQL, and SQLite. Whether you prefer the Active Record pattern for domain-rich applications or the Repository pattern for data-centric architectures, CQL has you covered.

Table of Contents


Quick Start

First, let's set up a basic model to work with:


Create Operations

Instance Creation with new + save

The most fundamental approach - create an instance and save it:

Direct Creation with create

Create and save in one step:

Find or Create

Avoid duplicates with find_or_create_by:


Read Operations

Finding by Primary Key

Finding by Attributes

Aggregations and Counting


✏️ Update Operations

Load, Modify, and Save

Bulk Updates


Delete Operations

Individual Deletion

Bulk Deletion


CRUD Flow Diagram


Repository Pattern

For data-centric applications, CQL also supports the Repository pattern:


Performance Tips

Efficient Queries

Indexing Strategy


Best Practices

Do's

  • Use create! and save! for critical operations where failure should halt execution

  • Validate data before saving to ensure data integrity

  • Use transactions for multi-step operations that must succeed or fail together

  • Handle errors gracefully with proper exception handling

  • Use batch operations for large datasets to improve performance

  • Implement proper indexing for frequently queried columns

Don'ts

  • Don't ignore validation errors - always handle them appropriately

  • Don't use find! without exception handling in user-facing code

  • Don't perform bulk operations without considering performance impact

  • Don't forget to close connections in long-running applications

  • Don't use raw SQL unless absolutely necessary - CQL provides type safety


Further Reading

For detailed Active Record CRUD operations with advanced features, see:


💡 Tip: CQL's CRUD operations are designed to be intuitive and type-safe. Start with the basic patterns and gradually explore advanced features as your application grows!

Last updated

Was this helpful?