Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create and update your SQL scripts?

I'm wondering what is the best way to create and maintain databases maps and SQL scripts. I know I'm more a fan of writing the SQL script by hand on a text editor (plus designing a map to have next to me on a piece of paper), while others prefers to use database maps softwares (MySQL Workbench, Visual Studio... some listed in this post) to automatically generate the script.

Both solutions have advantages and drawbacks. I see these advantages:

  • SQL script by hand:
    1. You know exactly what you write.
    2. You are able to keep a clean and easily readable SQL code.
    3. Writing the code, you keep a better view of your database specifics.
    4. Writing the code enables you to to practive your SQL knowledge.
  • Automatically generated script from designed map:
    1. Saves some time.
    2. Even without knowing SQL language, you can generate a script (even if I listed this one as an contrary advantage for SQL script by hand).
    3. Prevents typos.

What do you think, what way do you proceed?

like image 928
Otiel Avatar asked Jul 04 '11 09:07

Otiel


1 Answers

If automating something saves time and human error why wouldn't you do it? I would try auto-generating SQL if:

  1. I had already populated a test database and built up the schema in an organic fashion by writing and executing ad hoc SQL non-queries which I hadn't kept track of; and
  2. If the database was reasonably simple and with a low amount of normalisation

Another rare case might be if you had a massive list of data sets for which the schema needed to be extracted in the form of SQL.

The benefits of writing by hand are that you are aware of every part of the design and better able to enforce data integrity (for instance through use of foreign keys or limiting data types). In short, I would agree with your list of pros.

For upgrade scripts I strongly prefer writing these by hand because they're usually fairly short and it's nice for them to be more readable for the people who end up running them.

One tip I'd have for upgrade scripts is to make sure each script adds a row stating the upgrade version number in a table which is exclusively there to ensure the database is versioned correctly. Something like:

INSERT INTO DB_VERSION (upgrade_time, version_from, version_to, comment)
    VALUES ('2011-07-04T120320', '2.2.4', '2.3', 'add column x to table y.')
like image 174
Lisa Avatar answered Sep 27 '22 21:09

Lisa