15 minlesson

SELECT Statement Fundamentals

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

sql
1SELECT column1, column2, ...
2FROM table_name;

Selecting All Columns

Use * to select all columns from a table:

sql
1SELECT * FROM students;

This returns every column for every row in the students table.

Selecting Specific Columns

List the columns you want, separated by commas:

sql
1SELECT first_name, last_name, email
2FROM 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:

sql
1SELECT 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:

sql
1SELECT * FROM students
2WHERE gpa > 3.5;

Comparison Operators

OperatorDescription
=Equal
<> or !=Not equal
>Greater than
<Less than
>=Greater than or equal
<=Less than or equal

Examples

sql
1-- Students with GPA exactly 3.5
2SELECT * FROM students WHERE gpa = 3.5;
3
4-- Students with GPA above 3.0
5SELECT * FROM students WHERE gpa > 3.0;
6
7-- Find a specific student by email
8SELECT * FROM students WHERE email = 'alice.brown@student.edu';

ORDER BY Clause

Sort results using ORDER BY:

sql
1-- Sort by GPA ascending (lowest first)
2SELECT * FROM students
3ORDER BY gpa;
4
5-- Sort by GPA descending (highest first)
6SELECT * FROM students
7ORDER BY gpa DESC;
8
9-- Sort by multiple columns
10SELECT * FROM students
11ORDER BY major, last_name;

LIMIT and OFFSET

Control how many rows are returned:

sql
1-- Get only the first 5 students
2SELECT * FROM students
3LIMIT 5;
4
5-- Skip the first 10, then get 5
6SELECT * FROM students
7LIMIT 5 OFFSET 10;
8
9-- Top 3 students by GPA
10SELECT * FROM students
11ORDER BY gpa DESC
12LIMIT 3;

DISTINCT

Remove duplicate values:

sql
1-- Get unique majors
2SELECT DISTINCT major
3FROM students;
4
5-- Unique city/state combinations
6SELECT DISTINCT city, state
7FROM customers;

Combining Clauses

Clauses must appear in this order:

sql
1SELECT columns
2FROM table
3WHERE conditions
4ORDER BY columns
5LIMIT number
6OFFSET number;

Example

sql
1SELECT first_name, last_name, gpa
2FROM students
3WHERE major = 'Computer Science'
4ORDER BY gpa DESC
5LIMIT 5;

This query:

  1. Selects name and GPA columns
  2. From the students table
  3. Only for Computer Science majors
  4. Sorted by GPA (highest first)
  5. Limited to top 5 results

Summary

  • SELECT retrieves data from tables
  • Use * for all columns or list specific columns
  • WHERE filters rows based on conditions
  • ORDER BY sorts results (ASC or DESC)
  • LIMIT restricts the number of rows returned
  • DISTINCT removes duplicate values
SELECT Statement Fundamentals - Anko Academy