r/learnSQL • u/Klutzy-Macaroon-5081 • Jun 08 '26
Is there a cleaner/shorter way of making updates for data like this?
UPDATE hr_employee_staging
SET Education = 'Below College'
WHERE Education = '1';
UPDATE hr_employee_staging
SET Education = 'Some College'
WHERE Education = '2';
UPDATE hr_employee_staging
SET Education = "Bachelor's Degree"
WHERE Education = '3';
UPDATE hr_employee_staging
SET Education = "Master's Degree"
WHERE Education = '4';
UPDATE hr_employee_staging
SET Education = 'Doctorate Degree'
WHERE Education = '5';
9
Upvotes
2
u/Ginger-Dumpling Jun 09 '26
Why are you updating it? Is the data wrong? Do you have a mix of "ids" and descriptions and you're making them uniform? Did you change your mind in what your want it to look like?
It looks like you have an education_level_id that's an integer in a varachar column, and you're replacing it with a textual description of that level. Do you not have an education_level table that has both id/description that you can join to and swap one column for another at read time?
Someone posted doing it as a case statement. If you're in a situation that would benefit from it, your could add a where condition to only select the values being updating.
Someone else also noted that it looks like it's a staging table...part of an ETL process? Is this a one time fix, or does the process regularly insert and then do a bunch of updates? If that's the case, you may want to just stop doing that and fix you mapping so it inserts with the ultimate value that you want.
2
u/Massive_Show2963 Jun 09 '26
As was mentioned introduce a case statement and include this in a transaction:
BEGIN TRANSACTION
UPDATE hr_employee_staging
SET Education =
CASE Education
WHEN '1' THEN 'Below College'
WHEN '2' THEN 'Some College'
WHEN '3' THEN 'Bachelor''s Degree' --- apostrophes inside strings are escaped by doubling them
WHEN '4' THEN 'Master''s Degree'
WHEN '5' THEN 'Doctorate Degree'
END
WHERE Education IN ('1', '2', '3', '4', '5');
COMMIT
1
u/r3pr0b8 Jun 09 '26
if you were to create a small table with those numeric codes and their translations, you could do a joined update
sql syntax varies by database platform, do a quick search in your sql manual
1
u/mu_SQL Jun 10 '26 edited Jun 10 '26
Use a temptable or derived table and Join on Education.
CREATE TABLE #EducationMap
(
EducationCode VARCHAR(10),
EducationDesc VARCHAR(50)
);
INSERT INTO #EducationMap (EducationCode, EducationDesc)
VALUES
('1', 'Below College'),
('2', 'Some College'),
('3', 'Bachelor''s Degree'),
('4', 'Master''s Degree'),
('5', 'Doctorate Degree');
UPDATE s
SET s.Education = m.EducationDesc
FROM hr_employee_staging s
INNER JOIN #EducationMap m
ON s.Education = m.EducationCode;
DROP TABLE #EducationMap;
1
u/[deleted] Jun 08 '26
[removed] — view removed comment