Please enable JavaScript to use CodeHS

Data and Databases

SQL queries

SQL is the language used to ask questions to a relational database. You can use it to filter, sort, and summarize data. In this tutorial, you will learn four of the most common SQL commands.

SQL ~10 min Middle / High School
The Big Idea

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.


Query Basics

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.


Filtering

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.


Sorting and Limiting

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;

Interactive

Query builder

Try filtering and sorting the tiny Students table below. Choose a grade filter and a sort order, then click Run query.

idfirst_namelast_namegrade
1MayaChen9
2LeoRamos10
3SofiaKim9
4AidenPatel11
5EmmaJohnson10
6 NoahWilliams12

Your query: SELECT * FROM Students;


Code

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.


Your Turn

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;


Check Yourself

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.