Creating a new Supabase table
Learn how to create a new table in Supabase, manage migrations, and use the new table in your Next.js app.
When creating a new feature in your app, you might need to create a new table in your Supabase database. In this guide, we'll learn how to create a new table in Supabase, manage migrations, and use the new table in your Next.js app.
1. Postgres Queries
Let's say you want to create a table to store a list of todos. Here's the PostgreSQL query to create a todos
table:
2. Approaches to Creating Tables
There are two main approaches to creating tables in Supabase:
- Direct SQL Execution: Run the SQL query directly in the Supabase SQL editor (localhost:54323 for local development or in your production Supabase database).
- Using Migrations: Create and manage database changes through migrations, which is the recommended approach for better tracking and version control.
While the first approach is quick, it's not ideal for maintaining and tracking changes over time. Let's focus on the migration approach.
3. Managing Migrations
Nextbase provides commands to create and manage migrations:
Creating a New Migration
To create a new migration:
This command will create a new timestamped SQL file in the supabase/migrations
directory. Open this file and add your SQL query:
Applying Migrations Locally
To apply new migrations to your local database without losing data:
Resetting Local Database
If you need to reset your local database and apply all migrations from scratch:
Pushing Migrations to Production
To push your migrations to the production Supabase database:
This command will apply any new migrations to your production database.
4. Generating Types Locally
After creating or modifying tables, you should regenerate TypeScript types for your Supabase tables. Run the following command:
This command regenerates the types for your local database. The generated types are located at @/src/lib/database.types.ts
.
5. Using Generated Types
Types are crucial for type checking and auto-completion in your IDE. You can use the generated types to type-check your database queries and auto-complete column names.
Example usage:
In this example, data
will be an array of Todo
objects, with types generated from your database schema.
Conclusion
By following this workflow, you can create new tables, manage database changes through migrations, and ensure type safety in your Nextbase project. This approach provides better version control, easier collaboration, and a more maintainable codebase.