To change the column type of nameplate_capacity_mw in the nem_gen_spec table from character varying(255) to a numeric type (e.g., NUMERIC or FLOAT), follow these steps:
✅ Step 1: Check if the data can be safely converted
Run this query to see if any non-numeric values exist (which will block the conversion):
SELECT nameplate_capacity_mw
FROM nem_gen_spec
WHERE nameplate_capacity_mw !~ '^[-+]?[0-9]*\.?[0-9]+$'
AND nameplate_capacity_mw IS NOT NULL;
This regex matches positive/negative integers and floating-point numbers.
If this query returns no rows, you're safe to proceed.
If it does return any rows, you'll need to:
- Remove them
- Or clean them (if fixable)
✅ Step 2: Alter the column type
You can now safely run the column type change. PostgreSQL requires you to explicitly cast the existing text values to numeric:
ALTER TABLE nem_gen_spec
ALTER COLUMN nameplate_capacity_mw
TYPE NUMERIC
USING nameplate_capacity_mw::NUMERIC;
You can change NUMERIC to something more specific like NUMERIC(10,2) or FLOAT, depending on your precision needs:
NUMERIC(10,2) – up to 99999999.99
FLOAT – faster, but floating point (approximate values)
NUMERIC – exact decimal (safe for financial or power measurements)
⚠️ Optional: Backup the column first (safety net)
If you're worried and want a backup before the conversion, run:
ALTER TABLE nem_gen_spec
ADD COLUMN nameplate_capacity_mw_backup character varying(255);
UPDATE nem_gen_spec
SET nameplate_capacity_mw_backup = nameplate_capacity_mw;
👆 This adds a backup column so you can revert if needed.
✅ Step 3 (Optional): Verify the new type
After running the change, confirm the column type:
\d+ nem_gen_spec
or
SELECT column_name, data_type
FROM information_schema.columns
WHERE table_name = 'nem_gen_spec'
AND column_name = 'nameplate_capacity_mw';
✅ Step 4 (Optional): Clean up (remove backup column)
When you're confident everything is working:
ALTER TABLE nem_gen_spec
DROP COLUMN nameplate_capacity_mw_backup;
📌 TL;DR (One-liner if you're sure the data is clean):
ALTER TABLE nem_gen_spec
ALTER COLUMN nameplate_capacity_mw
TYPE NUMERIC
USING nameplate_capacity_mw::NUMERIC;
Let me know if you'd like a script that automatically converts any bad entries to NULL or 0 before transformation.