Try Tuts+ Premium, Get Cash Back!
SQL for Beginners
basix

SQL for Beginners

Most modern web applications today interact with databases, usually with a language called SQL. Lucky for us, this language is quite easy to learn. In this article, we are going to start with some basic SQL queries and use them to interact with a MySQL database.

What You Need

SQL (Structured Query Language) is a language designed for interacting with relational database management systems (RDBMS), like MySQL, Oracle, Sqlite etc… To perform the SQL queries in this article, I suggest that you have MySQL installed. I also recommend phpMyAdmin as a visual interface to MySQL.

The following applications make it very easy to install both MySQL and phpMyAdmin on your local machine:

We are going to use command line for queries. WAMP already comes with a MySQL Console. For MAMP, you may want to read this article.

CREATE DATABASE: Creating a Database

Here comes our very first query. We are going to be creating a database to work with.

First, open up your MySQL Console and login. For WAMP, the default password is blank. For MAMP, the password should be ‘root’ by default.

After logging in, type this query and hit enter:

CREATE DATABASE my_first_db;

Note that semicolon (;) is added at the end of the query, just like at the end of lines of code.

Also, the special words ‘CREATE DATABASE’ are case insensitive, along with all special words in SQL. But for the sake of readability, we will be writing them in uppercase.

Optional: Character Set and Collation

If you would like to set the default character set and collation, you can write the same query like this instead:

CREATE DATABASE my_first_db DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

Here is a list of supported character sets and collations in MySQL.

SHOW DATABASES: List All Databases

This query is used to get a list of all databases you have.

DROP DATABASE: Delete a Database

You can delete an existing database with this query.

Be careful with this query, because it gives you no warnings. If you have tables and data under the database, they will all be deleted instantly.

USE: Selecting a Database

This technically is not a query. It is a ‘statement’ and does not require a semicolon at the end.

It tells MySQL to select a default database to work with, for the current session. Now we are ready to create tables and do other things under this database.

What is a Database Table?

You can think of a database table like a spreadsheet or csv file that holds structured data.

Just like in this example, tables have column names, and rows of data. With SQL queries we can create these tables. We can also add, read, update and delete the data.

CREATE TABLE: Creating a Table

With this query we can create tables in the database. Unfortunately the MySQL documentation is not very friendly for new learners. The structure of this type of query can get very complex, but we will start with an easy one.

The following query will create a table with 2 columns.

CREATE TABLE users (
	username VARCHAR(20),
	create_date DATE
);

Note that we are able to write a query in multiple lines, and even use tabs for indentation.

First line is easy. We just create a table named ‘users’. Following that, in parantheses, we have a list table columns separated by commas. After each column name, we have a data type, such as VARCHAR or DATE.

VARCHAR(20) means that the column is a string type, and can be a maximum of 20 characters long. DATE is also a data type that is specifically used for storing dates, in this format: ‘YYYY-MM-DD’.

PRIMARY KEY

Before we run that query, we should also include a column for ‘user_id’, which will be a PRIMARY KEY. Without getting too much into the details, you can think of a PRIMARY KEY as a way to identify each row of data in a table.

Now the query becomes:

CREATE TABLE users (
	user_id INT AUTO_INCREMENT PRIMARY KEY,
	username VARCHAR(20),
	create_date DATE
);

INT makes this a 32bit integer type (i.e. numeric). AUTO_INCREMENT automatically generates a new id number every time we add new rows of data. It is not required, but makes it much more convenient.

This column does not have to be an integer, but it is the most commonly used type. Having a PRIMARY KEY column also is not required, but it is strongly recommended for good database design and performance.

Let’s run the query:

SHOW TABLES: List All Tables

This query allows you to get a list of tables that are currently in the database.

EXPLAIN: Show Table Structure

To see the structure of an existing table, you can use this query.

Fields (aka. columns) are listed in the results, with their properties.

DROP TABLE: Delete a Table

Just like DROP DATABASES, this query deletes a table and its contents, without a warning.

ALTER TABLE: Modify a Table

This query also can have quite a complex structure because of the multitude of changes it can perform on a table. Let’s look at some simple examples.

(Make sure to re-create the table we just dropped or the following queries obviously won’t work.)

Add a Column

ALTER TABLE users
	ADD email VARCHAR(100)
	AFTER username;

Thanks to the readability of SQL, I don’t think that query even needs an explanation.

Remove a Column

That was also very simple. But use it with caution as it permanently removes data without a warning.

Re-add the email column because we are going to be using it later:

ALTER TABLE users
	ADD email VARCHAR(100)
	AFTER username;

Modify a Column

Sometimes you may want to change the properties of a column, so you don’t have to delete and recreate it.

That renamed the username column to ‘user_name’ and changed the type from VARCHAR(20) to VARCHAR(30). A change like this should not disturb any of the existing data in the table.

INSERT: Add Data to a Table

Let’s add some data into the table using this query.

As you can see, VALUES() contains the list of field values, separated by commas. The string values are enclosed in single quotes. And the values need to be in the order of the columns that were defined when we created the table.

Note that the first value is NULL for the PRIMARY KEY field we called ‘user_id’. We do this so that an id is automatically generated, because the column is set to AUTO_INCREMENT. When entering a row of data for the first time, the id will be 1. Next inserted row will be 2 and so on…

Alternate Syntax

Here is another syntax for inserting rows.

This time we are using the keyword SET instead of VALUES, and it is not followed by paratheses. There are a few things to note here:

  • A column can be omitted. For example we did not assign a value to user_id, which will default to the AUTO_INCREMENT functionality. If you omit a VARCHAR column, it would default to an empty string (unless a different default value was specified during table creation).
  • Each column has to be referenced by its name. Because of this, they can be in any order, unlike the previous syntax.

Alternate Syntax 2

Here is yet another syntax.

Again, since each column is referenced by name, they can be in any order.

LAST_INSERT_ID()

You can use this query to get the AUTO_INCREMENT id for the last inserted row, in the current session.

NOW()

I think it is a good time to demonstrate how you can use a MySQL function inside your queries.

The NOW() function returns the current date. So you can use it to automatically set a DATE column to the current day while inserting a new row.

Note that we received a warning from MySQL, but it is not a big deal. The reason is that NOW() actually returns time information as well.

But the create_date column we created only contains the date, and not the time, therefor the returned data was truncated. We could use the CURDATE() function instead, which returns just the date, but the data stored at the end would be the same either way.

SELECT: Read Data from a Table

Obviously the data we added would be useless unless we can read it. This is where the SELECT query comes in.

Here is the simplest possible SELECT query for reading from a table:

In this case, the asterisk (*) means that we asked to fetch all the columns from the table. If you want only specific columns, the query would look like this:

WHERE Clause

More often than not, we are only interested in some of the rows, and not all. For example, let’s say we want the email address for the user ‘nettuts’.

Think of it like an IF statement. WHERE allows you to put conditions in the query for the results you are looking for.

Note that for the equality condition, only a single equal sign is used (=), instead of double (==) which you might be used to from programming.

You can use other comparison conditions too:

AND and OR can be used to combine conditions:

Note that numeric values do not have to be inside quotes.

IN()

This is useful for matching multiple values.

LIKE

This allows you to do wildcard searches.

Percentage sign (%) is used as the wildcard.

ORDER BY Clause

If you want the results to be returned in a specific order, use this clause:

The default order is ASC (i.e. ascending). You can add DESC to reverse order it.

LIMIT … OFFSET …

You can limit the number of returned results.

LIMIT 2 just gets the first 2 results. LIMIT 1 OFFSET 2 gets 1 result, after the first 2 results. LIMIT 2, 1 means the same thing, but note that the first number is the offset and the second number is the limit.

UPDATE: Update Data in a Table

This query is used for updating the data in a table.

Most of the time, it is used with a WHERE clause, because you would want only specific rows to be updated. If a WHERE clause is not provided, all rows would be updated with the same changes.

You can also use a LIMIT clause to limit the number of rows to be updated.

DELETE: Delete Data from a Table

Just like UPDATE, this query is also usually used with a WHERE clause.

TRUNCATE TABLE

To delete the entire contents of a table, you can just do this:

DELETE FROM users;

But it is usually more performance efficient to use TRUNCATE instead.

TRUNCATE also resets the AUTO_INCREMENT numbers so a new row will again have the id 1. But this does not happen with a DELETE query, and the counter keeps going up.

Escaping String Values and Special Words

String Values

Certain characters need to be escaped, otherwise you can have problems.

Backslash (\) is used for escaping.

This is also very important for security reasons. Any user input going into the database needs to be properly escaped. In PHP, you use the mysql_real_escape_string() function or use prepared statements since they do escaping automatically.

Special Words

Since MySQL has many special words like SELECT or UPDATE, you can prevent collision by putting quotes around your table and column names. But these are not the regular quotes; you need to use the backtick (`) character.

Let’s say you want to add a column named ‘delete’ for some reason:

Conclusion

Thank you for reading the article. Hopefully I was able to show you that SQL has an easy learning curve yet it is very powerful.

Please leave your comments and questions, and have a great day!

Ready to take your skills to the next level, and start profiting from your scripts and components? Check out our sister marketplace, CodeCanyon.

CodeCanyon

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Ollie

    Please take this as constructive criticism. I feel this is a really good quick reference guide for beginners, but not the best tutorial. You do a good job of explaining the “what” but not the “why”, which I think makes it harder for students to learn and remember.

    • http://adamjennings.co.uk Adam

      agree with ollie. a top ‘what’ tut, but could do with understanding how i could put it into practice, uses and stuff.

    • kuldeep

      I think its great tutorial , he explain everything with example, I am not getting why u still needed ‘WHY’? Burak thanks for the tutorial….

      • http://thedigitalyardsale.com Digital Yard Sale

        So you don’t care why you’re supposed to do certain things, you just follow instructions blindly?

    • http://mdgrech.com Michael Grech

      I think this is an excellent tutorial too. i don’t understand what Ollie is asking though. His criticism is rather vague.

      @Ollie, what exactly do you mean by explain ‘why’? Like how databases work from a mathematics standpoint or why a users would use a database in the first place?

      • kevin

        Why is having a primary key important to good database design?

  • http://tutorijali.hdonweb.com/ Ivan Mišić

    Great tutorial :-)

  • Momo from france

    Trés trés bien !

  • Girish

    This was very helpful dude.. :)

  • http://www.monieweb.com Monie

    Anyway I can print this tutorial?

  • http://design-fury.com/portfolios/ Anthony

    Overall, this is great tutorial. It really is helping me understand Sql; I am following all of the explanations with ease. However, I can’t seem to figure out how to work MAMP. I downloaded it as suggested, and once I open the application it takes me to a website where I can’t seem to apply what is being described.

    Maybe I’m the only one, but I could use a little help on actually getting started.

    Any help would be greatly appreciated.

    • jason

      Youtube can be very helpful

  • Shano

    This is not an exclusive tutorial it is already on some other website

    • http://www.jeffrey-way.com Jeffrey Way

      Really? Can you send me a link?

  • http://w3spice.com waqas

    very nice indeed -:)

  • Muksheed

    I this is a wonderfull tute & Thank U very Much sir…….

  • Can****yon

    Simple. Well explained. Nice. Thanks…

  • Kieran

    Thanks Burak!

  • leonel

    nice tuto … something that u miss is how to delete a column from a table

    also how can i add a colum in the top .. cuz u only show the after option.

  • badb

    well I study Mysql at the moment your tutorial explains some of the basics features but doesn’t cover enough for a basic mysql understanding. I’m sorry to tell you that but there is much more complete tutorials on the net to learn mysql “the easy way”.

    You got paid for that one ?

    here few critics:

    nothing about sql_mode.
    nothing about innodb/Myisam,
    nothing about \G displays
    nothing about source to import or mysqldump to export db which is very handy for beginners, most of students work at home/uni/college and transport work on external devices.
    nothing about show create table which is handy for beginners,
    auto_increment attribut works with PK nothing about that….

    you introduce collation at the beginning but without any kind of explanation why ? may be because it’s not that straight forward for the beginning of a tutorial you should have used the default setting, instead of playing with character set and collations….if the guy write is first db (which is your example)
    this-> CREATE DATABASE my_first_db DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

    is not dummy friendly at all….

    well about dummy where is the option –i-am-a-dummy ? It could be good for some people to experiment with that mode the first times, don’t you think ? and I’m sorry again but using XAMP or LAMP or Easyphp or whatever ..is not god practice to get the concept of each entities… MYSQL works without apache and php, if you want your readers to understand this consept, you have to show them that MYSQL works independently from anything else, you don’t need to install XAMP and co. to play with mysql.

    there are few other points I’ve seen but I don’t have much time see ya.

    • http://www.phpandstuff.com Burak
      Author

      Re-read the title. It’s “SQL” for beginners, not “MySQL”. A lot of what you said is very MySQL specific.

      Also SQL is a language, MySQL is an RDBMS. The articles focus is on language; and again a lot of what you said is about administration, not language.

      • http://www.wickedsoftware.net michael herndon

        The main image for the tutorial does slant towards the mysql logo of the dolphin with orange and blue text. Which could lead to confusion.

  • RJHBookLinux

    Thank you VERY much for the tutorial! Extremely informative, and a great easy start for learning SQL! Don’t mind the nay-sayers, I think it was great! I’m pumped to get started on part 2 and 3 of the series!

    Yes, to the people who think this wasn’t informative enough, open your eyes. The article is titled “SQL for Beginners” for crying out loud! Furthermore, if you dug a little bit deeper, you’d see that this is only part 1 of a 3 part article.

    Thanks again dude, very good tut! :D

  • http://www.kodyaz.com SQL-Developer

    A great tutorial listing all requirements and set up instructions for new learners.
    I’m very happy to see that the author of this useful article is from my country.

  • http://ryscript.co.cc ryan

    this is really good TUT. for mysql beginners. nice TUT.

  • http://www.facebook.com/chughgaurav Gaurav

    Great articles , these are must read for all developers to learn faster .

  • john

    nice and simple, thanks.

  • Jaywalker

    Great tutorial. Easy reading and quite interesting. Thanks.

  • http://thisisquitegood.blogspot.com Rajesh Kumar

    Thanks!
    I am new to database and I found that this is quite good article to start with database queries.

  • Waseem

    Thanks 4 Such a nice tutorial…..

  • http://alkisl.tumblr.com Alkis

    Thanks man, this helped a lot!

  • http://www.barrymcgee.co.uk Barry McGee

    I found this very useful, many thanks!

  • http://menian.eu/ Yasen Vasilev

    Pretty good tutorial! But still it’s a bit hard for complete starters with SQL. I had to read from some other place at first to grasp more details and explanations to feel ok with that one. Have it as advice, friends – learn from few places, you will always find something new here or there (*:

  • victor

    you made this easy thanks

  • DeFSatan

    The easiest and best explained tutorials for starters! Thanks a bunch man.

  • http://www.impulsis.com impulsis

    Nice one. We’ll use the tutorial for our interns I think. thx again.

  • Vinit

    Very Very Very Very Very Very Very Very good and help full
    thanks a lot

  • http://DrainedApple.com Squiggle

    I’m currently in an SQL class and my teacher keeps skipping around expecting us to keep up. This was a great read since I’ve never used SQL before and its nice to read something so simple and straight forward.

    Thanks for posting!

  • eLyAIR

    Very nice tut!! thanks a lot Burak. keep up the great job :-)

  • Garrett Heinlen

    This article/series is very informative, and I really glad someone has taken the time to explain and go over it in such depth. Thanks again.

  • LA

    Wow very information series of tuts! I really appreciate it!

  • Umaselvan

    Thanks a lot.. :) useful for beginners like me…..

  • Donna

    Thanks for sharing the tutorial!!! I found it very useful. Is there a Lesson 2? I am ready : )

  • http://c.jwally.com.ve/ Ignacio Aular

    Hello there.! Thank you very much.

  • http://www.agileinfoways.com/ Mittul Chauhan

    thanks .. this was really informative

  • Gary

    Entering “blank” for the password doesn’t work for me. The console “beeps” at me and then shuts down. Any suggestions?

  • sandhanamurali

    i am really enjoyed with your valuable script .i would like to know how to use these real time application ,if you would have given that would be very useful to me.

  • TRGold

    So far, great tutorial. It’s really giving me the chance to grapple with SQL and get the basics. One point: This IS an ‘SQL for beginners’ tutorial, and significant changes from step to step should be pointed out.

    For instance in the UPDATE section. I wrestled for 30 minutes trying to find out where I was getting an Error 1064 Syntax error. You should maybe point out that there is no comma separator between UPDATE SET statements and WHERE statement. Up until that point in the tutorial, all separate statements were separated with a comma. SQL documentation does a poor job of highlighting this, and so did this tutorial. Remember this is for beginners, you have spell some things out for us thick headed learners.

    Other than that, I think it is a great place to start learning SQL.

  • Oksana

    Excellent ! Thank you very much.

  • sdfd

    ssss

    • yyy

      yyy

  • Pain

    Insert into table employee(id int, name varchar(10) not null)
    if i run this query it will execute even if i put nothing in the name field.
    What i want is that at least one letter must be put in the field otherwise it show an error. is there any other command for that because this command not working?

  • kwandoa

    This was super awsome. Thank YOU!!

  • Tevfik Hurkan

    Burak teşekkürler. Ne güzel bir çalışma olmuş, eline emeğine sağlık. (Just thanked the author in our common mother tongue.)

  • newbie

    Good one. Had no trouble understanding

  • Marcin EF

    Absolutely stellar article!