
Defining Data Types and Constraints
Now that we have our Supabase project up and running, it's time to define the structure of our data. Think of this as building the blueprint for your application's information. Supabase uses PostgreSQL under the hood, so we'll be working with SQL data types and constraints.
The Supabase SQL Editor provides a user-friendly interface to manage your database schema. We'll primarily be creating tables and then defining the columns within those tables, specifying their data types and any important rules or constraints they must follow.
Let's start by creating a simple table to store information about our users. We'll name this table users. When defining tables, it's good practice to include a unique identifier, often called a primary key.
CREATE TABLE users (
id uuid PRIMARY KEY DEFAULT uuid_generate_v4()
);In this statement:
CREATE TABLE users: This is the command to create a new table namedusers.id uuid PRIMARY KEY DEFAULT uuid_generate_v4(): This defines a column namedid.uuidis a data type that generates a universally unique identifier.PRIMARY KEYensures that eachidvalue is unique and cannot be null, serving as the main identifier for each row.DEFAULT uuid_generate_v4()automatically generates a new UUID whenever a new row is inserted without an explicitid.
Next, let's add some more common fields to our users table, such as an email address and a timestamp for when the user was created. We'll also enforce that the email must be unique.
ALTER TABLE users
ADD COLUMN email text UNIQUE NOT NULL,
ADD COLUMN created_at timestamp with time zone DEFAULT timezone('utc'::text, CURRENT_TIMESTAMP);Here's what these additions mean:
ALTER TABLE users ADD COLUMN email text UNIQUE NOT NULL: We're adding a column namedemail.textis a flexible data type for strings.UNIQUEmeans no two users can have the same email.NOT NULLensures that every user record must have an email address.ADD COLUMN created_at timestamp with time zone DEFAULT timezone('utc'::text, CURRENT_TIMESTAMP): This adds acreated_atcolumn to record when the user was created.timestamp with time zonestores date and time information along with the timezone.DEFAULT timezone('utc'::text, CURRENT_TIMESTAMP)automatically sets the creation time to the current UTC time if not specified.