What is a database cursor and when should you use one?

Answer

A cursor is a database object that allows row-by-row processing of a query result set. Unlike set-based SQL (which processes all matching rows at once), cursors iterate one row at a time. Declared and used within stored procedures or procedural SQL blocks. Syntax (PostgreSQL): DECLARE cur CURSOR FOR SELECT ...; OPEN cur; FETCH NEXT FROM cur INTO vars; CLOSE cur;. Use cases: when row-by-row processing with complex conditional logic is unavoidable, ETL with per-row transformations. Drawbacks: very slow for large datasets (1000x slower than set-based), consumes server memory, and holds locks longer. Almost always a set-based SQL rewrite (CTEs, window functions, bulk UPDATE) is preferable over cursors.