SELECT

Introduction and Use Case(s)

The SELECT command in Redis is used to switch the current connection to a different logical database. Redis supports multiple databases, which are identified by their numeric indices. This command is especially useful when you want to logically separate data within a single Redis instance.

Syntax

  1. SELECT index

Parameter Explanations

  • index: The zero-based numeric index of the database to be selected. Redis typically has 16 databases by default, indexed from 0 to 15.

Return Values

  • OK: Indicates that the database switch was successful.

Example

  1. dragonfly> SELECT 1
  2. OK
  3. dragonfly> SET key "value"
  4. OK
  5. dragonfly> SELECT 0
  6. OK
  7. dragonfly> GET key
  8. (nil)
  9. dragonfly> SELECT 1
  10. OK
  11. dragonfly> GET key
  12. "value"

Code Examples

  1. dragonfly> SELECT 2
  2. OK
  3. dragonfly> SET mykey "hello"
  4. OK
  5. dragonfly> SELECT 3
  6. OK
  7. dragonfly> GET mykey
  8. (nil)
  9. dragonfly> SELECT 2
  10. OK
  11. dragonfly> GET mykey
  12. "hello"

Common Mistakes

  • Invalid Index: Trying to select a database index that does not exist will result in an error. Ensure the index is within the configured range.

Example

  1. dragonfly> SELECT 16
  2. (error) ERR DB index is out of range

FAQs

How many databases can I have in Redis?

By default, Redis allows 16 databases (indexed 0-15), but this can be changed in the configuration file (redis.conf) by setting the databases directive.

Can different connections use different databases simultaneously?

Yes, each connection can select its own database independently of other connections.