SQL SELECT Statement

📘 SQL SELECT Statement

The SELECT statement is the most commonly used SQL command. It is used to retrieve data from one or more tables in a relational database.


1. Basic Syntax

SELECT column1, column2, ...
FROM table_name;
  • SELECT — specifies the columns to fetch

  • FROM — specifies the table to query

Example


2. Selecting All Columns

SELECT *
FROM employees;

✔ Good for quick inspection
✖ Avoid in production (returns unnecessary data)


3. Using WHERE to Filter Results

SELECT *
FROM employees
WHERE department = 'IT';

Filtering supports operators such as:

  • = equal

  • != or <> not equal

  • > < >= <=

  • BETWEEN

  • LIKE

  • IN

Example:


4. Sorting Results with ORDER BY

SELECT name, salary
FROM employees
ORDER BY salary DESC;
  • ASC → ascending

  • DESC → descending


5. Renaming Columns with AS (Aliases)

SELECT salary AS employee_salary
FROM employees;

6. Removing Duplicates with DISTINCT

SELECT DISTINCT department
FROM employees;

7. Limiting Results (LIMIT / TOP)

PostgreSQL / MySQL / SQLite

SELECT *
FROM employees
LIMIT 5;

SQL Server

SELECT TOP 5 *
FROM employees;

8. Using Functions in SELECT

SQL allows functions inside the SELECT list:

  • COUNT()

  • AVG()

  • SUM()

  • MIN()

  • MAX()

Example:

SELECT COUNT(*) AS total_employees
FROM employees;

9. SELECT with JOIN (Advanced)

SELECT e.name, d.department_name
FROM employees e
JOIN departments d ON e.department_id = d.id;

10. Common SELECT Pattern (Production Style)


 

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *