Cursors
SQL

Exploring Cursors and Temporary Tables in SQL

intro

In this comprehensive tutorial, we're going to dive into cursors and temporary tables in SQL using DbVisualizer and explore how they can be used to perform more complex operations on your data. By the end of this tutorial, you'll have a solid understanding of these concepts and be able to use them in your own SQL queries.

Tools used in the tutorial
Tool Description Link
Dbvisualizer DBVISUALIZER
TOP RATED DATABASE MANAGEMENT TOOL AND SQL CLIENT

Prerequisites

Before diving into the tutorial, you should have the following:

  • A basic understanding of SQL queries, including SELECT, FROM, WHERE, GROUP BY, and ORDER BY statements.
  • An SQL database client like DbVisualizer to run your SQL code and manage your database resources.

What are Cursors in SQL?

A cursor is a database object that allows you to traverse the result set of a SELECT statement one row at a time. This can be useful if you need to perform some sort of operation on each row of the result set, such as updating a column or performing a calculation.

Let's start by creating a sample database table that we can use to explore cursors. Here's the SQL code to create a table called "employees" with columns for id, name, and salary:

Copy
        
1 CREATE TABLE employees ( 2 id INT PRIMARY KEY, 3 name VARCHAR(50), 4 salary DECIMAL(10,2) 5 )

We then populate the table using the SQL code below:

Copy
        
1 INSERT INTO employees (id, name, salary) 2 VALUES 3 (1, 'John Doe', 50000.00), 4 (2, 'Jane Smith', 60000.00), 5 (3, 'Bob Johnson', 45000.00), 6 (4, 'Samantha Lee', 55000.00), 7 (5, 'Michael Scott', 70000.00)

Great! We have a basic set of data. Now we will use an SQL client to help us with upcoming steps.

Creating a Table with DbVisualizer

You can also create your database table using DbVisualizer by following these steps:

Step 1 - Connect to your database server as seen in this guide. After establishing a connection, navigate to the “Database” tab, right-click on “Databases” in the connections dropdown, and select “Create Database…” as shown in the image below:

Navigating the database connections dropdown
Navigating the database connections dropdown

Finally, enter a name for your database and click on “Execute,” as shown in the image below:

Creating the database
Creating the database

Step 2 - Create a table by right-clicking on “Tables” in your database dropdown, then clicking on “Create Table”.

Creating a table via a dropdown
Creating a table via a dropdown

Step 3 - Finally, enter a name for your table and the column's properties, then click the “Execute” button to run it.

Creating the employees table
Creating the employees table

Step 4 - Now we want to populate our employees table. Navigate to the employees table , then click on the “+” icon to add a new row of data to the table.

Populating the employees table
Populating the employees table

Step 5 - After populating the table, click on the check mark to save the changes.

Saving the data in the employees table
Saving the data in the employees table

Now that we have our sample table, let's create a cursor to loop through each row and perform a calculation on the salary column. Here's the SQL code to create the cursor:

Copy
        
1 @delimiter %%%; 2 CREATE PROCEDURE update_employee_salary() 3 BEGIN 4 DECLARE id INT; 5 DECLARE done INT DEFAULT FALSE; 6 DECLARE cursor_name CURSOR FOR SELECT id FROM employees; 7 DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; 8 OPEN cursor_name; 9 my_loop: LOOP 10 FETCH cursor_name INTO id; 11 IF done THEN 12 LEAVE my_loop; 13 END IF; 14 UPDATE employees SET salary = salary * 1.05 WHERE id = id; 15 END LOOP; 16 CLOSE cursor_name; 17 END; 18 %%%

The code above gives all employees in a company a 5% raise in their salary. We achieved this by creating a stored procedure named update_employee_salary and declaring some variables to help us loop through the rows in the employees table.

To loop through the rows, we used a cursor named cursor_name to select the id column from the employees table. We then used the OPEN statement to open the cursor and make its results available for the loop.

Inside the loop, we used the FETCH statement to retrieve the next row from the cursor and assign its id value to a variable named id. We then checked whether there were any more rows to fetch using an IF statement. If there were no more rows, we exited the loop using a LEAVE statement.

If there were still more rows to fetch, we updated the salary for the current row by multiplying it by 1.05 using an UPDATE statement. This gave all employees a 5% raise in their salary. We then repeated the loop, fetching the next row from the cursor and updating the salary until there were no more rows left.

Finally, we used the CLOSE statement to close the cursor and free up any resources it was using. We also used the END statement to mark the end of the procedure.

To execute the procedure, we simply called it using the CALL statement, like this:

Copy
        
1 CALL update_employee_salary();

Now let's see the updated salaries for each employee:

Copy
        
1 SELECT * FROM employees

This will return the following result set:

Result set for the update in employees salary
Result set for the update in employees salary

As you can see, the cursor looped through each row of the employees table and multiplied the salary column by 1.05, resulting in a 5% salary increase for each employee.

What are Temporary Tables in SQL?

A temporary table is a table that exists only for the duration of a session or transaction. It can be useful if you need to store intermediate results or perform complex calculations that require multiple steps.

Let's continue with our "employees" table example and create a temporary table to store the intermediate results of a calculation. Let's say we want to calculate the average salary for employees whose salary is greater than 55000. Here's the SQL code to create a temporary table called "temp_employees":

Copy
        
1 CREATE TEMPORARY TABLE temp_employees ( 2 id INT PRIMARY KEY, 3 name VARCHAR(50), 4 salary DECIMAL(10,2) 5 )

We then insert the relevant rows:

Copy
        
1 INSERT INTO temp_employees (id, name, salary) 2 SELECT id, name, salary FROM employees WHERE salary > 55000

Let's break this down.

First, we use the CREATE TEMPORARY TABLE statement to create a temporary table called temp_employees with the same columns as our employees table.

We then use an INSERT INTO statement to insert the relevant rows into the temporary table, selecting only those rows where the salary column is greater than 55000.

Now that we have our temporary table, we can perform the calculation and retrieve the result. Here's the SQL code to calculate the average salary:

Copy
        
1 SELECT AVG(salary) AS avg_salary FROM temp_employees

This will return the following result set:

Result set for the average salary on the temporary employees table
Result set for the average salary on the temporary employees table

As you can see, we were able to use a temporary table to store the relevant rows and perform the calculation without affecting the original "employees" table.

Combining Cursors and Temporary Tables

Now let's see how we can use cursors and temporary tables together to perform a more complex operation. Let's say we have a table called orders with columns id, customer_id, and amount, and we want to calculate the total amount spent by each customer.

Orders table
Orders table

We can combine cursors and temporary tables by using a cursor to loop through each customer_id, and using a temporary table to store the intermediate results. Here's the SQL code to create the cursor and temporary table:

Copy
        
1 @delimiter %%%; 2 CREATE PROCEDURE calculate_customer_totals() 3 BEGIN 4 DECLARE save_customer_id INT; 5 DECLARE done INT DEFAULT FALSE; 6 DECLARE cursor_name CURSOR FOR SELECT DISTINCT customer_id FROM orders; 7 DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; 8 OPEN cursor_name; 9 CREATE TEMPORARY TABLE customer_totals ( 10 customer_id INT, 11 total_amount DECIMAL(10,2) 12 ); 13 my_loop: LOOP 14 FETCH cursor_name INTO save_customer_id; 15 IF done THEN 16 LEAVE my_loop; 17 END IF; 18 INSERT INTO customer_totals (customer_id, total_amount) 19 SELECT save_customer_id, SUM(amount) FROM orders WHERE customer_id = save_customer_id; 20 *-- Fetch the next row of the result set* 21 END LOOP; 22 CLOSE cursor_name; 23 SELECT * FROM customer_totals; 24 END; 25 %%%

The code above gives the total amount spent by each customer on orders by calculating the sum of their order amounts in the orders table. To achieve this, we declared a cursor named cursor_name to select all distinct customer_id from the orders table. We also created a temporary table named customer_totals to hold the results.

Inside the loop, we used the FETCH statement to retrieve the next row from the cursor and assign its customer_id value to a variable named save_customer_id. We then checked whether there were more rows to fetch using an IF statement. If there were no more rows, we exited the loop using a LEAVE statement.

If there were still more rows to fetch, we calculated the total amount spent by the current customer using a SELECT statement with the SUM() function and then inserted the customer_id and total amount spent into the customer_totals table using an INSERT INTO statement.

We repeated the loop, fetching the next row from the cursor and calculating the total amount spent for each customer until there were no more rows left. Finally, we used the CLOSE statement to close the cursor and free up any resources it was using. We also used the SELECT statement to retrieve all the data from the customer_totals table and display it as the result of the stored procedure.

To execute the procedure, we simply called it using the CALL statement, like this:

Copy
        
1 CALL calculate_customer_totals();
Temporary customer_totals table
Temporary customer_totals table

Conclusion

In this tutorial, we've explored cursors and temporary tables in SQL using DbVisualizer. Cursors are like the GPS of SQL - they allow you to traverse the result set of a SELECT statement one row at a time and perform operations on each row. Temporary tables, on the other hand, are like your own personal parking lot in the world of SQL - they allow you to store intermediate results or perform complex calculations without modifying the original table. 🤝

By combining cursors and temporary tables, you can perform more complex operations on your SQL data. But like a good burger and fries 🍔🍟, you don't want to overdo it or it could be too much to handle. So remember to use them sparingly, as they can be resource-intensive and slow down your queries if used improperly.

With DbVisualizer by your side and a better understanding of cursors and temporary tables, you're well-equipped to conquer even the most challenging SQL queries. With its intuitive interface and wide range of features, you can quickly write and execute SQL queries, visualize your data, and optimize your database performance. It's like having your own personal assistant to help you navigate the sometimes tricky world of SQL.

I hope this tutorial was helpful and enjoyable, and that you feel more confident in using cursors and temporary tables in your own SQL queries. Happy querying, my friend! 🕵️‍♀️👨‍💻

FAQ

What are cursors in SQL?

Cursors in SQL are database objects that allow you to traverse the result set of a SELECT statement one row at a time. They are useful when you need to perform operations on each row individually, such as updating a column or performing calculations.

How do I create and use cursors in SQL?

To create and use cursors in SQL, you need to declare a cursor, open it, fetch rows from the cursor into variables, perform operations on the fetched rows, and close the cursor. You can use the FETCH statement to retrieve the next row from the cursor, and a loop construct to iterate through all the rows.

What are temporary tables in SQL?

Temporary tables in SQL are tables that exist only for the duration of a session or transaction. They can be used to store intermediate results, perform complex calculations, or temporarily hold data without affecting the original tables in the database.

How do I create and use temporary tables in SQL?

To create and use temporary tables in SQL, you can use the CREATE TEMPORARY TABLE statement to define the table structure. Temporary tables can be populated with data using INSERT statements or by selecting data from other tables. They can be queried and manipulated just like regular tables but are automatically dropped at the end of the session or transaction.

Can I combine cursors and temporary tables in SQL?

Yes, you can combine cursors and temporary tables in SQL to perform more complex operations on your data. For example, you can use a cursor to iterate through rows in a table and insert or update data in a temporary table based on certain conditions. This allows you to process and analyze the data in a controlled and step-by-step manner.

Dbvis download link img
About the author
Ochuko Onojakpor
Ochuko Onojakpor

Ochuko is a full-stack Python/React software developer and freelance Technical Writer. He spends his free time contributing to open source and tutoring students on programming in collaboration with Google DSC.

The Table Icon
Sign up to receive The Table's roundup
More from the table
Title Author Tags Length Published
title

Automating SQL Queries with SQL CLI and SQL Job Scheduling

author Bonnie tags AUTOMATION SQL 6 min 2025-01-14
title

Understanding the SQL UNIQUE Constraint

author Leslie S. Gyamfi tags DbVisualizer SQL 6 min 2025-01-07
title

SQL CHECK Constraint: Definitive Guide With Examples

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2024-12-16
title

SQL Upsert: Inserting a Record If It Does Not Exist

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2024-12-10
title

How and Why to Add an Index in SQL

author Lukas Vileikis tags MySQL POSTGRESQL Search SQL SQL SERVER 8 min 2024-11-28
title

MySQL 9.0 and the New EXPLAIN Features

author Lukas Vileikis tags MySQL SQL 9 min 2024-11-27
title

Massive SQL DELETE Operations and Database Purging Explained

author Lukas Vileikis tags DELETE SQL 4 min 2024-11-26
title

List of SQL Reserved Words in All Major Databases

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 16 min 2024-11-20
title

A Beginner’s Guide to SQL & Relational Database Management Systems

author Leslie S. Gyamfi tags BEGINNER SQL 5 min 2024-11-19
title

SQL Variable: What It Is and How To Use It

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2024-11-18

The content provided on dbvis.com/thetable, including but not limited to code and examples, is intended for educational and informational purposes only. We do not make any warranties or representations of any kind. Read more here.