MySQL For Absolute Beginners
MySQL For Absolute Beginners
MySQL For Absolute Beginners
1 of 24
http://www.elated.com/articles/mysql-for-absolute-beginners/
Search articles...
94
Tweet
Never used MySQL before? Start here! This tutorial walks you
through the very basics of MySQL and SQL databases. Learn
how to install MySQL, how to issue commands, and how to
Popular articles
jQuery Mobile: What Can It Do for You?
use a MySQL database on your computer. This will give you a good
grounding in MySQL that you'll find useful when you start developing
database-driven websites using PHP, Ruby, or your language of choice.
You'll explore the following areas in this tutorial:
05-07-2015 14:35
2 of 24
http://www.elated.com/articles/mysql-for-absolute-beginners/
What is a database?
A database is a structured collection of data. Here are some typical
examples of databases:
An online store database that stores products, customer details and
orders
A database for a web forum that stores members, forums, topics and
posts
A database for a blog system,
system such as WordPress, that stores users,
blog posts, categories, tags, and comments
The software that manages databases is known as a database management
05-07-2015 14:35
3 of 24
http://www.elated.com/articles/mysql-for-absolute-beginners/
username,password,emailAddress,firstName,lastName
"johnsmith","brickwall53","[email protected]","John","Smith"
"maryjones","garden37","[email protected]","Mary","Jones"
While this technique is fine for simple data structures and small amounts of
data, you quickly run into problems as your site grows. Searching and
updating a very large text file is slow and prone to corruption. What's more,
things start to get messy when you want to link records together, such as
linking a customer record to the orders that the customer has made, and
then linking each order record to the products that are in the order.
Relational databases are designed to take care of all these problems. Here
are some reasons to use a database instead of text files:
They're fast. Databases use indexes, or keys, to find records of data
extremely quickly. For example, once you add a key to an emailAddress
field for member records in a database, you can retrieve a member record
based on the member's email address almost instantly, no matter how
many millions of members you may have in your database.
They're reliable. A DBMS ensures that the data in the database is read
and written reliably, without corrupting the data. Many DBMSs allow you
to use techniques like locking and transactions to ensure that records are
inserted and updated in a predictable way.
They let you link records together. Relational databases let you store
different types of data in groups known as tables. You can then link data
together across tables. For example, you can create a customers table
and an orders table, then link a customer record to all the order records
associated with the customer. The ability to link records across tables lets
you create complex databases with lots of different types of related data.
4 of 24
http://www.elated.com/articles/mysql-for-absolute-beginners/
You now know why databases are useful, and how they can help you build
complex websites and web apps. But why use MySQL in particular?
There are many great DBMSs out there, including MySQL, PostgreSQL,
SQLite, Oracle, and SQL Server, and all of them can be used for most web
development purposes.
That said, MySQL does have a few advantages for web developers compared
to some other systems:
It's open source,
source which means it's free for anyone to use and modify.
It's widely available. MySQL can be installed on many different
platforms, and it usually comes standard with most web hosting setups.
It's easy to use. Setting up and working with MySQL databases is
relatively straightforward.
It works well with PHP. As of version 5.3, PHP has a native MySQL driver
that is tightly coupled with the PHP engine, making it a good choice for
PHP coders.
Each DBMS has its own strengths and weaknesses. For example,
PostgreSQL is also open source, is very stable, and has a great community
behind it. SQLite is extremely fast and self-contained (and is also free),
while Oracle and SQL Server have a lot of enterprise-level features that
make it a good choice for large organizations.
Installing MySQL
As I mentioned above, most web hosting accounts come with MySQL
pre-installed. However, if you're developing websites using MySQL, you also
want to have the MySQL server running on your own computer, so that you
can create and test your databases and code without needing to upload files
to your live server all the time.
There are two main components to MySQL:
The MySQL database server, mysqld . This is the MySQL DBMS that
does the actual work of managing your databases. It runs all the time in
the background, accepting connections from client programs, web scripts
and so on.
Various client and utility programs. These include mysql , the
command-line MySQL Monitor client that you'll use later in the tutorial to
issue commands to the server. You'll also find programs like mysqladmin
for administering MySQL databases, and mysqldump for exporting and
backing up databases.
05-07-2015 14:35
5 of 24
http://www.elated.com/articles/mysql-for-absolute-beginners/
There are many ways to install the MySQL server and associated programs.
Here are three ways you can do it:
Using an official MySQL installation package. There are prebuilt
packages available for many different operating systems, including
Windows, Mac OS X and Linux. The basic procedure is to download the
package file, extract it, and run the installer. See the documentation for
the exact steps.
Using a Linux package manager. Many Linux distros come with a
package manager for example, Ubuntu includes the Ubuntu Software
Centre that makes it easy to install MySQL, along with PHP, Apache
and other web development software. See your distro's documentation
for details.
Installing an entire LAMP/WAMP/MAMP package. This is arguably the
easiest way to install a complete MySQL-based development setup on
your computer. These packages contain all you need to start building
database-driven sites, including the Apache web server, MySQL, and
PHP/Perl, hence the acronym "AMP". (The L, W and M stand for Linux,
Windows and Mac OS X respectively.) Since everything's installed in one
go, you'll find that Apache, MySQL and PHP/Perl all play nicely together,
with little or no further configuration required.
If you want to get up and running as quickly and easily as possible, I'd
personally recommend downloading and installing XAMPP. This
LAMP/WAMP/MAMP package is available for Linux, Windows, Mac OS X and
Solaris, and automatically installs and sets up Apache, MySQL, PHP and Perl
on your computer. What's more, it's easy to uninstall everything later if you
want to.
To install XAMPP:
1. Visit the XAMPP homepage and click the link for your operating system
(Linux, Windows, Mac OS X or Solaris).
2. Follow the steps on the page to download, install, start, and test the
XAMPP system on your computer.
05-07-2015 14:35
6 of 24
http://www.elated.com/articles/mysql-for-absolute-beginners/
05-07-2015 14:35
7 of 24
http://www.elated.com/articles/mysql-for-absolute-beginners/
Once the MySQL Monitor runs, you'll see something like this in your
terminal window:
The last line, mysql> , is the MySQL prompt. This is where you type your
commands to send to the MySQL server.
Let's try out a couple of commands. Type the following at the mysql>
prompt, then press Enter :
select now();
This tells MySQL to get the current date and time and display it. You'll see
something like this appear:
+---------------------+
| now()
+---------------------+
| 2011-08-24 11:36:40 |
+---------------------+
1 row in set (0.00 sec)
This command lists all the MySQL databases on your computer. Since you've
just installed MySQL, there will just be a few default databases, similar to the
following:
05-07-2015 14:35
8 of 24
http://www.elated.com/articles/mysql-for-absolute-beginners/
+--------------------+
| Database
+--------------------+
| information_schema |
| mysql
| performance_schema |
| test
+--------------------+
4 rows in set (0.00 sec)
Now that you know how to send commands to your MySQL server, you're
ready to create your own database and start adding data to it. You'll do this
in the following sections.
When you're finished with the MySQL Monitor, you can quit it by typing
exit at the prompt and pressing Enter .
If you're not comfortable with the command line, there are other ways to
administer MySQL and issue commands. MySQL Workbench is a free
graphical app that can connect to any MySQL server and administer it.
There's also the web-based phpMyAdmin, which is included in many
LAMP/WAMP/MAMP packages.
Creating a database
Let's create a simple database for an imaginary book store. At your mysql>
prompt, type the following and press Enter :
create database bookstore;
MySQL has now created your database. You can check this by typing show
databases again:
05-07-2015 14:35
9 of 24
http://www.elated.com/articles/mysql-for-absolute-beginners/
+--------------------+
| Database
+--------------------+
| information_schema |
| bookstore
| mysql
|
|
| performance_schema |
| test
+--------------------+
4 rows in set (0.00 sec)
As with all relational databases, MySQL organizes its data in tables. A table
holds one or more records of related data, in a similar way to an associative
array in JavaScript or PHP. A table consists of:
05-07-2015 14:35
10 of 24
http://www.elated.com/articles/mysql-for-absolute-beginners/
One or more fields. Each field holds a specific type of information. For
example, in a books table, you might have one field for the book title,
another field for the book's author, and so on.
One or more records. A record is a set of field values that stores all the
information about a particular entity in the table. In a books table, a
record would store all the field values for a specific book.
The easiest way to understand fields and records is to see how they look
when laid out in a table. Let's set up a books table to hold books in our
book store:
id
title
author
price
John Steinbeck
12.99
Nineteen Eighty-Four
George Orwell
8.99
Haruki Murakami
7.99
The top row of the table holds the field names: id , title , author , and
price . The next three rows are the three book records in our table. Each
record has its own field values: for example, the first record's title field
contains "The Grapes of Wrath", while the second record's title field
contains "Nineteen Eighty-Four".
Since a single column in a table holds all the different record values for a
specific field, fields are also commonly known as columns . Similarly, the
records in a table are commonly called rows.
So how do you actually create this table in MySQL? To do this, you need to
create a schema for the table. This is a text file containing a series of SQL
statements that create the table and define the table's fields.
Here's the schema save it as a file called books.sql somewhere on your
computer:
USE bookstore;
DROP TABLE IF EXISTS books;
CREATE TABLE books
(
id
title
author
price
PRIMARY KEY
(id)
);
05-07-2015 14:35
11 of 24
http://www.elated.com/articles/mysql-for-absolute-beginners/
Let's take a look at the SQL statements in this file and see what they do:
USE bookstore
This tells MySQL to switch to the bookstore database that you created
earlier. MySQL will then carry out all further operations on this database.
DROP TABLE IF EXISTS books
This deletes any previous books table from the database, since you can't
redefine a table if it already exists.
Be careful when using DROP TABLE . When you delete a table like this,
any data in the table is gone forever!
The NOT NULL constraint prevents the field containing NULL values. In
MySQL, NULL is a special type of value that can be useful in some
situations. However, it can also be quite confusing for beginners, so
we won't use them in this tutorial.
05-07-2015 14:35
12 of 24
http://www.elated.com/articles/mysql-for-absolute-beginners/
key uniquely identifies records in the table; a table can have only one
primary key. MySQL also creates an index using the primary key this
lets you retrieve a book record extremely quickly by referencing its id
field, even if the table contains millions of rows.
Now that we've created our schema statements, we need to run them
through MySQL to create the actual table. To do this, switch back to the
MySQL Monitor and type the following command at the mysql> prompt:
source /path/to/books.sql
Database changed
Query OK, 0 rows affected, 1 warning (0.00 sec)
Query OK, 0 rows affected (0.10 sec)
To check that your books table was created, you can type show tables :
+---------------------+
1 row in set (0.00 sec)
You can even inspect the table schema to make sure it's correct. To do this,
use the explain command, like this:
| Type
+--------+------------------+------+-----+---------+----------------+
| id
| int(10) unsigned | NO
| PRI | NULL
| auto_increment |
05-07-2015 14:35
13 of 24
| title
http://www.elated.com/articles/mysql-for-absolute-beginners/
| varchar(255)
| NO
| NULL
| author | varchar(255)
| NO
| NULL
| price
| NO
| NULL
| decimal(10,2)
+--------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
Adding records
You've now created a database called bookstore , and added a books table
to it. Let's try adding a record to the books table.
To add a record to a table, you use the SQL INSERT statement, passing in
the record's field names and values. Type the following line in the MySQL
Monitor to insert a book record into your table:
INSERT INTO books ( title, author, price )
VALUES ( "The Grapes of Wrath", "John Steinbeck", 12.99 );
You should see the following output, indicating that MySQL has added the
row to the table:
As you can see, we've used an INSERT statement to add the book "The
Grapes of Wrath" to the table. We specified INTO books to tell MySQL which
table to insert the record into, then listed the field names that we want to
supply values for in parentheses, followed by the keyword VALUES , followed
by the field values in the same order as the field names, again in
parentheses.
Notice that we haven't specified a value for the id field. Since it's an
auto_increment field, MySQL generates the field value automatically.
Let's add another couple of books to the table:
Duplicates: 0
Warnings: 0
As you can see, you can insert multiple rows at once by supplying multiple
sets of field values, enclosed in parentheses and separated by commas.
05-07-2015 14:35
14 of 24
http://www.elated.com/articles/mysql-for-absolute-beginners/
Retrieving records
Now that we've added some records to the table, how can we retrieve them?
This is where SQL queries come in. The SQL SELECT statement lets you
retrieve one or more records from a table or even multiple tables at once
based on criteria that you supply. The basic syntax is:
SELECT fieldNames FROM tableName [WHERE criteria]
There's a lot more to the SELECT statement than this, but we'll keep
things simple in this tutorial!
Let's try a basic SELECT query on our books table using the MySQL
Monitor:
| author
| price |
+----+----------------------------+-----------------+-------+
|
| John Steinbeck
| 12.99 |
2 | Nineteen Eighty-Four
| George Orwell
8.99 |
7.99 |
+----+----------------------------+-----------------+-------+
3 rows in set (0.00 sec)
This SELECT query retrieves all fields ( * ) from the books table. Since we
haven't supplied any additional criteria, the query retrieves all the records in
the table, and displays the field values in the MySQL monitor.
As you can see, MySQL has auto-generated the values for the id field,
05-07-2015 14:35
15 of 24
http://www.elated.com/articles/mysql-for-absolute-beginners/
beginning with 1.
What if we want to retrieve just one record from the table, such as the book
"Nineteen Eighty-Four"? To narrow down the selection, we can add a WHERE
clause, like this:
| author
| price |
+----+----------------------+---------------+-------+
|
8.99 |
+----+----------------------+---------------+-------+
1 row in set (0.00 sec)
As well as selecting by the id field, we can select by any other field we like:
| author
| price |
+----+----------------------+---------------+-------+
|
8.99 |
+----+----------------------+---------------+-------+
1 row in set (0.01 sec)
We can also use other operators, such as < (less than), > (greater than),
and the boolean AND operator, to retrieve a range of records:
mysql> SELECT * FROM books WHERE price < 10 AND price > 5;
+----+----------------------------+-----------------+-------+
| id | title
| author
| price |
+----+----------------------------+-----------------+-------+
|
2 | Nineteen Eighty-Four
| George Orwell
8.99 |
7.99 |
+----+----------------------------+-----------------+-------+
2 rows in set (0.00 sec)
Finally, instead of retrieving all fields using * , we can specify just the field
or fields we want to retrieve. Here's an example:
05-07-2015 14:35
16 of 24
| title
http://www.elated.com/articles/mysql-for-absolute-beginners/
| author
+----------------------------+-----------------+
| The Grapes of Wrath
| John Steinbeck
| Nineteen Eighty-Four
| George Orwell
As you can see, SELECT queries make it easy to retrieve just the records and
fields you want from your table.
Summary
This tutorial has introduced you to databases in general, and MySQL in
particular. You've covered the following topics:
The concept of a database,
database which lets you easily store large amounts of
structured data for your websites and web apps.
Why databases are a good idea compared to, say, flat text files of data.
Some reasons to choose MySQL for your DBMS.
How to install MySQL in three different ways: installing the official
packages, using a Linux package manager, and installing a
LAMP/WAMP/MAMP package such as XAMPP.
How to use the MySQL Monitor program,
program mysql , to connect to your
MySQL server and issue commands.
How to create databases with the CREATE DATABASE command.
How to create tables with the CREATE TABLE command.
A few MySQL data types,
types including int , varchar , and decimal .
The concepts of NULL values,
values auto-increment fields,
fields unique fields,
fields
and primary keys.
keys
Adding records to a table using the INSERT statement, and
Retrieving records from a table with the SELECT statement.
MySQL databases are a big topic, and there are lot more important areas to
explore, including updating and deleting records; table relationships;
normalization; joining tables; and grouping results. However, I hope you've
found this article useful as a general introduction to MySQL.
If you want to learn more, the MySQL manual has a decent tutorial section,
including more details on using the MySQL Monitor, creating databases, and
adding tables and data. It also includes some common queries that you can
take and adapt for your own uses. You might also like to read my article
05-07-2015 14:35
17 of 24
http://www.elated.com/articles/mysql-for-absolute-beginners/
Build a CMS in an Afternoon with PHP and MySQL to learn how to use PHP
and MySQL together in practice.
Have fun!
[Photo credit: koalazymonkey]
Follow Elated
94
Tweet
month! Privacy
Link <a href="http://www.elated.com/articles/my
HTML:
Your Email Address...
URL only: http://www.elated.com/articles/mysql-for-a
Related articles
7 Exciting Up-and-Coming
Web Technologies
Ruby Tutorial for Absolute
Beginners
Easy HTML Templates with
Mustache
JSON Basics: What You Need
to Know
05-07-2015 14:35
18 of 24
http://www.elated.com/articles/mysql-for-absolute-beginners/
These will not exist until you create tables and add data to them. You only
need to be concerned with the file structure unless you have to do a
manual recovery, hopefully that will not happen,
A .sql file is a text file that contains a set of command lines to rebuild the
database, table structures and data, that is used for exporting, importing
or taking backups of the database.
05-07-2015 14:35
19 of 24
http://www.elated.com/articles/mysql-for-absolute-beginners/
Or if you prefer a Windows GUI as MySQL CLI takes a bit of getting used to
download and install HeidiSQL ( http://www.heidisql.com/ )
You can see the CLI command assemble in the "command" pane and learn
how it works.
05-07-2015 14:35
20 of 24
http://www.elated.com/articles/mysql-for-absolute-beginners/
/xammp/mysql/users.sql;
I get this error message...
ERROR 1064 (42000): You have an error in your SQL syntax; check the
manual that corresponds to your MYSQL server version for the right syntax
to use near '/xammp/mysql/users.sql' at line 1
I'm really confused now!
Which is equivalent to
use db_name
source file.ext;
The mysql command is to start the mysql CLI daemon so it can accept
instructions
The USE command says "Open 'db_name' and set it as the current working
database.
The SOURCE command says Open the named file and execute the
commands in the sequence they appear.
[Edited by chrishirst on 07-Feb-14 09:12]
05-07-2015 14:35
21 of 24
http://www.elated.com/articles/mysql-for-absolute-beginners/
Hi Chris
Not sure whats going on here but perhaps this was the problem before
and hadn't realised.
I did a show databases; command and got the following;
+--------------------+
| Database |
+--------------------+
| information_schema |
| test |
+--------------------+
2 rows in set (0.01 sec)
Where did the other databases go including the users.sql !
So decided to restart my laptop and create a new database. This time I
followed the instructions and created a database called bookstore.sql but
then got this error message !
=====================================================================
ERROR 1044 (42000) Access denied for user @localhost to database
bookstore
=====================================================================
Puzzled as to whats happening but Im sure you will be able to help...
05-07-2015 14:35
22 of 24
http://www.elated.com/articles/mysql-for-absolute-beginners/
05-07-2015 14:35
23 of 24
http://www.elated.com/articles/mysql-for-absolute-beginners/
05-07-2015 14:35
24 of 24
http://www.elated.com/articles/mysql-for-absolute-beginners/
Database Server running. I'm using a MAC and when I go into the Terminal
and enter "mysql -u root" and hit ENTER, I get mysql: command not found
Is there something I'm missing?
Post a response
Want to add a comment, or ask a question about this article? Post a
response.
To post responses you need to be a member. Not a member yet? Signing up
is free, easy and only takes a minute. Sign up now.
Top of Page
Home
Contact Us
Articles
Spamwars
Forums
RSS
05-07-2015 14:35