Question: How to Create Table in Redis?


Redis is a key-value store and does not have built-in support for tables like traditional relational databases. However, you can still represent table-like structures using Redis data structures like hashes or sets.

A common approach is using Redis hashes to represent rows and columns of a table. Here's an example:

Suppose you want to create a table users with the following structure:

| id | name | email |


| 1 | Alice | |

| 2 | Bob | |

| 3 | Carol | |

To represent this table in Redis, follow these steps:

  1. Use the user id as the key and map it to a Redis hash containing the column names and their respective values.
  2. If you need to query users by email, create a secondary index using a Redis hash that maps email addresses to user ids.

Here's how you would use the redis-cli tool to create the table:

# Add user 1
redis-cli HSET users:1 id 1 name Alice email
# Add user 2
redis-cli HSET users:2 id 2 name Bob email
# Add user 3
redis-cli HSET users:3 id 3 name Carol email

# Create secondary index for emails
redis-cli HSET users:email 1
redis-cli HSET users:email 2
redis-cli HSET users:email 3

With this structure, you can easily fetch a user by id:

redis-cli HGETALL users:1

Or find a user id by email:

redis-cli HGET users:email

Keep in mind that Redis is not designed as a relational database, and complex queries or operations might not be well-suited for Redis. If you require advanced querying capabilities, consider using a dedicated relational database like PostgreSQL or MySQL.

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.