So you want to learn about databases huh?
Well this article will cover off the most basics of basics. Here is the table of contents for our first peak at database management.
- Create Database
- Create Table
- Insert Data
- Update Data
- Delete Data
- Query Data
The goal is at end of this article that you have a basic understanding of how to preform all of these functions inside a database.
I recommend that you use the SQLYOG Tool to interface with your database.
You can get the community version here. http://code.google.com/p/sqlyog/
So lets talk about Databases now.
A database is really just a set of objects. It is best practice to make sure that a database only contains stuff that is in some-way related to each other. For example: You do not want your Blog database merged with say. your accounting database. The reasons should be clear however I should probably go over the “rules” of database design in the Real World.
- Keep data sets separate. This is for security and for maintainability sake. Think of it as organizing stacks of paper. You want distinct piles of paperwork otherwise you will never know where anything is.
- Never have redundant fields. We will discuss this later on in a design article.
- Use proper-naming when appropriate.
Most of this is common sense. So now that we have some ground rules lets dive into actually doing some cool stuff.
1. CREATE DATABASE – http://dev.mysql.com/doc/refman/5.0/en/create-database.html
So lets look at the most basic syntax of the statement.
CREATE DATABASE <name>;
Pretty simple yes? I thought so.
So lets go ahead and create our first database.
Create Database Blog;
Yay, Our First database.
That was cool? No…I guess it wasn’t. All we did was create a virtual “pile”. There’s nothing in it…Yet.
2. Create Table - http://dev.mysql.com/doc/refman/5.1/en/create-table.html
Well now we are getting somewhere. This command will allow us to create a object or rather in database geek speak, a Table. Tables hold data or you can think of it as a document in your pile.
Before we get into the syntax of creating our very first table we will need to outline some specifics about data-columns.
The first and most important thing is something called a Primary Key. The primary key is a data-column dedicated to making sure each data-row is unique. The standard name for this column is “id” and it represents a integer auto-generated by the database. Every time a new data-row is created a new id gets created as well. An example of this might be something like, Employee #. The Employee # is unique to a single individual and thus would be considered a Primary Key. For the most part every data table should have a Primary Key. Just like everything there are exceptions to this rule which we will discuss at a later time.
So lets take a look at a Create Table Command.
CREATE TABLE `Blog`.`Posts` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR (255),
`post_text` TEXT,
PRIMARY KEY (`id`)
) ;
So lets break this down. The first line tells the database what the table name is going to be. The () tells the database about the contents of the table. Next comes the data-columns. They are always represented in this fashion:
`<name>` <type> <NULL | NOT NULL> <OPTIONS>
We see in this case the first column is the special Primary key field. The primary key should always have the AUTO_INCREMENT attached. This lets the system auto-generate a positive non-zero unique #. The primary key should always be of INT as well. We will discuss data types later on in another article.
The next 2 lines define 2 more data columns, 1 of a String with max length of 255, The next of Text. Text fields are strings as well, however their max length is much larger than 255. The final line tells the database that the primary key is the column named id.
There we go our first data-table! Next up how do we use it!
3. MySQL INSERT -
Inserting data is very easy.
INSERT INTO `Blog`.`Posts` (`name`, `post_data`) VALUES(‘abcde’, ’123456′);
The first set of () defines the order and what data fields you are putting data into. Note that ID has no data being inserted. That is handled by the system. It is possible to leave out data columns when inserting data, only define columns you have data for, never insert blank data into a column.
The VALUES() defines what data is going in. It is processed in the same order as the columns defined previously. So the database will set name = abcde, and post_data = 123456.
4. Updating Data -
Well thats fine and dandy but how do I update it if I make an mistake. Well its just as easy.
Update `Blog`.`Posts` set `name` = ‘abcde’, `post_text` = ’123456′ WHERE id = 1;
So as you can guess we are switching the values around in our Post. We are also seeing a new clause, the WHERE clause. The where clause is used as a filter when using an UPDATE or SELECT statement. Obviously when updating we generally only want to affect 1 record. This is where the ID column comes in. Since it was our first post, it’s id number should be 1. Want to affect every post? just drop the where clause.
Where clauses can also use greater and less than. Not Equal is defined by <>. But we will get into more detail about this later.
5. Delete Data
So well that’s all nice, but I really just want to get rid of that post now.
DELETE FROM `Blog`.`Posts` WHERE id = ’1′;
…Bam! Post gone.
6. Query Data
Well what if i want to find posts. Well my friend that is handled via the SELECT statement. The select statement is the bread-and-butter of databases. It is how you retrieve your information.
SELECT name, post_data FROM `Blog`.`Posts`;
This query will do what?
If you said return all data-rows of the Posts table you are correct!
Want to get the latest 5 posts?
SELECT name, post_data FROM `Blog`.`Posts` Order By id desc LIMIT 5;
Here we introduce the Order By Clause and the LIMIT clause. I think they are pretty self-explanatory. Order tells the database in which order you want the data, and LIMIT says how many items you want.
Well maybe you want the most recent 10 posts pertaining to Obama.
SELECT name, post_data FROM `Blog`.`Posts` WHERE post_data LIKE ‘%Obama%’ Order By id desc LIMIT 10;
What is all this? LIKE? Well its exactly what it looks like. Like returns all items that match its Expression. In this case it is anything that contains the word Obama. Notice How i said contains. That means that Obamainator is a valid match. If you just wanted Obama, omit hte %s. %s is a wild-card, meaning any text.
Anyway this is the end of the first Tutorial.
I hope you enjoyed it.