Jed Rembold
Monday, October 13, 2025
psql issues? I posted something
on Discord, but will summarize.UPDATE statementSET keyword, either:
SET |||col₁||| = 5, |||col₂||| = |||col₃|||SET (|||col₁|||, |||col₂|||) = (5, |||col₃|||)
The table named revq to the right is acted
upon by the below SQL queries. What entries in the table are left
untouched once all queries have been run?
ALTER TABLE revq ADD COLUMN row4 INT;
UPDATE revq SET row4 = row2;
UPDATE revq SET (row2,row3)=(row3, row2) WHERE row1 IN ('B','C');
UPDATE revq SET row3 = row3 - row4;
UPDATE revq SET row2 = row2 + row4 WHERE row3 > 10;
ALTER TABLE revq DROP COLUMN row4;
Frequently, if you are about to heavily modify a table, you should consider working on a backup copy
We actually have already seen the basic machinery for this:
CREATE TABLE |||new_table||| AS
SELECT * FROM |||og_table|||;
For including constraints and indexes, you can use a Postgres specific syntax, but the newly created table will initially be missing the data
CREATE TABLE |||new_table|||
(LIKE |||og_table||| INCLUDING ALL);In some cases, you’ll want to update or pass information across tables
In core SQL, you’d need to use subqueries, which we’ll be talking about in a few chapters
In Postgres, to update, you can use
FROM:
UPDATE |||table₁|||
SET |||col_name||| = |||table₂|||.|||col₂|||
FROM |||table₂|||
WHERE |||table₁|||.|||col₁||| = |||table₂|||.|||col₁|||;To insert values from another table into another:
INSERT INTO |||new_table||| SELECT * FROM |||old_table|||;DROP for removing structural aspects of a
table like columns, constraints, indexes, or the table itselfDELETE FROM for removing content (rows)
from tablesDROP will frequently come after an
ALTER TABLE unless you are dropping the table
itselfDELETE FROM without a filter will
delete all rows
ALTER TABLE |||table name||| DROP COLUMN |||col_name|||;
ALTER TABLE |||table name||| DROP CONSTRAINT |||const_name|||;
DROP INDEX |||index_name|||;
DROP TABLE |||table name|||;
DELETE FROM |||table name|||; -- All rows gone!
DELETE FROM |||table name||| WHERE |||condition|||;
START TRANSACTION; or
BEGIN;COMMIT; actually makes the changesROLLBACK; throws out everything within
the transaction