🗓️ 01102024 0944
📎 #mysql
Overview
NOTE
a database object used to retrieve, manipulate, and traverse over a set of rows resulting from a query
- Allow row-by-row processing of result sets, giving developers the ability to apply procedural logic to each row
| Standard SQL query | SQL Cursor |
|---|---|
| Operate on entire sets of data at once | Allow more granular control over how data is accessed / processed |
When to Use
SQL cursors are useful in situations where:
- You need to iterate through a result set row-by-row and apply specific logic to each row.
- Dealing with procedural logic
- Can't be easily expressed in a single SQL query (e.g., complex transformations, multi-step updates)
- Want to process the result set in smaller chunks
- Avoid loading the entire dataset into memory, especially for large datasets
INFO
Refer to mysql_cursor_lifecycle for how to use a cursor
Types
SQL supports various types of cursors
Differ based on how they handle the underlying data and whether they allow modifications
Implicit Cursors
- Automatically created by the SQL engine to handle single-row queries like
SELECT INTO - Used for simple, single-row queries
- Less control for the developer, but are lightweight and automatic
Explicit Cursors
- Declared by the developer for multi-row queries where row-by-row processing is required.
- More control is given to the developer in terms of how to open, fetch, and close the cursor.