Skip to main content

Description

Returns the number of keys in the currently selected database.

Method Signature

dbsize(): Promise<number>

Parameters

This command takes no parameters.

Return Value

result
number
The number of keys in the database

Examples

Get database size

const size = await redis.dbsize();
console.log(`Database contains ${size} keys`);

Monitor database growth

const before = await redis.dbsize();
console.log(`Keys before: ${before}`);

await redis.set("key1", "value1");
await redis.set("key2", "value2");
await redis.set("key3", "value3");

const after = await redis.dbsize();
console.log(`Keys after: ${after}`);
console.log(`Added ${after - before} keys`);

Check if database is empty

const size = await redis.dbsize();
if (size === 0) {
  console.log("Database is empty");
} else {
  console.log(`Database has ${size} keys`);
}

Track deletes

await redis.set("temp1", "value");
await redis.set("temp2", "value");
await redis.set("temp3", "value");

const before = await redis.dbsize();
await redis.del("temp1", "temp2", "temp3");
const after = await redis.dbsize();

console.log(`Deleted ${before - after} keys`);

Performance

DBSIZE is an O(1) operation - it returns the count instantly without scanning the keyspace.

See Also

  • keys - Find all keys matching a pattern
  • scan - Incrementally iterate over keys
  • flushdb - Delete all keys in the database

Build docs developers (and LLMs) love