How to Create Database in 2026: SQL and Managed Options
Learn how to create database tables with SQL commands or a managed tool, then back up, secure and test restores before you store real data.
Your app is finally running locally, the routes return clean JSON, and your hardcoded mock arrays are starting to feel fragile. Now you need real persistence, so you look up how to create database setups that won't break the week you ship. Most tutorials hand you a single CREATE DATABASE statement, tell you to paste an admin password into a config file, and call the job done.
That shortcut costs you later. Running one SQL command gives you an empty shell, not a production-ready datastore. You haven't finished creating a database until your application connects through a scoped role, your schema enforces basic rules, automated backups are running, and you've tested a restore.
Whether you're spinning up a local PostgreSQL server on your laptop or letting an autonomous coding agent provision a hosted instance from your terminal, the same engineering discipline separates reliable setups from midnight fire drills. Let's walk through the commands, design choices, and operational checks that get it right the first time.
Create a Database in Five SQL Commands
If you already have PostgreSQL or MySQL installed locally, five commands give you a working, isolated database with its first structured table. Run these in order inside psql for PostgreSQL or the mysql client for MySQL:
CREATE DATABASE shop;CREATE USER orders_app WITH PASSWORD 'a-long-generated-secret';(orCREATE USER 'orders_app'@'localhost' IDENTIFIED BY 'a-long-generated-secret';in MySQL)GRANT ALL PRIVILEGES ON DATABASE shop TO orders_app;(orGRANT ALL PRIVILEGES ON shop.* TO 'orders_app'@'localhost';in MySQL)\c shopinpsql(orUSE shop;in MySQL)CREATE TABLE customers (id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, email TEXT UNIQUE NOT NULL);
Here is a visual overview of the five-step flow from creating the database container to running your first verification query.

Why Each Command Matters
Naming the database after your application (shop) keeps your project separate from default system databases like postgres or test. Skipping this step means test tables pile up inside a shared default space that becomes risky to drop or migrate later.
Creating a dedicated login role (orders_app) stops your application code from connecting as postgres or root. Generate a long random secret from a password manager, say a random string of at least 20 characters, and store it in an environment variable rather than hard-coding it in source files.
Granting privileges only on shop keeps a compromised app credential from touching other databases on the same server. Never grant superuser rights to an application role, even during local development, because bad habits from local configs have a way of slipping into staging and production.
Switching context with \c shop or USE shop; ensures your tables land inside the right database. Plenty of developers have run a migration script against the wrong target because they forgot to switch sessions first.
Defining the first table with both a primary key and a UNIQUE NOT NULL constraint on email forces the database engine to reject broken rows immediately. Leaving keys off "for now" lets duplicate and orphaned records accumulate until cleaning them up takes an entire afternoon.
PostgreSQL and MySQL Commands Side by Side
Both engines follow the same logic, though their syntax differs slightly for user hostnames, auto-incrementing keys, and session switching.
| Task | PostgreSQL | MySQL |
|---|---|---|
| Create database | CREATE DATABASE shop; | CREATE DATABASE shop; |
| Create application role | CREATE USER orders_app WITH PASSWORD 'a-long-generated-secret'; | CREATE USER 'orders_app'@'localhost' IDENTIFIED BY 'a-long-generated-secret'; |
| Grant rights on the database | GRANT ALL PRIVILEGES ON DATABASE shop TO orders_app; | GRANT ALL PRIVILEGES ON shop.* TO 'orders_app'@'localhost'; |
| Connect to the database | \c shop (inside psql) | USE shop; |
| Create the first table | CREATE TABLE customers (id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, email TEXT UNIQUE NOT NULL); | CREATE TABLE customers (id BIGINT AUTO_INCREMENT PRIMARY KEY, email VARCHAR(255) UNIQUE NOT NULL); |
| Confirm the database exists | \l | SHOW DATABASES; |
Practical rule: If your application connects using the admin account on day one, assume it will still be using that admin account a year from now. Scope the role before you write your first route handler.
Confirming Your Setup Works
Before closing your terminal, verify that the engine created the database and that your new role can read and write to it. Run \l in PostgreSQL or SHOW DATABASES; in MySQL to confirm shop appears in the list.
Next, reconnect as orders_app, insert a single test row with INSERT INTO customers (email) VALUES ('test@example.com');, and read it back with SELECT * FROM customers;. In PostgreSQL 15 and newer, remember that a regular user also needs GRANT CREATE ON SCHEMA public TO orders_app; (or ownership of the schema) to create tables inside public, so testing with the actual app role catches permission gaps right away.
Choose the Engine That Fits Your Data
A billing ledger and a session cache are both "databases," but picking one engine to serve both jobs is how teams end up with Redis as a system of record or a relational schema tortured into storing documents. Match the engine to the shape of your data and the way your application queries it.
The 2024 Stack Overflow Developer Survey shows what working teams run: respondents reported using PostgreSQL at 48.7%, MySQL at 40.3%, SQLite at 33.1%, MongoDB at 24.8%, and Redis at 20.0%. Relational systems dominate because business data almost always has structure and relationships that demand consistency.
| Engine | Best fit | 2024 survey usage | Watch for |
|---|---|---|---|
| PostgreSQL | Structured records with joins, constraints and transactions | 48.7% | Heavier setup and tuning as load grows |
| MySQL | Web applications with relational data and broad hosting support | 40.3% | Check SQL mode and character set when you create the database |
| SQLite | Embedded apps and single-user prototypes | 33.1% | One file with limited concurrent writers |
| MongoDB-compatible | Document-shaped data that changes often | 24.8% | Decide early what to embed and what to reference |
| Redis-compatible | Caching, sessions and fast key-value access | 20.0% | Data lives in memory, so set persistence on purpose |
Matching Workloads to Engines
Use a clear decision rule rather than trying to force one engine to do every job:
- Relational engines (PostgreSQL or MySQL): Choose these whenever records connect to other records and require joins, foreign-key constraints, and multi-step transactions, such as user accounts, orders, or billing ledgers.
- SQLite: Reach for SQLite when building embedded tools, desktop software, or single-user prototypes where a single local file eliminates server administration.
- MongoDB-compatible document stores: Use a document database when your records are nested objects whose fields evolve rapidly across versions, such as product catalogs with unpredictable attributes.
- Redis-compatible key-value stores: Deploy Redis for caching, session storage, queues, or fast counters, and never treat it as the sole authoritative copy of records you can't afford to lose.
The workload decides, but the operational cost decides too. Every engine you adopt is another backup policy to configure, another set of credentials to scope, and another restore procedure to test before you can call the database created. Two well-run databases beat four neglected ones.
If no workload constraint pulls you sharply toward a specialist store, I would default to the relational engine your team and hosting platform already know how to operate. When you're comparing free cloud database options for a new build, write down a two-sentence note in your repository explaining why you chose that engine. Future teammates will know what trade-offs you accepted and when it makes sense to revisit them.
Design Tables, Keys and Relationships First
Typing SQL before you sketch your entities is the fastest way to paint yourself into an expensive migration. The relational model Edgar F. Codd introduced in 1970 still sets the shape: entities become tables, properties become columns, and relationships run through shared keys, while logical queries stay independent of physical disk layout.
Take a small online shop. List the distinct things the app tracks: customers, orders, and order_items. The diagram below shows how those three tables connect through shared identifiers.

Turning Entities into Constrained Tables
Give each table a single surrogate primary key (id) so internal references never break when user-facing data changes. Map each entity's properties into typed columns: email on customers, placed_at on orders, and quantity plus unit_price_cents on order_items.
Connect the tables with foreign keys. Each row in orders carries a customer_id referencing customers(id), and each row in order_items carries an order_id referencing orders(id). The engine then refuses an order for a customer who does not exist.
Normalize transactional data enough that a product name lives in one products table instead of being repeated across thousands of orders. Copy unit_price_cents onto each order_item at the moment of purchase so a catalog price change next month does not rewrite last quarter's receipts. I would take that extra column. A receipt that changes under you later costs more than the storage.
A database is not really created when the tables exist. It is created when the relationships are explicit enough that scoped access, backups, and a restore test still describe the same data. Let the database enforce the invariants rather than trusting application code alone:
- Required fields: Mark columns like
customer_id,placed_at, andemailasNOT NULLso half-formed rows cannot sneak in from a buggy script. - Uniqueness rules: Put a
UNIQUEconstraint oncustomers(email)to prevent duplicate accounts during concurrent sign-ups. - Domain checks: Add a
CHECK (quantity > 0)constraint onorder_itemsso nobody can submit a negative quantity that credits their own balance. - Targeted indexes: Create indexes only for access paths you already know you will run, such as an index on
orders(customer_id)for loading a user's order history.
For a visual walkthrough of how relational keys and normalization rules come together in practice, watch the schema design guide below.
Three Schema Mistakes That Cost Weeks Later
Developers often stuff comma-separated product IDs into a single text column on orders to avoid creating an order_items table. That shortcut saves ten minutes on day one. Every revenue report, refund check, and inventory query gets harder afterward, because the engine cannot join, constrain, or index a list buried in text.
Skipping foreign keys because "the backend validates it" fails the first time a background worker, seed script, or manual hotfix writes directly to the database. Using email as a primary key looks tidy until a customer changes their address and you have to cascade updates across every related table.
As your schema evolves, track every change through versioned migrations and run ANALYZE after major structural updates so the query planner refreshes its table statistics, following standard database migration strategies that test changes against realistic data volumes before touching production.
Each table should answer one clear question, and you should be able to write your first
SELECTquery on paper before running your firstCREATE TABLE.
Create a Managed Database from the Command Line
Running a local PostgreSQL or MySQL instance works well when you're learning SQL or coding on a flight with no Wi-Fi. The moment you share a project with teammates, deploy a hosted web app, or let an autonomous coding agent build features on its own, installing and patching database servers by hand slows everything down.
A managed CLI workflow removes separate dashboard sign-ups and manual copy-pasting of connection strings. Here is how to spin up a hosted database directly from your project repository:
- Open your project folder in a terminal and run
npx extraorbital add postgres. If your workload calls for a document store or cache instead, substitute the service name, such asnpx extraorbital add mongodbornpx extraorbital add redis. - Know when to use
provisionversusadd. Runningprovisionscans the project to detect which services it needs but is missing, whileaddcreates the specific service you name. - Sign in on the connect page that the CLI opens in your browser, select your team and project, and inspect every environment variable name before clicking approve.
- Check your project directory to confirm the CLI wrote the connection details to
.env, or appended them to an existing.env.localfile. - Document only the variable names (such as
DATABASE_URL) in your project README or team notes, never the raw values, and then run one live query from your application to confirm connectivity.
Local Servers Versus Managed Databases
Choosing between local and managed comes down to who (or what) needs access to the data and how much maintenance you want to own. Local engines cost nothing and give you instant resets when experimenting with schema designs.
Managed databases win whenever multiple developers need a shared staging environment, when a hosted application requires reliable uptime, or when coding agents must provision their own infrastructure without stopping to ask a human for provider accounts. You trade full OS-level control for automated patching, network isolation, and consistent credential delivery across environments.
CLI Pitfalls to Avoid
Even a single-command workflow has sharp edges if you rush through it:
- Wrong working directory: Running the add command outside your project root writes connection strings into the wrong
.envfile, which can point one app at another project's database. - Committed secrets: Always verify
.envand.env.localare listed in.gitignorebefore your nextgit add, because pushing a live database URI to a repository forces an immediate credential rotation. - Unverified backups: Assuming a hosted database automatically protects you against accidental
DROP TABLEstatements or bad migrations is a classic mistake; managed hosting handles hardware failures, not human error, unless you configure and test a recovery policy.
Back Up the Database and Prove You Can Restore It
Seeing green checkmarks next to nightly backup jobs creates a dangerous illusion of safety. A backup file sitting in cloud storage proves only that an export script ran, not that you can rebuild a working application when something breaks.
That confidence gap shows up sharply in industry data: in a 2025 survey of more than 3,000 IT professionals reported by Kaseya, 60% believed they could recover in under a day, yet only 35% could. The same report noted that accidental deletion, misconfiguration, hardware failure, and human error remain leading causes of data loss.
Before your production database accepts its first real user, treat backups and recoverability as two distinct engineering deliverables.

Setting RPO and RTO Before Launch
Write down two target numbers before creating your production instance: your Recovery Point Objective (RPO), which is the maximum data gap you can afford to lose, and your Recovery Time Objective (RTO), which is the longest your service can stay down while recovering.
Enable automated full backups, and turn on transaction-log or write-ahead log (WAL) archiving whenever you need point-in-time recovery (PITR) to undo an accidental deletion from ten minutes ago. Operational ranges vary widely with database size; as Azure's PostgreSQL guidance cited in the Runbook Academy PostgreSQL recoverability lesson illustrates, point-in-time restore may achieve an RPO below five minutes, while RTO depends on database size and log replay and can range from minutes to as much as 12 hours.
If you need a deeper look at retention schedules and snapshot tooling, review dedicated database backup configuration patterns alongside your engine's native WAL or binlog documentation.
Running a Real Restore Drill
Schedule a recurring drill in an isolated, disposable environment and execute these six steps in order:
- Pull and restore the latest backup: Download an actual backup artifact into a separate test instance rather than checking whether a file exists in a bucket.
- Replay logs to a chosen timestamp: Roll forward transaction logs to a specific target time or log sequence number (LSN) to prove you can stop right before a simulated bad migration.
- Promote the instance: Bring the restored server out of recovery mode so it accepts live read and write connections.
- Verify data integrity: Check known test records, compare table row counts, and confirm constraints and indexes came back intact.
- Run application smoke tests: Point a staging build of your app at the restored database and execute core flows like signing in and placing a test order.
- Log every elapsed duration: Record retrieval, restore, log replay, validation, and reconnection times. The newest verified record gives you your actual RPO, and total elapsed time until the app responds cleanly gives you your actual RTO.
Pre-Launch Recovery Checklist
Don't mark database setup complete until every item below is checked off:
- Written targets: RPO and RTO numbers are documented in your runbook and agreed upon by the team.
- Automated schedules: Scheduled backups run automatically without manual triggers.
- Log archiving: WAL or binary-log archiving is active if daily snapshots leave too large a data-loss window.
- Calendarized drills: A restore drill sits on a recurring calendar, with past drill timings logged where everyone can see them.
- Encryption and retention: Backups are encrypted at rest and in transit, with explicit retention limits so old archives purge on schedule.
Skip three common traps: checking only that backup files exist, restoring exclusively to the very latest timestamp (which wouldn't help after a bad DELETE), and skipping the application smoke test after the SQL engine starts up.
A database isn't ready for production when it accepts its first write. It's ready when you've timed a full restore into a clean environment and watched your app pass smoke tests against it.
Scope Credentials and Plan Safe Teardown
Sharing one long-lived admin password across developer laptops, CI runners, and AI agent prompts used to be sloppy; today it's a direct invitation to a breach or a wiped production table. As teams hand more provisioning and query tasks to autonomous coding agents, least-privilege access moves from "nice to have" to mandatory.
Developers already feel that tension. According to the 2025 Stack Overflow Developer Survey, 87% of respondents are concerned about AI accuracy and 81% have concerns about AI security and privacy, even as teams increasingly connect agents directly to data stores, repurposing Redis for agent data management (43%) and adopting vector tools such as ChromaDB (20%) and pgvector (18%). When an agent can generate SQL and run migrations automatically, an overly broad credential multiplies the blast radius of a single hallucinated command.
Least-Privilege Rules for Humans and Agents
Build access control around distinct identities and narrow boundaries from day one, applying strong database access control practices before connecting external tools:
- Machine-specific identities: Issue separate credentials for each application service, CI job, and autonomous agent so you can revoke one machine without breaking everything else.
- Purpose-built roles: Create narrow roles matched to the job, such as an
analytics_roread-only role for reporting dashboards and anorders_approle restricted strictly to application tables. - Short-lived or rotated secrets: Set short token lifetimes where supported, and rotate static database passwords on a fixed schedule so leaked secrets expire quickly.
- Strict environment separation: Keep development, staging, and production in completely separate databases so an agent testing a destructive migration can never touch customer data.
- Immutable audit logs: Record credential creation, role changes, and administrative operations in an append-only log that neither developers nor agents can edit.
- Budget and expiry caps: Put automatic lifetime deadlines and spending limits on temporary prototype databases so forgotten experiments don't sit open and accrue bills indefinitely.
Safe Teardown in Five Steps
Knowing how to retire a database cleanly matters just as much as creating one, especially when spinning up disposable environments for feature branches or agent runs. Follow this sequence every time you decommission a database:
- Revoke credentials first: Disable or delete the machine's and application's database credentials so active workers stop writing immediately.
- Scrub environment files: Remove stale connection variables from
.env,.env.local, and deployment secret managers. - Export what matters: Dump any final schema snapshots, audit records, or analytics tables you need for compliance or reference.
- Delete the database deliberately: Destroy the database or project using explicit confirmation. Deleting a project requires typing the project name at a terminal, or using
--yeswithout one; because--yesbypasses that confirmation check, reserve it strictly for teardown scripts you've carefully reviewed. - Audit for orphans: Check your hosting panel or local server to confirm no leftover snapshots, volumes, or unused roles remain behind.
Pick Your Path and Run a First Query
The right path depends on where the database will live. If you're learning SQL or building offline, create your database today with the five SQL commands on a local PostgreSQL or MySQL server. If you need a hosted, shared, or agent-provisioned database, take the managed command-line route instead: ExtraOrbital provisions databases, AI, storage, and auth for a project with one command and no separate accounts to create, and your first team starts on the Free plan with no card required.
Whichever path you pick, resist the urge to jump straight into writing application features. Sketch your entities, primary keys, foreign keys, and constraints on paper before running your first CREATE TABLE so your schema protects your data from the start.
A database isn't really created when the first CREATE statement succeeds. It's created when access is scoped, backups are running, and you've proven a restore works. Complete these three concrete checks before writing real business logic:
- Run a full query cycle: Connect with your scoped application role (never the admin user), insert one test row into your first table,
SELECTit back to verify formatting and permissions, andDELETEit cleanly. - Time one practice restore: Take a snapshot of that test database, restore it into a disposable copy, verify the row count, and log how many minutes the round trip took while the stakes are still zero.
- Record your operational contract: Write down your target RPO, your target RTO, and the exact names of your scoped application roles inside your repository's documentation before you store a single customer record you can't afford to lose.
That restore timing matters more than people expect. If the round trip takes forty minutes on an empty test database, plan for a painful afternoon when a production restore runs under pressure.
Ready to skip juggling separate database dashboards and manual .env edits? ExtraOrbital lets developers and autonomous coding agents provision managed Postgres, MongoDB-compatible, Redis-compatible, and vector databases from one CLI command, complete with scoped machine credentials and audit logs. Start building with your first team on the Free plan at ExtraOrbital.