Welcome back, future SQL experts! Now that you know how to insert data into a table, the next step is learning how to retrieve that data.
In this chapter, we’ll cover:
- The basic
SELECTstatement - Selecting specific columns
- Using
WHEREto filter results - Aliasing columns
- Sorting with
ORDER BY - Real examples using our
studentstable
Let’s dive in! ๐
๐ง Why SELECT is Important
The SELECT statement is the most commonly used command in SQL. Whether you're displaying a report, fetching records for analysis, or just checking if your data was saved properly — you'll use SELECT .
✅ Syntax
SELECT column1, column2, ... FROM table_name;
To get all columns from a table:
SELECT * FROM table_name;
๐งช Example Table: students
Let's continue using our sample table:
CREATE TABLE students
( id INT ,
name VARCHAR ( 50 ),
age INT ,
course VARCHAR ( 30 ),
marks DECIMAL ( 5 , 2 ));
And here are some sample rows:
| id | name | age | course | marks |
|---|---|---|---|---|
| 1 | Rahul Sharma | 21 | SQL | 85.50 |
| 2 | Anjali Mehta | 22 | SQL | 91.75 |
| 3 | Vikas Gupta | 23 | SQL | 88.00 |
๐ Select All Records
SELECT * FROM students;
This will return all columns and rows in the table.
๐ฏ Select Specific Columns
SELECT name, marks FROM students;
This shows only the student names and their marks.
๐ Filter Results with WHERE
SELECT * FROM students WHERE marks > 85 ;
This will show only students who scored more than 85 marks.
More filter examples:
SELECT name FROM students
WHERE age = 22 ;
SELECT * FROM students
WHERE course = 'SQL' AND marks > 90 ;
๐ท Use Aliases with AS
Aliases help rename columns for readability:
SELECT name AS "Student Name", marks AS "Score" FROM students;
๐ข Sorting Results with ORDER BY
SELECT * FROM students ORDER BY marks DESC ;
ASC: Ascending (default)DESC: Descending
You can also sort by multiple columns:
SELECT * FROM students ORDER BY course, name;
๐ Practice Tasks
Try writing queries for these:
- Show names and marks of students who scored above 90.
- Show all students sorted by age, oldest first.
- Display all students who are enrolled in "SQL" and are younger than 23.
Post your answers in the blog comments! I’ll review them. ๐
๐ง Common Mistakes
| Mistake | Issue |
|---|---|
SELECT name, age students; |
Missing FROM keyword |
SELECT * FROM table; |
Incorrect table name |
WHERE age = 'twenty' |
Wrong data type in condition |
๐ Summary
| Task | SQL Example |
|---|---|
| Select all columns | SELECT * FROM students; |
| Select specific columns | SELECT name, marks FROM students; |
| Use filters | WHERE age >20 |
| Sort results | ORDER BY marks DESC |
| Rename columns | AS keyword |