Advertisement
❮ Previous: SQL Syntax Next: SQL Select Distinct ❯

SQL Select

The SELECT statement is the foundational building block of SQL, used to retrieve data from a database table.

It acts like a camera lens, allowing you to choose exactly which columns and rows you want to display.

Basic SELECT Syntax

Retrieve All Columns

Use the asterisk (*) wildcard to view every single column in a table.

SELECT * FROM employees;

Retrieve Specific Columns

List the exact column names separated by commas to pull only the data you need. This is faster and uses less memory.

SELECT first_name, last_name, salary FROM employees;

Rename Columns in the Output (AS)

You can use aliases to give columns temporary, reader-friendly names in your final report.

SELECT first_name AS "First Name", salary * 12 AS "Annual Salary"FROM employees;

Common Ways to Filter and Refine SELECT

Eliminate Duplicates (DISTINCT)

If a column contains identical values across rows, DISTINCT forces SQL to return only unique, individual values.

-- Shows unique department names, removing any duplicates

SELECT DISTINCT department FROM employees;

Filter Rows (WHERE)

Add a WHERE clause to extract only the records that meet a specific condition.

SELECT first_name, department, salary FROM employeesWHERE salary > 60000;

Limit the Results (LIMIT or TOP)

If a table has millions of rows, you can cap the output to a specific number.
(Note: Most modern databases use LIMIT at the end, but SQL Server uses SELECT TOP at the beginning).

-- MySQL, PostgreSQL, SQLite

SELECT * FROM employees LIMIT 5;

-- SQL Server (T-SQL)

SELECT TOP 5 * FROM employees;

A Complete SELECT Blueprint

When you chain multiple clauses together, they must follow this exact chronological order, or the database will throw a syntax error:

SELECT department, AVG(salary) AS avg_sal  -- 5. Choose columns / math operations

FROM employees                              -- 1. Pick the source table

WHERE status = 'Active'                     -- 2. Filter individual rows

GROUP BY department                         -- 3. Group identical rows together

HAVING AVG(salary) > 50000                  -- 4. Filter the grouped results

ORDER BY avg_sal DESC                       -- 6. Sort the final output

LIMIT 3;                                    -- 7. Cut off the display list
❮ Previous: SQL Syntax Next: SQL Select Distinct ❯
Advertisement