MySQL for Absolute Beginners
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 create and use databases.
A database is an essential part of most websites and blogs, but setting up and using a database can be a daunting task for the beginner web developer.
In this tutorial you'll learn — in simple terms — how to install, set up, and 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:
- The concept of a database, and why databases are useful
- The advantages of using MySQL to manage your databases
- How to install MySQL on your computer
- Using the MySQL Monitor program to send commands to your MySQL server
- How to create a database and table
- SQL (Structured Query Language), and what it's used for
- Adding records to a table, and retrieving records from a table
Ready to start exploring MySQL? Let's go!
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, such as WordPress, that stores users, blog posts, categories, tags, and comments
The software that manages databases is known as a database management system, or DBMS. MySQL is an example of a DBMS. Rather confusingly, DBMSs are often called databases too. Strictly speaking though, the database is the data itself, while the DBMS is the software that works with the database.
There are many different ways to organize data in a database, known as database models. One of the most popular is the relational model, which is what MySQL uses (along with PostgreSQL, Oracle, Microsoft SQL Server, and other common systems). Consequently, MySQL is known as a relational database management system, or RDBMS.
The following diagram shows how a database, the DBMS, and your website's code interact with each other.
Why use a database?
If you haven't used a database for your website before, you may have stored data in text files such as comma-separated value (CSV) files. Here's an example of a CSV file:
username,password,emailAddress,firstName,lastName "johnsmith","brickwall53","firstname.lastname@example.org","John","Smith" "maryjones","garden37","email@example.com","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
emailAddressfield 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
customerstable and an
orderstable, 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.
Why use MySQL?
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?
That said, MySQL does have a few advantages for web developers compared to some other systems:
- It's open 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.
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
mysqladminfor administering MySQL databases, and
mysqldumpfor exporting and backing up databases.
In addition, many MySQL installs include documentation, header files for developers, and the MySQL test suite.
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:
- Visit the XAMPP homepage and click the link for your operating system (Linux, Windows, Mac OS X or Solaris).
- Follow the steps on the page to download, install, start, and test the XAMPP system on your computer.
Issuing commands to MySQL
Assuming you've now installed and started your MySQL server using one of the above techniques, how do you interact with the server? When you installed the MySQL server, you also installed
mysql, the MySQL Monitor. This is a command-line client program that you can use to connect to the server and issue commands.
So let's try firing up the MySQL Monitor and see what it can do. Follow these two steps:
- Open a terminal window:
- Windows 7: Click the Windows logo, then choose All Programs > Accessories > Command Prompt.
- Mac OS X: Open a Finder window, then choose Applications > Utilities > Terminal.
- Ubuntu: Choose Applications > Accessories > Terminal, or if you're using the Unity desktop, click the Ubuntu logo and type terminal. (More info)
- Run the
mysqlprogram in the terminal window:
- Windows 7: Assuming you installed XAMPP, type cd c:\xampp\mysql\bin and press Enter, then type mysql -u root and press Enter.
- Mac OS X and Ubuntu: Just type mysql -u root and press Enter.
-u rootparameter tells the MySQL Monitor to connect to the MySQL server using the root user, which is always available with MySQL. By default, MySQL's root user doesn't need a password. This is OK for a development setup on your computer, but a terrible idea for a live server! If you're installing MySQL on a live server, make sure you secure it properly. XAMPP also comes with some security scripts that can automatically make your XAMPP installation more secure.
Once the MySQL Monitor runs, you'll see something like this in your terminal window:
Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 3893 Server version: 5.5.8 Source distribution Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> _
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:
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)
Now try another command:
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:
+--------------------+ | 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;
If all goes well, you'll see something like this:
Query OK, 1 row affected (0.05 sec)
MySQL has now created your database. You can check this by typing show databases again:
mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | bookstore | | mysql | | performance_schema | | test | +--------------------+ 4 rows in set (0.00 sec)
Congratulations — you've just created your first MySQL database!
Some SQL basics
All of the commands you've issued so far —
show databases, and
create database bookstore — are SQL statements. SQL, or Structured Query Language, is the language you use to communicate with most DBMSs, including MySQL. Using SQL, you can create and delete databases and tables; insert new data into tables; update data; delete data; and retrieve data.
Statements that retrieve data from a database are also commonly called queries, hence the name "Structured Query Language".
You'll use SQL in the rest of this tutorial as you create a table in your new database, add a record, and retrieve a record.
Creating a simple table
- One or more fields. Each field holds a specific type of information. For example, in a
bookstable, 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
bookstable, 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:
The top row of the table holds the field names:
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 int unsigned NOT NULL auto_increment, # Unique ID for the record title varchar(255) NOT NULL, # Full title of the book author varchar(255) NOT NULL, # The author of the book price decimal(10,2) NOT NULL, # The price of the book PRIMARY KEY (id) );
Let's take a look at the SQL statements in this file and see what they do:
This tells MySQL to switch to the
bookstoredatabase that you created earlier. MySQL will then carry out all further operations on this database.
DROP TABLE IF EXISTS books
This deletes any previous
bookstable 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!
CREATE TABLE books ( ... )
This statement creates a new table called
books. The stuff in between the parentheses defines the table's fields and its primary key, as we'll see next.
id int unsigned NOT NULL auto_increment
The first field we define is
id. This is a special type of field that assigns a unique numeric ID to each book record in the table. Most of the time, you'll want your table to have a unique field of some sort, so that you can easily identify a particular record. We give the field an
int unsignedtype, which can hold large, positive integer numbers. We also add the
auto_incrementattribute to the field — now, whenever we add a new record to the table, MySQL will automatically assign a new, unique value to the record's
idfield (starting with 1).
NOT NULLconstraint prevents the field containing
NULLvalues. In MySQL,
NULLis 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.
title varchar(255) NOT NULL
Next we define the field to hold each book's title. We give it a
varchar(255)type, which means it can hold a text string up to 255 characters long.
author varchar(255) NOT NULL
The next field is the book's author. As with the
titlefield, we give it the
price decimal(10,2) NOT NULL
The last field is the book's price. We give this field a
decimal(10,2)type, which means that the field can hold a 10-digit decimal number, with 2 of the digits sitting to the right of the decimal point.
PRIMARY KEY (id)
Finally, we create a primary key based on the table's
idfield. A primary 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
idfield, 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
/path/to/books.sql is the full path to your
books.sql file. (If you ran
mysql in the same folder as your
books.sql file then you can just type source books.sql.)
You should see the following output in MySQL Monitor:
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:
mysql> show tables; +---------------------+ | Tables_in_bookstore | +---------------------+ | books | +---------------------+ 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:
mysql> explain books; +--------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | title | varchar(255) | NO | | NULL | | | author | varchar(255) | NO | | NULL | | | price | decimal(10,2) | NO | | NULL | | +--------+------------------+------+-----+---------+----------------+ 4 rows in set (0.00 sec)
You've now created a database called
bookstore, and added a
books table to it. Let's try adding a record to the
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:
Query OK, 1 row affected (0.06 sec)
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:
mysql> INSERT INTO books ( title, author, price ) VALUES ( "Nineteen Eighty-Four", "George Orwell", 8.99 ), ( "The Wind-Up Bird Chronicle", "Haruki Murakami", 7.99 ); Query OK, 2 rows affected (0.00 sec) Records: 2 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.
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:
mysql> SELECT * FROM books; +----+----------------------------+-----------------+-------+ | id | title | author | price | +----+----------------------------+-----------------+-------+ | 1 | The Grapes of Wrath | John Steinbeck | 12.99 | | 2 | Nineteen Eighty-Four | George Orwell | 8.99 | | 3 | The Wind-Up Bird Chronicle | Haruki Murakami | 7.99 | +----+----------------------------+-----------------+-------+ 3 rows in set (0.00 sec)
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, 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:
mysql> SELECT * FROM books WHERE id = 2; +----+----------------------+---------------+-------+ | id | title | author | price | +----+----------------------+---------------+-------+ | 2 | Nineteen Eighty-Four | George Orwell | 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:
mysql> SELECT * FROM books WHERE title = "Nineteen Eighty-Four"; +----+----------------------+---------------+-------+ | id | title | author | price | +----+----------------------+---------------+-------+ | 2 | Nineteen Eighty-Four | George Orwell | 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 | | 3 | The Wind-Up Bird Chronicle | Haruki Murakami | 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:
mysql> SELECT title, author FROM books; +----------------------------+-----------------+ | title | author | +----------------------------+-----------------+ | The Grapes of Wrath | John Steinbeck | | Nineteen Eighty-Four | George Orwell | | The Wind-Up Bird Chronicle | Haruki Murakami | +----------------------------+-----------------+ 3 rows in set (0.00 sec)
As you can see,
SELECT queries make it easy to retrieve just the records and fields you want from your table.
This tutorial has introduced you to databases in general, and MySQL in particular. You've covered the following topics:
- The concept of a 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,
mysql, to connect to your MySQL server and issue commands.
- How to create databases with the
- How to create tables with the
- A few MySQL data types, including
- The concepts of
NULLvalues, auto-increment fields, unique fields, and primary keys.
- Adding records to a table using the
- Retrieving records from a table with the
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 Build a CMS in an Afternoon with PHP and MySQL to learn how to use PHP and MySQL together in practice.
[Photo credit: koalazymonkey]
Responses to this article
20 most recent responses (oldest first):
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.
to load a .sql command script at the mysql comman prompt
Ok sorry about that should have noticed.... however.... after putting the following into the command line
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!
the command line to import a text file is
mysql db < file.ext
Which is equivalent to
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]
Not sure what’s 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 what’s happening but I’m sure you will be able to help...
Without wishing to be flippant you're stating the obvious... I realise what the error message is saying but as I'm the only user of the computer but nothing has changed since I started working through this tutorial a few days ago and created the original user.sql database.
So have you any idea as to why it's suddenly telling me I don't have permission and if you do could you set out the steps I should take ?
MySQL has an entirely seperate user list to the Windows user list, and uses a UNIX privilege/permissions hierarchy NOT the comparatively weak Windows permissions hierarchy.
When you installed MySQL it will have asked you for a root user password, it is THAT user / password combination that you need to login to the command window with, otherwise you are simply a "user" with no privileges beyond USE to open a database and running SELECT queries against that DB.
Once you are logged in to a 'root' command window (called a 'shell' in UNIX parlance) you will then have full privileges to see, read, change and 'drop' (delete) databases and tables, create users and set privileges to specific databases or actions.
Now to my first question.
Having successfully installed XAMPP.1.8.3-3 on a mac I have it all up and running perfectly.
I used terminal to set passwords for xampp, mySQL/phpAmin, mySQL root and FTP "daemon".
Now I tried mysql -u root and I get "command not found"
Is this because I'm not using terminal as a root user?
If so how do I log in as a root user.
Thanks - Paul
to accommodate the current Mac OS
Thanks and let me save you a reply.
mysql> select now();
mysql> show databases;
mysql> create database bookstore;
ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'bookstore'
mysql --user=root --password=password
Is there something I'm missing?
use the full path to the executable IN the command line or add the location to $PATH
mysql -u root -p [root password]
and provide the correct password for the mysql 'root' user
You can ALSO find the answer to this very question SIX posts back and is dated 10-Mar-14.
Also see, https://docs.oracle.com/cd/E17952_01/refman-5.6-en/resetting-permissions.html
Its really good to learn and also got to learn some new things,Thanks
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.