Quickstart with CockroachDB Serverless (beta)

This page guides you through the quickest way to get started with CockroachDB. You'll start a free CockroachDB Serverless (beta) cluster, connect with the CockroachDB SQL client, insert some data, and then read the data from a sample application.

For information on how to create a CockroachDB Cloud cluster with other options, see the Learn more section.

Note:

CockroachDB Serverless is currently in beta. For information about its limitations, see CockroachDB Serverless (beta) FAQs.

Step 1. Create a free cluster

  1. If you haven't already, sign up for a CockroachDB Cloud account.
  2. Log in to your CockroachDB Cloud account.
  3. On the Clusters page, click Create Cluster.
  4. On the Create your cluster page, select Serverless.

    Unless you change your monthly budget, this cluster will be free forever.

  5. Click Create cluster.

    Your cluster will be created in a few seconds and the Connection info dialog will display.

  6. Click the Connection string tab in the Connection info dialog and copy the connection string in step 2 to a secure location.

    Warning:

    The connection string in the command is pre-populated with your username, cluster name, and other details, including your password. Your password, in particular, will be provided only once. Save it in a secure place (we recommend a password manager) to connect to your cluster in the future. If you forget your password, you can reset it by going to the SQL Users page.

Step 2. Connect to the cluster

The Connection info dialog shows information about how to connect to your cluster for the client OS.

  1. In the Connection info dialog, choose your OS.
  2. Open a terminal on your local machine.
  3. Run the commands in each step of the Command Line tab of the Connection info dialog.
    1. Run the command in step 1 to install the CockroachDB binary and add it to your OS's PATH.
    2. Run the command in step 2 to download the CA certificate to your local machine.
    3. Run the command in step 3 to connect to your cluster using the SQL client.

You will see a welcome message when you've successfully connected to your cluster:

#
# Welcome to the CockroachDB SQL shell.
# All statements must be terminated by a semicolon.
# To exit, type: \q.
#

Step 3. Insert data

  1. You can now run CockroachDB SQL statements:

    icon/buttons/copy
    > CREATE TABLE messages (id UUID PRIMARY KEY DEFAULT gen_random_uuid(), message STRING);
    
    icon/buttons/copy
    > INSERT INTO messages (message) VALUES ('Hello world!');
    
  2. To exit the SQL shell:

    icon/buttons/copy
    > \q
    

Step 4. Run a sample app

  1. Create an app.js file on your local machine and copy the following code into it:

    icon/buttons/copy
    const parse = require("pg-connection-string").parse;
    const { Client } = require("pg");
    const prompt = require("prompt");
    
    (async () => {
    
      prompt.start()
      const URI = await prompt.get("connectionString");
      var connectionString;
      // Expand $env:appdata environment variable in Windows connection string
      if (URI.connectionString.includes("env:appdata")) {
        connectionString = await URI.connectionString.replace(
          "$env:appdata",
          process.env.APPDATA
        );
      }
      // Expand $HOME environment variable in UNIX connection string
      else if (URI.connectionString.includes("HOME")) {
        connectionString = await URI.connectionString.replace(
          "$HOME",
          process.env.HOME
        );
      }
      var config = parse(connectionString);
      config.port = 26257;
      config.database = 'defaultdb';
      const client = new Client(config);
    
      try {
        await client.connect();
        const result = await client.query('SELECT message FROM messages')
        console.log(result.rows[0].message)
        await client.end()
      } catch (err) {
        console.log(`error connecting: ${err}`)
      }
    
      // Exit program
      process.exit();
    })().catch((err) => console.log(err.stack));
    

    The application:

    1. Attempts to connect to a running cluster, given a connection string.
    2. Reads the sample data you inserted earlier.
    3. Prints the data to the terminal.
  2. Create a package.json file and paste in the following code:

    icon/buttons/copy
    {
      "dependencies": {
        "pg": "latest",
        "pg-connection-string": "latest",
        "prompt": "latest"
      }
    }
    
  3. Initialize and run the application:

    icon/buttons/copy
    npm install
    
    icon/buttons/copy
    node app.js
    

    In the Connection info dialog, go to the Connection string tab, copy the connection string from step 2, and paste it in your terminal.

    prompt: connectionString:
    

    After entering the connection string, the program will execute. The output will look like this:

    Hello world!
    
  1. Install SQLAlchemy.

    icon/buttons/copy
    pip install psycopg2-binary
    
  2. Create a main.py file and copy in the following code:

    icon/buttons/copy
    import logging
    import os
    import psycopg2
    
    def print_hello(conn):
      with conn.cursor() as cur:
          cur.execute("SELECT message FROM messages")
          logging.debug("print_hello(): status message: %s", cur.statusmessage)
          rows = cur.fetchall()
          conn.commit()
          for row in rows:
              print(row[0])
    
    def main():
      conn_string = input('Enter a connection string:\n')
    
      conn = psycopg2.connect(os.path.expandvars(conn_string))
      print_hello(conn)
    
      # Close communication with the database.
      conn.close()
    
    if __name__ == "__main__":
        main()
    

    The application:

    1. Attempts to connect to a running cluster, given a connection string.
    2. Reads the sample data you inserted earlier.
    3. Prints the data to the terminal.
  3. Run the application:

    icon/buttons/copy
    python3 main.py
    

    The program will prompt you for a connection string to the database:

    Enter a connection string:
    
  4. Back in the Connection info dialog, click Connection string, copy the connection string from step 2, and paste it in your terminal after the "Enter a connection string" prompt.

    Note:

    If the connection string does not include your SQL user password, replace <ENTER-PASSWORD> with the password.

    The program will then execute. The output should look like this:

    Hello world!
    
  1. Create a main.go file on your local machine and copy the following code into it:

    icon/buttons/copy
    package main
    import (
        "bufio"
        "context"
        "log"
        "os"
        "github.com/jackc/pgx/v4"
    )
    func readRows(conn *pgx.Conn) error {
        rows, err := conn.Query(context.Background(), "SELECT message FROM messages")
        if err != nil {
            log.Fatal(err)
        }
        defer rows.Close()
        for rows.Next() {
            var message string
            if err := rows.Scan(&message); err != nil {
                log.Fatal(err)
            }
            log.Printf(message)
        }
        return nil
    }
    func main() {
        // Read in connection string
        scanner := bufio.NewScanner(os.Stdin)
        log.Println("Enter a connection string: ")
        scanner.Scan()
        connstring := scanner.Text()
        // Attempt to connect
        config, err := pgx.ParseConfig(os.ExpandEnv(connstring))
        if err != nil {
            log.Fatal("error configuring the database: ", err)
        }
        conn, err := pgx.ConnectConfig(context.Background(), config)
        if err != nil {
            log.Fatal("error connecting to the database: ", err)
        }
      // Read rows
      readRows(conn)
      defer conn.Close(context.Background())
    }
    

    The main method of this program does the following:

    1. Attempts to connect to a running cluster, given a connection string.
    2. Reads the sample data you inserted earlier.
    3. Prints the data to the terminal.
  2. Initialize and run the app:

    icon/buttons/copy
    $ go mod init basic-sample && go mod tidy
    
    icon/buttons/copy
    $ go run main.go
    

    The program will prompt you for a connection string to the database:

    Enter a connection string:
    
  3. Back in the Connection info dialog, click Connection string, copy the connection string from step 2, and paste it in your terminal after the "Enter a connection string" prompt.

    Note:

    If the connection string does not include your SQL user password, replace <ENTER-PASSWORD> with the password.

    The program will then execute. The output should look like this:

    Hello world!
    


  1. Clone the following GitHub repository and check out the serverless branch:

    icon/buttons/copy
    git clone https://github.com/cockroachlabs/hello-world-java-jdbc.git
    cd hello-world-java-jdbc
    git checkout serverless
    
  2. In a text editor modify app/src/main/java/example/app/App.java with the settings from the Connection parameters tab of the Connection info dialog to connect to the cluster:

    icon/buttons/copy

    ds.setServerNames(new String[]{"{host}"});
    ds.setDatabaseName("{database}");
    ds.setUser("{username}");
    ds.setPassword("{password}");
    ds.setSslRootCert(System.getenv("$HOME/.postgresql/root.crt"));
    

    icon/buttons/copy

    ds.setServerNames(new String[]{"{host}"});
    ds.setDatabaseName("{database}");
    ds.setUser("{username}");
    ds.setPassword("{password}");
    ds.setSslRootCert(System.getenv("$HOME/.postgresql/root.crt"));
    

    icon/buttons/copy

    ds.setServerNames(new String[]{"{host}"});
    ds.setDatabaseName("{database}");
    ds.setUser("{username}");
    ds.setPassword("{password}");
    ds.setSslRootCert(System.getenv("%APPDATA%/.postgresql/root.crt"));
    

    Where:

    • {host} is the host for your cluster.
    • {database} is the cluster name and tenant ID plus .defaultdb. For example, funny-duck-3.defaultdb.
    • {username} is the SQL username.
    • {password} is the SQL user password.
    • Make sure ds.setSslRootCert is set to the correct path for your OS to the root.crt CA certificate you downloaded earlier.
  3. Run the application using gradlew:

    icon/buttons/copy
    ./gradlew run
    

    The application connects to the cluster using the JDBC parameters specified in the data source, then executes a SELECT statement and displays the results.

    The output should look like this:

    > Task :app:run
    Hello world!
    
    BUILD SUCCESSFUL in 3s
    2 actionable tasks: 2 executed
    

Next steps

You've successfully created your CockroachDB Serverless (beta) cluster, connected to it using the SQL client, and run some basic SQL statements.

Learn more

This page outlines the quickest way to get started with CockroachDB. For information on other options that are available when creating a CockroachDB Serverless (beta) cluster, see the following:

YesYes NoNo