Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk1 min

How to Create and Manage Tables in PostgreSQL on a VPS

A practical PostgreSQL VPS guide covering table creation, constraints, migrations, ownership, least-privilege grants, row cleanup, TRUNCATE, DROP, dependency review and troubleshooting.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Creating a PostgreSQL table on a VPS is a four-part job: connect to the intended database, define a schema-qualified table with constraints, verify the result, and give application roles only the privileges they need. Managing that table safely means treating changes and deletion as migrations, checking dependencies, and accounting for locks, ownership and backups.

Before you run any table command

Use an administrative shell only long enough to perform administrative work, and use a separate application role for normal queries. You need the PostgreSQL client (psql) or another SQL client, a role permitted to connect to the database, and a database on the VPS in which you intend to work.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do not assume that the database, schema or role selected by a default connection is correct. Confirm all four items before executing data-definition language (DDL).

psql "host=127.0.0.1 port=5432 dbname=appdb user=db_admin sslmode=require"

On a VPS where PostgreSQL listens only locally, host=127.0.0.1 avoids accidentally using a different server. If the database requires a Unix-domain socket, omit host or use the socket directory configured by your installation. Use an encrypted connection whenever the connection crosses a network; the exact TLS settings depend on your PostgreSQL version and VPS configuration.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

Immediately after connecting, run:

SELECT current_database(), current_user, current_schema(), version();
SHOW search_path;

conninfo is a psql command, while the other statements are SQL. Check that the database name, role, schema search path and PostgreSQL version match the migration you are about to run. For production changes, take a tested backup and have a rollback plan before starting.

Create a table with an explicit design

CREATE TABLE creates a new, initially empty table in the current database. If you specify a schema, PostgreSQL creates the table there, and the role executing the statement becomes the table owner. Constraints are tests that inserted or updated rows must satisfy.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Schema-qualify the name so a changed search_path cannot place the object in an unintended schema. This example creates an orders table in an application schema:

CREATE SCHEMA IF NOT EXISTS app;

CREATE TABLE app.orders (
    order_id    bigint GENERATED ALWAYS AS IDENTITY,
    customer_id bigint NOT NULL,
    order_state text NOT NULL DEFAULT 'pending',
    total_cents integer NOT NULL,
    ordered_at  timestamptz NOT NULL DEFAULT now(),
    notes       text,

    CONSTRAINT orders_pkey PRIMARY KEY (order_id),
    CONSTRAINT orders_total_nonnegative CHECK (total_cents >= 0),
    CONSTRAINT orders_state_valid CHECK (order_state IN ('pending', 'paid', 'cancelled'))
);

The identity column supplies a generated numeric value for each new row. A primary key gives every row a stable identity and automatically creates a unique index. NOT NULL rejects missing values; DEFAULT supplies a value only when an insert omits that column; and CHECK constraints encode rules that should not depend solely on application code.

Add relationships deliberately

If a referenced table already exists, add a foreign key to prevent orphaned orders. The referenced column must be a primary key or have a suitable unique constraint.

ALTER TABLE app.orders
    ADD CONSTRAINT orders_customer_fk
    FOREIGN KEY (customer_id)
    REFERENCES app.customers (customer_id);

Choose the foreign-key actions explicitly when the business rule requires them. PostgreSQL's default behavior prevents deletion or key changes that would leave dependent rows. Actions such as ON DELETE CASCADE can remove dependent data and should be used only when that consequence is intentional.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Name important constraints

Names such as orders_total_nonnegative and orders_customer_fk make errors, migrations and support work clearer than automatically generated names. Keep names unique within the namespace required by PostgreSQL and use a consistent convention across the application.

Inspect and test the new table

In psql, inspect both the logical definition and storage-related details:

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.
d app.orders
d+ app.orders

For portable SQL inspection, query the information schema:

SELECT table_schema, table_name, table_type
FROM information_schema.tables
WHERE table_schema = 'app' AND table_name = 'orders';

SELECT column_name, data_type, is_nullable, column_default
FROM information_schema.columns
WHERE table_schema = 'app' AND table_name = 'orders'
ORDER BY ordinal_position;

Constraints can be listed through the information schema or PostgreSQL catalogs:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
SELECT constraint_name, constraint_type
FROM information_schema.table_constraints
WHERE table_schema = 'app' AND table_name = 'orders';

Test both accepted and rejected rows in a staging database. A transaction is useful for a disposable check because it lets you roll back the test data:

BEGIN;

INSERT INTO app.orders (customer_id, total_cents)
VALUES (42, 1250);

-- This should fail because total_cents cannot be negative:
INSERT INTO app.orders (customer_id, total_cents)
VALUES (42, -1);

ROLLBACK;

Do not suppress a failed constraint test and continue a migration in the same transaction without handling the error: after an SQL error, PostgreSQL marks the transaction as aborted until you issue ROLLBACK (or use a savepoint).

Alter a table through controlled migrations

Use ALTER TABLE for structural changes, and record each change in the same migration system used to deploy application code. Coordinate the database change with the version of the application that reads or writes the affected columns.

Add a column safely

ALTER TABLE app.orders
    ADD COLUMN shipped_at timestamptz;

Adding a nullable column without a default is usually the least disruptive form. If existing rows need a value, decide whether that value is true historical data or merely a placeholder. Backfill in controlled batches where appropriate, then enforce a constraint only after the data satisfies it.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Set or change a default

ALTER TABLE app.orders
    ALTER COLUMN order_state SET DEFAULT 'pending';

Changing a default affects future inserts; it does not rewrite existing rows. If existing records also need changing, perform a separate, reviewed UPDATE and verify its scope.

Rename a column

ALTER TABLE app.orders
    RENAME COLUMN notes TO customer_notes;

A rename is metadata-only, but queries, views, functions, reports and application code may still refer to the old name. Deploy compatibility changes in an order that keeps the running application functional.

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Add a constraint after cleaning data

ALTER TABLE app.orders
    ADD CONSTRAINT orders_total_nonnegative
    CHECK (total_cents >= 0);

PostgreSQL checks existing rows when a new constraint is added. If violations exist, the command fails. Find and correct the violating rows first. For very large tables or busy systems, investigate the lock and validation behavior for your PostgreSQL version and workload before scheduling the migration.

Change a type or remove a constraint

ALTER TABLE app.orders
    ALTER COLUMN total_cents TYPE bigint
    USING total_cents::bigint;

ALTER TABLE app.orders
    DROP CONSTRAINT orders_state_valid;

A type conversion can rewrite data and hold locks, and the USING expression must produce a valid value for every row. Dropping a constraint removes a database guarantee; make sure an alternative validation exists before doing so.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Plan for locks and runtime

Most table changes require a lock, and the duration depends on the operation, table size, indexes, concurrent workload, PostgreSQL version and VPS resources. Check active sessions and schedule disruptive work during a maintenance window when necessary. Keep transactions containing DDL short, avoid waiting indefinitely behind an open transaction, and monitor the migration rather than assuming it is instantaneous.

Separate ownership from application privileges

Ownership determines who can alter or drop an object. It is different from the privileges an application needs to read or modify rows. PostgreSQL table privileges include SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES and TRIGGER.

Create an owner role that is used for migrations, and a runtime role with only the required permissions. For example:

CREATE ROLE app_owner NOLOGIN;
CREATE ROLE app_runtime LOGIN PASSWORD 'use-a-secret-managed-outside-source-control';

ALTER TABLE app.orders OWNER TO app_owner;

GRANT USAGE ON SCHEMA app TO app_runtime;
GRANT SELECT, INSERT, UPDATE ON TABLE app.orders TO app_runtime;
GRANT USAGE, SELECT ON SEQUENCE app.orders_order_id_seq TO app_runtime;

The sequence grant is needed when an identity or serial-backed key is implemented through a sequence and the runtime role must obtain generated values. Inspect the actual sequence name and privileges in your PostgreSQL version instead of assuming a naming pattern.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Grant only the operations the application performs. A reporting role may need SELECT but not INSERT, while a job that purges rows may need DELETE. Granting TRUNCATE is especially powerful because it removes all rows without requiring row-by-row delete privileges.

Do not rely on a broad PUBLIC grant. PostgreSQL grants no privileges to PUBLIC by default on tables, table columns, sequences, foreign data wrappers, foreign servers, large objects, schemas, tablespaces or configuration parameters. Review any explicit grants that your installation or provisioning scripts may have added:

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.
dp app.orders
SELECT grantee, privilege_type
FROM information_schema.role_table_grants
WHERE table_schema = 'app' AND table_name = 'orders';

Use column-level grants when necessary

If a role should update only selected fields, grant specific columns rather than the whole table:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
GRANT SELECT (order_id, customer_id, order_state, total_cents, ordered_at),
      UPDATE (order_state)
ON app.orders TO app_runtime;

Column grants do not replace schema access, and they do not grant sequence access. Test the complete application workflow with the runtime role rather than testing only a single query as an administrator.

Set default privileges for future tables

Explicit grants apply to existing objects. When one owner role repeatedly creates tables for an application, configure default privileges for objects that role will create in the future:

ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA app
    GRANT SELECT, INSERT, UPDATE ON TABLES TO app_runtime;

ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA app
    GRANT USAGE, SELECT ON SEQUENCES TO app_runtime;

Default privileges are tied to the object-creating role. Running the command as a different administrator, or omitting FOR ROLE app_owner, can configure the wrong owner. These defaults do not change privileges on tables that already exist, so review and correct existing grants separately.

Choose between deleting rows and deleting the table

Decide first whether you need to retain the table definition. The commands have materially different effects:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Operation Rows retained? Object retained? Dependency behavior Typical use
DELETE FROM app.orders WHERE ... Only rows matching the predicate are removed Yes Foreign-key and trigger rules apply row by row Selective or auditable data removal
TRUNCATE TABLE app.orders No rows remain Yes Requires appropriate privilege; referenced tables may block truncation unless handled explicitly Fast reset of a table when all data can be discarded
DROP TABLE app.orders RESTRICT No No Fails if dependent objects exist; RESTRICT is the default Remove the table only after dependencies are cleared
DROP TABLE app.orders CASCADE No No Removes dependent objects as well Intentional teardown after reviewing every dependent object

Remove selected rows with DELETE

DELETE FROM app.orders
WHERE order_state = 'cancelled'
  AND ordered_at < now() - interval '2 years';

Always run the predicate as a SELECT first, inspect the count and keep a backup or audit trail required by your retention policy. An omitted WHERE clause deletes every row.

Empty a table with TRUNCATE

TRUNCATE TABLE app.orders;

-- If identity values should restart as well:
TRUNCATE TABLE app.orders RESTART IDENTITY;

TRUNCATE is a table-level operation and can block or be blocked by concurrent work. Foreign-key relationships can prevent it unless all affected tables are included or the constraint is handled deliberately. Test the exact statement in staging; never use it as a substitute for a targeted delete when records must be retained.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Drop a table only after a dependency review

DROP TABLE removes the table, its indexes, rules, triggers and constraints. Before dropping it, identify foreign keys, views, materialized views, functions, triggers, jobs and application code that refer to it. In psql, start with:

d+ app.orders

Attempting a protected drop is safer than guessing:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
DROP TABLE app.orders RESTRICT;

If PostgreSQL reports dependencies, inspect each one and decide whether to migrate, remove or preserve it. Use CASCADE only when you have reviewed the complete dependency list and intend to remove those dependent objects:

DROP TABLE app.orders CASCADE;

A drop is not a reset. If you need the schema, indexes, constraints and grants to remain, use DELETE or TRUNCATE instead. If you need a reversible experiment, perform it in a transaction where the operation and all dependent changes are supported by your migration plan, and keep a tested backup for failures outside that transaction.

A migration workflow that works on a VPS

  1. Identify the target. Connect with the intended host, port, database and role, then verify current_database(), current_user, current_schema() and version().
  2. Review the change. Confirm whether it creates an object, changes data, changes privileges or removes dependencies. Check application compatibility and expected lock behavior.
  3. Back up and rehearse. Use the backup system configured for the VPS and restore it to a test database when possible. Run the migration and its rollback or recovery procedure there.
  4. Apply the smallest safe step. Use schema-qualified names, explicit constraint names and a short transaction. Avoid bundling unrelated destructive operations.
  5. Verify structure and behavior. Inspect with d or catalog queries, test permitted and rejected operations, and check grants using dp.
  6. Deploy application code in a compatible order. For additive changes, create the new structure before code depends on it. For removals or renames, stop old code from referencing the object before deleting it.
  7. Monitor and document. Record the migration version, owner, grants, expected dependencies and recovery action. Watch sessions and logs for lock waits or constraint failures.

VPS security and reliability checks

  • Expose PostgreSQL only to networks that must connect. Keep administrative access separate from application access and review firewall rules with the VPS provider's documentation.
  • Use encrypted client connections when traffic leaves the host. Certificate, pg_hba.conf, server-listener and certificate-authority settings are version- and environment-specific.
  • Store credentials outside source control, rotate them, and avoid using a superuser in application configuration.
  • Maintain backups that include the database objects and data needed for recovery, and test restoration rather than assuming a successful backup command proves recoverability.
  • Keep PostgreSQL and the VPS operating system patched according to a maintenance policy compatible with your application.

Troubleshooting common failures

“relation does not exist”

Check the database and schema first. An unqualified name follows search_path, so app.orders may exist while orders does not resolve. Use dt *.* in psql or query information_schema.tables.

“permission denied for schema”

The role may have table privileges but lack USAGE on the containing schema. Grant schema usage separately, and verify that the role is connecting to the intended database.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

“permission denied for sequence”

An insert that uses an identity or sequence-backed key may require sequence privileges in addition to table privileges. Inspect the sequence attached to the column and grant only the required sequence rights.

“must be owner of table”

Table privileges do not normally grant structural ownership. Run the migration as the owner or a role permitted to assume that ownership, rather than giving the runtime role broad administrative rights.

“cannot drop table because other objects depend on it”

Keep RESTRICT, inspect each reported dependency, and remove or migrate dependents deliberately. Do not switch to CASCADE merely to make the error disappear.

A migration is waiting or appears hung

The operation may be waiting for a lock held by another transaction. Find long-running or idle-in-transaction sessions, coordinate with the workload owner, and choose a maintenance window if the change cannot safely run concurrently. The time required is workload- and schema-dependent; there is no universal VPS duration.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Useful checks after every change

  • d+ schema.table shows columns, indexes, constraints and storage details in psql.
  • SELECT current_user; confirms which role is executing subsequent commands.
  • dp schema.table exposes table and column grants.
  • A representative insert, update, select and delete performed as the application role confirms the intended least-privilege boundary.
  • A rejected insert that violates each important NOT NULL, UNIQUE, CHECK and foreign-key rule confirms that the database, not only the application, enforces the rule.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.