sqlrefactoring-databases

How to rename SQL table column name(s) and not break stuff


I revisited some of my code from my beginner days and found that some of the SQL table column names are so ambiguous it made me cringe.

Now If I go ahead and change the names, the time and effort required to correct all the mappings in the code doesn't seem justifiable at this point.

I was wondering if its possible to provide an alias at all when inserting to the DB?

I ask because you can use an alias on a SELECT like this:

SELECT users.id, username, number AS order_number FROM users INNER JOIN orders ON users.id = orders.user_id;

Or does anyone have any other suggestions on how I can accomplish this?


Solution

  • While refactoring a database is no doubt a large and risk activity here are some tips to mitigate risk. Below are some suggestions with various pros and cons (as I see the them) hopefully they will help.

    Code

    Depending on your programming language, comfort and time frame you can replace inline direct SQL with a RDBMS independent object relational mapper like Hibernate / NHibernate etc.

    Pros

    Cons

    Stored Procedures

    Depending on your RDBMS you can provide abstraction and additional security to the underlying data and schema using stored procedures.

    Pros

    Cons

    Views

    You could rename your existing table(s) Users and Orders to something else and use a view to offer the column name abstraction.

    Pros

    Cons

    Facade tables Combined with the views suggestion you can create facade tables with revised column naming and security access. When data is inserted into the facade table use triggers as the abstraction mechanism to populate the old tables.

    Pros

    Cons