Try Tuts+ Premium, Get Cash Back!
Visual Database Creation with MySQL Workbench

Visual Database Creation with MySQL Workbench

Tutorial Details
  • Program: MySQL Workbench
  • Difficulty: Beginner

In today’s tutorial, you’ll learn how to use a visual database modeling utility to draw a database diagram and automatically generate SQL. Specifically, we’ll review how to use MySQL Workbench, a cross-platform, visual database design tool.


What is MySQL Workbench?

MySQL Workbench is a powerful tool developed by MySQL with three primary areas of functionality:

  • SQL Development: Replaces MySQL query browser. Allows the user to connect to an existing database and edit and execute SQL queries.
  • Data Modeling: Complete visual database design and modeling.
  • Database Administration: Replaces MySQL administrator. Graphic interface to start/stop servers, create user accounts, edit configuration files, etc.

In this tutorial, we’ll focus on the Data Modeling aspect to create a database from scratch, and then have just a quick look at the SQL editor to execute our generated SQL script and create the database within MySQL.

MySQL Workbench is available for Windows, Linux and Mac OSX. There are two different editions: the Community OSS Edition and the commercial Standard Edition. The community edition is Open Source and GPL licensed, as you’d expect. It’s fully functional, and is the one we’ll be using in this article. The commercial edition adds some extra functionalities, such as schema and model validation or documentation generation.

Note: this tutorial is based on the Community OSS Edition version 5.2 (5.2.16), currently in beta release at the time of the writing (April 2010).


Planning our Database

To learn how to use MySQL Workbench, we’ll use a very simple database for online classes as an example. Suppose a group of teachers want to offer online classes for several subjects, using Skype or any other video conferencing software. For our little project, we have decided that we need to store the following information:

When drawing our diagram, we will need to know the relationships between these groups of data as well; so we better think about that now!

  • One teacher can teach many subjects
  • One subject can be taught by many teachers
  • Each class has only one teacher
  • One teacher can teach many classes
  • One student can attend many classes
  • One class has many students
  • One class may have several hours (in a week)
  • At one particular day and hour, there may be several classes
  • A class is about one subject
  • One subject may be taught in many classes

At this point, we have all the information we need to meet the star of this show…


Send in MySQL Workbench

It’s time to launch Workbench. In the data modeling part of the home screen, we click ‘Create new EER Model’, and the following screen appears:

When we create a new database model, it contains the default mydb schema. We can rename it and use it as our DB schema. A database model can have several different schemas.

The catalog on the right will show every element in our schema, and allow us to drag and drop elements to diagrams if needed.

Having the separate sections for Physical Schemata and EER Diagrams, and the possibility to include several Schemas in one database model may be confusing. The next section explains these concepts and how they are related.


Clarifying Concepts

The physical schema contains all the necessary pieces to define the database: tables, columns, types, indexes, constraints, etc. This is what we are really defining. Every object added in the graphical model also shows up in the physical schema. It is, in fact, a visual way to define our schema.

We can have several schemas for the same database model in the same way we can have several databases in a MySQL server. Each schema will be a MySQL database. For example, in the next screen, we have two schema tabs:

If we generate the SQL script, we will have two separate CREATE DATABASE statements – actually we will have CREATE SCHEMA which is just a synonym.

CREATE SCHEMA IF NOT EXISTS `schema1`;
CREATE SCHEMA IF NOT EXISTS `schema2`;

“EER stands for Extended (or Enhanced) Entity-Relationship. EER diagrams are just a way to model the data and the relationships between data using standard symbols”

They will be listed as databases within the MySQL server host when using SHOW DATABASES.

Now, what is an EER Diagram?. EER stands for Extended (or Enhanced) Entity-Relationship>. EER diagrams are just a way to model the data and the relationships between data using standard symbols. EER models can be complex, but MySQL Workbench uses only a subset of all possible graphical elements, because the purpose of this diagram (in this tool) is to have every element mapped to the physical schema.

We can use an EER diagram to define the whole database, or just small parts. For example, we can have a schema with five tables defined, and then create a new diagram to define two more tables using the visual editor. The diagram will contain only two tables, but those two tables will also be included in the schema, together with the previous five.


Creating our Tables

Back to our initial example; we have to rename the default schema by double clicking the name. At this point, we have two possibilities: we can start adding tables to our physical schema using the add table icon, or we can start an EER Diagram and add all the tables there.

I prefer to add a new diagram from the beginning and create my schema visually; however, in order to show how to do it with both methods, we are going to create the first two tables in the schema tab, and then continue with the EER Diagram.

When you click the Add Table icon, the table editor opens as a tab below:

Using the table editor, we change the table name and switch to the columns tab (in the tabs below the editor) to enter our columns. We can choose the data type (there is a drop-down list with all the MySQL data types), assign default value, if needed, and we have seven checkboxes to mark any of the following properties:

  • PK – Primary key
  • NN – Not null
  • UQ – Unique
  • BIN – Binary
  • UN – Unsigned
  • ZF – Zero fill
  • AI – Autoincrement

Go Visual

This is one way to add our tables, though we can also create them using the diagrams. If we click the Add Diagram icon now, we will begin a new, empty diagram, and that’s not what we want. We want the two tables that we just created to be in the diagram.

If we go to the menu, select Model/Create Diagram from Catalog Objects, now we have our diagram, and are ready to continue.

Select the table icon on the left; the pointer changes to a hand with a little table. Next, click anywhere in the canvas to create a new table.

Now you just have to double click the table, and the editor tab appears to edit the name, columns, types, etc.- the same way as we did before.

After entering the column details for the new tables, we’ll be ready to start drawing the relationships.


Drawing Relationships

In the vertical tool bar on the left, we have six tools available to create relationships.

Don’t worry about the last one, we’ll explain it later. For the 1:1 and 1:n relationships, we have two different types of symbols: identifying and non identifying. What does that mean?

A relationship is considered identifying when one table is entirely dependent on the other to exist.

A relationship is considered identifying when one table is entirely dependent on the other to exist. A row in that table depends on a row in the other table. A common example is to have a separate table to store phones for users. It may be necessary to have it in another table, because there can be several phones for one user, but each row in that table is entirely dependent on the user – it belongs to the user.

You should be aware that relationships have some implications. If we want to create the physical tables in MySQL, relationships must be mapped in some way. There are a few rules to map relationships into tables:

  • 1:1 relationships. Primary key for one of the tables is included as foreign key in the other table.
  • 1:n relationships. Primary key of the table in the ’1′ side is added as foreign key in the table in the ‘n’ side.
  • n:m relationships. A new table (join table) is created. The primary key is composed of the primary keys from the two original tables.

Identifying relationships are typically used for the join tables created from a many-to-many relationship. These new tables are entirely dependent on the two original tables.

Also, in the case of 1:1 and 1:n identifying relationships, the foreign key introduced will be part of the primary key for that table, forming a composite primary key.

The good news is that MySQL Workbench knows these rules better than most of us. We just draw our lines, and the foreign keys or join tables will be automatically be created. We can also choose to do it manually, as we’ll see shortly.

To draw a relationship, click the icon, and then click the two tables to relate. For one-to-many relationships, click on the “many” side table first, and then on the “one” side table. Let’s see how to do it for the n:m teachers-subjects relationship, and for the 1:n teachers-classes.

The default name assigned for the foreign keys, and for the join tables can be changed globally in Edit/Preferences/Model Tab, or only for the present project in Model/Model Options.

If we don’t want tables and foreign keys to be generated in this way, we can use the mysterious “sixth symbol.”

The “sixth symbol” creates a relationship using existing columns, meaning that you have already included the necessary foreign keys in your tables and created the necessary join tables (n:m mapping tables). Since we’ve already created these Join tables, we don’t need n:m relationships; only 1:n is available.

When we have all our relationships defined, our diagram should looks like so:

Be aware that we have been using the default MySQL Workbench notation for the diagrams, but you can change that in Model/Object Notation and Model/Relationship Notation. This is an example of our model in Classic notation:

At this point, our model is ready, and we can generate the SQL to create the MySQL database.


Generating SQL

Select File/Export/Forward Engineer SQL CREATE Script. We are only three wizard screens away from generating our file!

We even have the option to review and edit the generated SQL before saving it:

And that’s it. Clicking finish, the SQL script will be generated and saved. Now, we can use it in any way we wish. We can load it using the command-line mysql client:

mysql> SOURCE scriptName.sql

Or, we can use MySQL Workbench to finish the work, connecting to our MySQL server and running the script.


Connecting to a MySQL Server

Select Database/Manage Connections from the menu, and click NEW.

If you don’t want to set the password here, you’ll be prompted for it when needed. Click “Test Connection” to check if your parameters are correct, and then click close.

Now, to load the script, we’ll use the SQL editor. In the main menu select Database/Query Database; a window prompts you to select a connection, and then the SQL editor tab opens.

Now click the lightning icon to execute the SQL script, and your database will be generated!

We could also have generated the MySQL database directly from the model, without referencing the actual file, using Database/Forward Engineer from the menu; however, I find it useful to generate the script and then use it how I wish.


Conclusion

MySQL Workbench is an impressive tool. We have only seen a few basic possibilities in the data modeling part, and only peeked at the SQL editor in the second half of this tutorial. We learned how to create a database visually and draw diagrams that can be kept as documentation. You can export the diagrams as a PNG, SVg, PDF or PostScript file. Thanks for reading, and let me know what you think!

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.viking-tech.ro Victor

    This is great for beginners.
    Thx

  • 3CK

    Looks interesting, i’ll try it.

  • http://www.imblog.info Muhammad Adnan

    This seems good tool.

    I have tried Navicat MySql and I liked it.

  • Khalil

    I was trying to use Workbench. Great tutorial … Thank you

  • Philipp

    MySQL Workbench is really nice but not really stable. Be sure to save your Project regulary! I’ve tested it on windows and OS X – it doesn’t matters.

    But anyway nice article!

    • Lateef

      What version did u use

    • tim

      I completely agree…quits unexpectedly very often…save after every change

  • http://www.hipervinculo.net Raúl Riera

    I love simple lightweight solutions like http://www.sequelpro.com/

    Although, options are always welcome

    • Awesome

      That’s for mac only…

  • TahaH

    Absolutely great. Nice tut

  • Mike

    Great Tutorial….. Very Informative.

    One question…. what’s the name of the font that you used for the pointers like “Tables Created So far” etc ?

    The closest font that I could find was ” Bradley hand ITC”

    Please let me know.

    Appreciate your help.

    Thanks.

    • Pablo
      Author

      Mike, the font is Segoe Print. Thanks for your comments.

  • Purple

    I tried the MySQL workbench a few weeks ago. Very nice but I encountered a disaster. Connected to a remote mysql db. Pulled the schema and for some reason, my whole db got corrupted to a point where I couldn’t see the tables in phpmyadmin. Couldn’t even repair the database. Luckily I had a backup.

    You may have heard this a million times but: Back up your db before you attempt anything on a live production site!

    Thanks!

  • http://www.elimcmakin.com eli

    How does this compare in terms of development time to making DBs with phpMyAdmin? What are people’s experiences?

    • http://www.wahix.com DMin

      phpMyAdmin does the job for you. But if you really wont to work on databases. Get yourself MySQL QueryBrowser (free from MySQL.org).
      now, Workbench replaces the QueryBrowser program but nevertheless, you’ll love the power of working with a real database application if you’re only used to phpMyAdmin.

      • http://www.elimcmakin.com eli

        I see. Thankyou for the info.

  • http://www.engram.nu Niklas Larsson

    Nice tutorial. I have always been using the Query Browser and Administrator programs. I didn’t even know that they published a EER diagram program. Thanks for this.

  • http://www.tariqit.com Tariq

    Good introduction about my workbench.

    Thanks

  • Pachito Marco Calabrese

    It’s a nice way for beginners!

    • http://twitter.com/iDev247 iDev247

      What do you recommend for more advanced users? Using only SQL or another application?

      • http://twitter.com/adityamenon90 aditya menon

        @iDev Haven’t you heard of the Story of Mel – The REAL programmer? He wrote code in Hexadecimal – not even assembly.

        There are still many in our trade who do not like to automate rudimentary tasks – since a human brain is always better than an IDE – well that’s their thought not mine! :)

        So our friend here might be recommending that we open up the MySQL command prompt and write “raw, unadorned, inscrutable” SQL Statements. Directly.

        =)

  • michael

    It would also be nice to mention some tools for windows users ;)

  • http://eddwebs.co.cc Eddie

    Absolutely superrrrr

  • paulo silva

    @michael: Workbench runs on windows.
    @onextrapixel: it would be nice to also let people know the differences between the free version and the paid one, like reverse engineering and such. Great tut, as usual.

  • http://www.BertrandLirette.com Bertrand

    I’m actually using Illustrator to design DBs schemas since Access produces such ugly ones. The clients don’t like them. Is there a way to skin the DB schema with this kind of tool (or any other ones) to make it more attractive?

    Thanks! I’ll check this out if I can skin it!

    • http://twitter.com/iDev247 iDev247

      I understand exactly what you’re talking about. They’re lots of tools that help you create database schemas, wireframes, flowcharts and so on but most of them look like crap. I always need to redo them in Illustrator.

  • w1sh

    How cool. How very, very cool.

  • William

    Thanks Pablo …. what a great tutorial !

  • http://www.tenaxtechnologies.com software development for startups

    MySQL Workbench is really nice but not really stable.
    But in any case it’s a nice tutorial.

  • http://superdit.com aditia

    yup mysql workbench solve the problem for me to finding free database modelling tool, but i never used to directly connect to mysql server, so far i’m using for data modeling and generate sql script and still using phpmyadmin to viewing data and backup need

  • http://www.andreabarghigiani.info Andrea Barghigiani

    Really a great article! I’ve been working a bit with Workbench but each time I touch the diagrams i got a bit “scared” :P

    I cannot wait for the next part!!!

  • http://www.nunomedia.com Nuno

    Thanks a lot my friend. You saved me. I am using this tool for my project. I followed your steps and worked very thanks. I wish we had more tutorial like that. Er diagrams, databases, the earlier stages. Thanks

  • Dimitry

    Nice article about a nice instrument. Thanks a lot!

  • http://www.tecmania.it/ marina

    my sql for http://www.tecmania.it used aruba hosting , thanks

  • josheat

    Awesome post!
    Instantly connected to my AppServ mysql testbed, with almost no fuss.
    This looks like a great way to get your head around bigger databases, I wish I knew about it 6 months earlier.
    Thanks man

  • http://www.crackmyidea.blogspot.com/ Bappi

    Nice tutorial. First time i thought Workbench is very hard. But This tutorial is very easy to learn.Thanks

  • David

    Do any hosting providers allow you to connect to MySQL through MySQL workbench? This makes stored procedures much easier to maintain instead of the command line!

  • http://freejavaprogramming.weebly.com Darknight

    Hey, Which program can i use to this? Which program is showing to this pictures? Wat’s the name? Plz answer.

  • JoeYoung

    Thank you , it help me a lot .

  • http://qmmr.pl Marcin

    Thanks for the tut, I like :)

  • jini

    Great tutorial for beginners. Thanks a lot !!!!

  • http://leahayes.co.uk Lea Hayes

    This is a great article!

    I am still struggling understand the differences between “Non-Identifying” and “Identifying” relationship options. For example, why is “wp_postmeta” using “Non-Identifying” in the following diagram:

    http://codex.wordpress.org/images/9/9e/WP3.0-ERD.png

    It would be greatly appreciated if you could help me out with this question!

  • Amjad

    Thanks,

    Enjoyed this easy to follow tutorial.

    I realy wanted to know how to manage table connections a little better. you mentioned

    “The good news is that MySQL Workbench knows these rules better than most of us. We just draw our lines, and the foreign keys or join tables will be automatically be created. We can also choose to do it manually, as we’ll see shortly.”

    But you haven’t shown how to do it manually. could you explain a little more on this.

  • Lee

    I liked the tutorial very much but am confused by the use of the term “SCHEMA”. From what I could see it was used interchangeably with the term “DATABASE”, so why have it? I actually have two databases which both contribute tables to the one EER diagram. The tutorial implied that only one database could be used per diagram but that is neither my experience nor desirable.

  • http://friendster.com/degeist Mokolai

    great!!, it’s just so great!!, i had enjoyed and learned a lot on this tutorial of yours !! this tuts sure makes the beginners the most basic idea on what’s in the box of MySQL Workbench!! (particularly on me, who wants to master Web Database Administration).

    again thanks for this dude !!

  • vikash

    nice job….its very helpful

  • Steve

    Thanks a lot. But where can i get a full step by step guide on MySql?

  • http://www.bbmatrix.com KENNETH

    This is great. I have been experiencing difficulties connecting to the database. I am using msql WB 5.2 CE on window XP. I tried connecting to the database through “Manage Connection”, after typing the username and password, I clicked on test connection but I received an error message: Failed to connect to Mysql @ 127.0.0.1:3306. Access denied for user “bbm”@localhost(using password:yes)

  • arun

    why can’t we develop a single query language for accessing all the databases?

  • http://www.ipadfornothing.co.uk PM

    Nice tutorial – do you know of any tutorials which expend on the functions of the Workbench app – or pehaps a good book ?

    Thanks

  • sudha

    fantastic tutorial !!! really helpful … great work – whose ever it is …

  • Nassim B.

    Navicat isn’t free nor open source …. this tutorial is really greaaat, thanks 1000

  • Eby

    Hi, am so impressed with the way you simplified this tutorial. It made my work so easy.

    Thanks

  • Oana

    Veeeery helpful for beginners. 10x

  • Raizer

    I have been reading lots of stuff onWorkbench,but this is the only article that showed me (not explain) how to build the Database.Thx

  • I

    congratulations on choosing a different example than the typical employee/department. Very nice tutorial.

    @Lea Hayes
    My understanding is that it should be “identifying”: the meta-data belongs to a post and it has no reason to exist without being associated to one. But I think they use code to remove meta-data that is not associated with a post.

  • Yasinta Nike Wijaya

    thankyou for this tutorial ^^ It’s really help me

  • VelvetMirror

    This is an excellent tutorial, and MySQL workbench is a great tool.

    Thanks!

  • http://facebook.com barrey

    hi Pablo, i just tried mysql workbench on my pc. but i have problem with mysql connection.
    it said: “Unhandled exception has occurred in your application. if you click Continue, the application will ignore this error and attempt to continue. if you click quit, the aplication will close immediately.
    images/ui/message_confirm.png”

    is it because i install MSSQL Server @ same pc?
    but MySQL Query Browser work fine.

    pls help, thanks before.