What is SQL?
SQL stands for Structured Query Language. It is a special language for working with relational databases. SQL commands look a lot like plain English, which makes them easier to read than some other programming languages.
With SQL, you can create tables, insert data, update records, delete rows, and ask questions. Asking questions is called querying the database. In this tutorial, we focus on querying.
SELECT and FROM
The most common SQL query has the form:
SELECT column_name FROM table_name;
SELECT says which columns you want. FROM says which table to look in. To get all columns, use an asterisk:
SELECT * FROM Students;
This says, "Show me every column for every row in the Students table." The semicolon at the end tells the database that the command is complete.
WHERE
Databases usually hold more data than you want to see at once. The WHERE clause lets you filter rows. For example:
SELECT * FROM Students WHERE grade = 10;
This only returns students in grade 10. You can also use >, <, >=, <=, <> (not equal), and LIKE for partial text matches.
ORDER BY and LIMIT
ORDER BY sorts your results. Use ASC for ascending and DESC for descending:
SELECT * FROM Students ORDER BY grade DESC;
LIMIT caps how many rows come back. This is useful when a table has millions of rows and you only want to see the first few:
SELECT * FROM Students ORDER BY grade DESC LIMIT 5;
Query builder
Try filtering and sorting the tiny Students table below. Choose a grade filter and a sort order, then click Run query.
| id | first_name | last_name | grade |
|---|---|---|---|
| 1 | Maya | Chen | 9 |
| 2 | Leo | Ramos | 10 |
| 3 | Sofia | Kim | 9 |
| 4 | Aiden | Patel | 11 |
| 5 | Emma | Johnson | 10 |
| 6 | Noah | Williams | 12 |
Your query: SELECT * FROM Students;
SQL queries
SQL is the language used to talk to most databases. This sample creates a table, inserts rows, and asks questions of the data.
Check yourself
Write an SQL query that would find all students in grade 11, sorted by last name alphabetically.
Your query:
Sample answer: SELECT * FROM Students WHERE grade = 11 ORDER BY last_name ASC;
Quick quiz
1. What does the SELECT statement do?
2. Which clause filters rows?
3. What does ORDER BY do?
Keep learning
You can query a single table. Next, learn how tables connect to each other.
Part of the Data and Databases series.