Skip to content

Language Primitives

/

Data types

Booleans

A boolean (bool) is a primitive type that can be either true or false.

CREATE person SET newsletter = false, interested = true;

Many SurrealDB operators and functions return booleans.

SELECT
    name,
    id,
    name = "Billy" AS name_is_billy,
    name.len() > 20 AS name_is_long
FROM
    CREATE person SET name = "Billy";
Output
[
	{
		id: person:7j4t4higwb141v1v2xum,
		name: 'Billy',
		name_is_billy: true,
		name_is_long: false
	}
]

Boolean values can be written in anycase.

CREATE person SET 
    newsletter = FALSE,
    interested = True,
    very_interested = trUE;

When performing a query on the database, accessing a record's ID directly or using a record range allows performance to be significantly sped up by avoiding the table scan which a WHERE clause on an unindexed field needs.

However, if a WHERE clause is unavoidable, performance can still be improved by simplifying the portion after the clause as much as possible. A field that stores a precomputed value, such as a boolean, avoids calling a function on every record. Compare the field with a literal (is_short = true) rather than testing it on its own (WHERE is_short): a comparison with a literal lets the scan reject a record before decoding it, while a bare field is only tested after the record is decoded.

DEFINE FIELD data_length ON person VALUE random_data.len();
DEFINE FIELD is_short ON person VALUE random_data.len() < 10;

-- Fill up the database a bit with 10,000 records
CREATE |person:10000|
  SET random_data = rand::string(1000) RETURN NONE;
-- Add one outlier with short random_data
CREATE person:one SET random_data = "HI!" RETURN NONE;

-- Function call + compare operation: slowest
SELECT * FROM person WHERE random_data.len() < 10;
-- Stored number compared with a literal: much faster
SELECT * FROM person WHERE data_length < 10;
-- Stored boolean compared with a literal: also much faster
SELECT * FROM person WHERE is_short = true;
-- Direct record access: almost instantaneous
SELECT * FROM person:one;

All SurrealQL values are either truthy or not. While seemingly similar to booleans in that true is a truthy value and false is not, the truthiness of a value extends to all value types and is based on the existence of a concrete value as opposed to empty values, NONE, NULL, and so on. For more information and examples, see this page.

Was this page helpful?