Debug School

rakesh kumar
rakesh kumar

Posted on • Edited on

How to delete particular row from postgress pgsql using commands

Enter PostgreSQL
Show all databases
Connect to a particular database
delete all rows from table

Enter PostgreSQL

sudo -u postgres psql
Enter fullscreen mode Exit fullscreen mode

Show all databases

Inside psql:

\l
Enter fullscreen mode Exit fullscreen mode

or:

\list
Enter fullscreen mode Exit fullscreen mode

Exits PostgreSQL completely and returns to the Linux terminal.

\q
Enter fullscreen mode Exit fullscreen mode

Example:

hl_booking
hl_country
hl_profile
hl_trip
postgres
Enter fullscreen mode Exit fullscreen mode

Connect to a particular database

For example:

\c hl_booking
Enter fullscreen mode Exit fullscreen mode

You should see:

You are now connected to database "hl_booking".

Then show all tables:

\dt
Enter fullscreen mode Exit fullscreen mode

Suppose your table name is bookings.

delete all rows from table

To delete all rows but keep the table structure:

DELETE FROM availability_slots;
Enter fullscreen mode Exit fullscreen mode
SELECT * FROM bookings;
Enter fullscreen mode Exit fullscreen mode
SELECT * FROM bookings LIMIT 10;
Enter fullscreen mode Exit fullscreen mode
SELECT *
FROM bookings
WHERE status = 'confirmed';
Enter fullscreen mode Exit fullscreen mode
INSERT INTO bookings
(user_id, status)
VALUES
(10, 'pending'),
(11, 'confirmed'),
(12, 'cancelled');
Enter fullscreen mode Exit fullscreen mode
UPDATE bookings
SET status = 'confirmed'
WHERE id = 10;
Enter fullscreen mode Exit fullscreen mode
UPDATE bookings
SET
    status = 'confirmed',
    updated_at = NOW()
WHERE id = 10;
Enter fullscreen mode Exit fullscreen mode
DELETE FROM bookings
WHERE id = 10;
Enter fullscreen mode Exit fullscreen mode

DELETE FROM bookings
WHERE id = 10
RETURNING *;
Enter fullscreen mode Exit fullscreen mode

To see all fields/columns of a particular PostgreSQL table, use:

## \d bookings
Enter fullscreen mode Exit fullscreen mode
DELETE FROM users
WHERE kc_user_id IS NULL
   OR kc_user_id NOT IN (
       '6b4bc082-3329-4973-8493-d70cdc2eab4a',
       '0c2c40d7-cf4e-4868-bb50-0425267035fd',
       'a2132c98-b754-4d30-9ec1-18f43ecd5041',
       'bd15ebc7-3e38-418a-a496-f6bfe5dc42d0'
   );
Enter fullscreen mode Exit fullscreen mode
DELETE FROM organizer_profiles
WHERE kc_user_id IS NULL
   OR kc_user_id NOT IN (
       '6b4bc082-3329-4973-8493-d70cdc2eab4a',
       '0c2c40d7-cf4e-4868-bb50-0425267035fd',
       'a2132c98-b754-4d30-9ec1-18f43ecd5041',
       'bd15ebc7-3e38-418a-a496-f6bfe5dc42d0'
   );
Enter fullscreen mode Exit fullscreen mode
SELECT * FROM users;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)