SELECT Statement Fundamentals
The SELECT statement is the foundation of SQL querying. It allows you to retrieve data from one or more tables.
Basic Syntax
sql1SELECT column1, column2, ...2FROM table_name;
Selecting All Columns
Use * to select all columns from a table:
sql1SELECT * FROM students;
This returns every column for every row in the students table.
Selecting Specific Columns
List the columns you want, separated by commas:
sql1SELECT first_name, last_name, email2FROM students;
This is more efficient than SELECT * because it only retrieves the data you need.
Column Aliases
You can rename columns in the output using AS:
sql1SELECT first_name AS "First Name",2 last_name AS "Last Name",3 gpa AS "Grade Point Average"4FROM students;
The WHERE Clause
Filter rows using conditions:
sql1SELECT * FROM students2WHERE gpa > 3.5;
Comparison Operators
| Operator | Description |
|---|---|
= | Equal |
<> or != | Not equal |
> | Greater than |
< | Less than |
>= | Greater than or equal |
<= | Less than or equal |
Examples
sql1-- Students with GPA exactly 3.52SELECT * FROM students WHERE gpa = 3.5;34-- Students with GPA above 3.05SELECT * FROM students WHERE gpa > 3.0;67-- Find a specific student by email8SELECT * FROM students WHERE email = 'alice.brown@student.edu';
ORDER BY Clause
Sort results using ORDER BY:
sql1-- Sort by GPA ascending (lowest first)2SELECT * FROM students3ORDER BY gpa;45-- Sort by GPA descending (highest first)6SELECT * FROM students7ORDER BY gpa DESC;89-- Sort by multiple columns10SELECT * FROM students11ORDER BY major, last_name;
LIMIT and OFFSET
Control how many rows are returned:
sql1-- Get only the first 5 students2SELECT * FROM students3LIMIT 5;45-- Skip the first 10, then get 56SELECT * FROM students7LIMIT 5 OFFSET 10;89-- Top 3 students by GPA10SELECT * FROM students11ORDER BY gpa DESC12LIMIT 3;
DISTINCT
Remove duplicate values:
sql1-- Get unique majors2SELECT DISTINCT major3FROM students;45-- Unique city/state combinations6SELECT DISTINCT city, state7FROM customers;
Combining Clauses
Clauses must appear in this order:
sql1SELECT columns2FROM table3WHERE conditions4ORDER BY columns5LIMIT number6OFFSET number;
Example
sql1SELECT first_name, last_name, gpa2FROM students3WHERE major = 'Computer Science'4ORDER BY gpa DESC5LIMIT 5;
This query:
- Selects name and GPA columns
- From the students table
- Only for Computer Science majors
- Sorted by GPA (highest first)
- Limited to top 5 results
Summary
SELECTretrieves data from tables- Use
*for all columns or list specific columns WHEREfilters rows based on conditionsORDER BYsorts results (ASC or DESC)LIMITrestricts the number of rows returnedDISTINCTremoves duplicate values