
For an instructor lead, in-depth look at learning SQL click below.
If you’re new to SQL (Structured Query Language), it might seem a bit daunting at first, but don’t worry – with some practice, you’ll quickly get the hang of it. Here, we will walk through the basics of SQL querying.
What is SQL?
SQL (Structured Query Language) is a programming language used to communicate with and manipulate databases. Most of the actions you need to perform on a database are done with SQL statements.
Getting Started
Before you start, you should have a database software installed on your computer. You could use MySQL, SQLite, PostgreSQL, or Microsoft SQL Server. For this guide, we’ll use MySQL because it’s widely used and open source.
Connecting to a Database
First, you will learn how to connect to a database. You will use the MySQL command-line tool.
1 2 3 |
mysql -u root -p |
The -u flag specifies the user (in this case, root), and the -p flag tells the system to issue a prompt for a password.
Creating Tables
Let’s start by creating a table in our database. Here’s how to create a table named ‘users’ with columns ‘id’, ‘name’, and ’email’.
1 2 3 4 5 6 7 8 |
CREATE TABLE users ( id INT AUTO_INCREMENT, name VARCHAR(100), email VARCHAR(100), PRIMARY KEY(id) ); |
Inserting Data
Now that we’ve created a users table, let’s insert some data into it.
1 2 3 4 5 |
INSERT INTO users (name, email) VALUES ('John Doe', <a href="mailto:'john@example.com'" >'john@example.com'</a>), ('Jane Doe', <a href="mailto:'jane@example.com'" >'jane@example.com'</a>); |
Selecting Data
To retrieve the data you’ve just inserted, you’d use a SELECT statement, like this:
1 2 3 |
SELECT * FROM users; |
Updating Data
If you need to update records in your table, you can use an UPDATE statement. Here’s how you would change John’s email:
1 2 3 4 5 |
UPDATE users SET email = <a href="mailto:'john_doe@example.com'" >'john_doe@example.com'</a> WHERE name = 'John Doe'; |
Deleting Data
To delete data from your database, you can use a DELETE statement. Here’s how to delete Jane Doe:
1 2 3 |
DELETE FROM users WHERE name = 'Jane Doe'; |
Congratulations! You have now learned the basics of SQL querying! Though this is just the tip of the iceberg, these are the most commonly used SQL commands, and they are enough to do a great deal of database work.