DATABASES / LESSON 02
SQL Basics.
Learn to write your first SQL queries to read data from a database

Loading the lesson…
Loading activities…
DATABASES / LESSON 02
Learn to write your first SQL queries to read data from a database

Loading the lesson…
Loading activities…
SQL (Structured Query Language) is how you talk to a database. You'd use English to ask a librarian for a book, and you use SQL to ask a database for data. Good news? SQL reads almost like plain English, which makes it one of the friendliest programming languages out there to pick up.
The most basic SQL command there is happens to be SELECT. It's how you ask the database to show you some data.
Let's pull that apart.
SELECT means "I want to get some data"* means "give me every column"FROM users means "look in the users table"; marks the end of the statementThat query hands back every row and every column from the users table. That's it. You just read a database.
You won't always need every column. To grab just a few, list them by name.
This returns only the name and email columns and skips everything else. When a table has a ton of columns and you only need a couple, this is the more efficient move.
The WHERE clause lets you filter which rows come back.
Here are the comparison operators you'll use the most.
= equals!= or <> not equals> greater than< less than>= greater than or equal<= less than or equalLIKE pattern matching (% is a wildcard)You can stack more than one condition together.
Use ORDER BY to put your results in order.
Use LIMIT to cap how many rows come back.
SQL comes with built-in functions that summarize your data for you.
Here's a more realistic query that mixes everything you just learned.
Read it out loud and it's basically a sentence... "select the name and email from users where age is at least 18, ordered by creation date (newest first), limit to 5 results."
SQL keywords don't care about capital letters, so all three of these do the exact same thing.
The convention, though, is SQL keywords in UPPERCASE and table and column names in lowercase. Your queries get WAY easier to read that way (and future you will say thanks).
SELECT gets data, FROM picks the table and WHERE filters the rowsORDER BY to sort results and LIMIT to cap how many rows come backCOUNT(), AVG() and MAX() summarize your dataNow that you can read data out of existing tables, the next step is making tables of your own. You'll lay out the structure of your data, pick the right data types and set up constraints that keep your data clean...