How do you create a database, tables, users and query data in PostgreSQL?
BeginnerHands-onPostgreSQL
Answer
Short answer
Use SQL inside psql: CREATE DATABASE, CREATE ROLE ... LOGIN, GRANT, CREATE TABLE, INSERT and SELECT. Check your work with \l, \dt and \d.
Step by step
-- 1. Create a user (role) and a database it owns
CREATE ROLE orders_app LOGIN PASSWORD 'Str0ng#Pass';
CREATE DATABASE orders OWNER orders_app;
-- 2. Switch to the new database
\c orders
-- 3. Create a table
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
customer VARCHAR(100) NOT NULL,
amount NUMERIC(10,2) NOT NULL,
status VARCHAR(20) DEFAULT 'NEW',
created_at TIMESTAMPTZ DEFAULT now()
);
\dt
\d orders
-- 4. Insert and read data
INSERT INTO orders (customer, amount) VALUES ('Aditya', 1499.00), ('Priya', 299.50);
SELECT * FROM orders;
SELECT customer, amount FROM orders WHERE amount > 500 ORDER BY created_at DESC;
-- 5. Update and delete (always with WHERE)
UPDATE orders SET status = 'PAID' WHERE id = 1;
DELETE FROM orders WHERE id = 2;
If another user needs read-only access:
CREATE ROLE reporting LOGIN PASSWORD 'R3port#';
GRANT CONNECT ON DATABASE orders TO reporting;
GRANT USAGE ON SCHEMA public TO reporting;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO reporting;
What to say in the interview
"In PostgreSQL, users are roles, so I create one with CREATE ROLE ... LOGIN, create the app's database with that role as owner, and grant other roles only what they need, for example SELECT for reporting. Tables are created with CREATE TABLE, and I verify with \dt and \d. I use these commands mostly to prepare databases for new services and to check data while troubleshooting."
Follow-up questions you may get
- What is a schema in PostgreSQL? A namespace inside a database that groups tables; the default is
public. - How do you see active connections?
SELECT * FROM pg_stat_activity;
More on PostgreSQL
How do you set up PostgreSQL and log in with psql?BeginnerHow do you back up and restore a PostgreSQL database?BeginnerWhat is PostgreSQL and why is it so popular?BeginnerHow is PostgreSQL organised: cluster, database, schema and table?BeginnerHow do you connect to PostgreSQL from the command line?BeginnerWhat are the most useful psql meta-commands?Beginner