Example Of Select Statement In Sql

5 min read

The SELECT statement is the cornerstone of data retrieval in Structured Query Language (SQL). It acts as the primary gateway for querying databases, allowing users to fetch specific information from one or more tables. Whether you are a beginner writing your first query or a seasoned developer optimizing complex reports, mastering the SELECT statement is non-negotiable. This guide provides a comprehensive walkthrough of SELECT syntax, practical examples ranging from basic filtering to advanced joins and window functions, ensuring you can extract exactly the data you need Simple, but easy to overlook..

Understanding the Basic Syntax

Before diving into complex scenarios, it is essential to internalize the fundamental structure of a SELECT query. The database engine processes clauses in a specific logical order, distinct from the written order, which influences how you construct your logic.

The standard syntax follows this pattern:

SELECT column1, column2, ...
FROM table_name
WHERE condition
GROUP BY column1, column2, ...
HAVING condition
ORDER BY column1, column2 ... ASC|DESC;

Key Clauses Explained:

  • SELECT: Specifies the columns (or expressions) to return. Use * to select all columns, though explicit listing is a best practice for performance and maintainability.
  • FROM: Identifies the source table or view.
  • WHERE: Filters rows before any grouping occurs. It operates on individual row data.
  • GROUP BY: Aggregates rows sharing the same values in specified columns into summary rows.
  • HAVING: Filters groups after aggregation. This is where you filter on aggregate functions like COUNT() or SUM().
  • ORDER BY: Sorts the final result set. Execution happens last.

Foundational Examples: Filtering and Sorting

Let’s assume a standard Employees table with columns: EmployeeID, FirstName, LastName, Department, Salary, HireDate, and ManagerID.

1. Selecting Specific Columns

Explicitly naming columns reduces network traffic and prevents issues if the table schema changes (e.g., a new sensitive column is added).

SELECT FirstName, LastName, Department
FROM Employees;

2. Filtering with the WHERE Clause

The WHERE clause supports comparison operators (=, !=, >, <, >=, <=) and logical operators (AND, OR, NOT).

Example: Find employees in the 'Engineering' department earning over 80,000.

SELECT FirstName, LastName, Salary
FROM Employees
WHERE Department = 'Engineering' AND Salary > 80000;

3. Pattern Matching with LIKE

Use LIKE for partial string matches. The wildcard % represents zero or more characters; _ represents a single character Took long enough..

Example: Find employees whose last name starts with 'S'.

SELECT FirstName, LastName
FROM Employees
WHERE LastName LIKE 'S%';

4. Handling NULL Values

NULL represents missing or unknown data. It cannot be compared using = or !=. You must use IS NULL or IS NOT NULL.

Example: Find employees who have not been assigned a manager.

SELECT FirstName, LastName
FROM Employees
WHERE ManagerID IS NULL;

5. Sorting Results with ORDER BY

Sorting is critical for reporting. You can sort by column name, alias, or positional index (though positional is discouraged).

Example: List highest paid employees first, breaking ties by hire date (oldest first).

SELECT FirstName, LastName, Salary, HireDate
FROM Employees
ORDER BY Salary DESC, HireDate ASC;

Intermediate Techniques: Shaping Data

Moving beyond simple retrieval, SQL allows you to transform data on the fly using aliases, calculations, and conditional logic.

6. Column Aliases (AS)

Aliases rename columns in the output, improving readability. The AS keyword is optional but recommended for clarity.

SELECT FirstName || ' ' || LastName AS FullName, 
       Salary * 12 AS AnnualSalary
FROM Employees;

Note: Concatenation syntax varies by dialect (|| for PostgreSQL/Oracle, + for SQL Server, CONCAT() for MySQL).

7. Removing Duplicates with DISTINCT

DISTINCT eliminates duplicate rows in the result set based on the selected columns Small thing, real impact..

Example: Get a unique list of departments.

SELECT DISTINCT Department
FROM Employees;

8. Conditional Logic with CASE Expressions

The CASE expression adds IF-THEN-ELSE logic directly into your query. This is invaluable for categorizing data without altering the table.

Example: Categorize salary bands.

SELECT FirstName, LastName, Salary,
       CASE 
           WHEN Salary < 50000 THEN 'Junior'
           WHEN Salary BETWEEN 50000 AND 100000 THEN 'Mid-Level'
           ELSE 'Senior'
       END AS SalaryBand
FROM Employees;

9. Limiting Results (Pagination)

Different databases handle row limiting differently Less friction, more output..

  • PostgreSQL, MySQL, SQLite: LIMIT 10 OFFSET 20
  • SQL Server (2012+): OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY
  • Oracle (12c+): OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY

Example: Get the second page of 10 employees ordered by ID.

SELECT EmployeeID, FirstName, LastName
FROM Employees
ORDER BY EmployeeID
LIMIT 10 OFFSET 10; -- Standard syntax example

Aggregation and Grouping: Summarizing Data

Aggregation functions (COUNT, SUM, AVG, MIN, MAX) collapse multiple rows into a single summary value. This is where GROUP BY and HAVING become essential.

10. Basic Aggregation with GROUP BY

Example: Count employees and calculate average salary per department.

SELECT Department, 
       COUNT(*) AS EmployeeCount, 
       AVG(Salary) AS AvgSalary
FROM Employees
GROUP BY Department;

Rule of Thumb: Every column in the SELECT list that is not inside an aggregate function must appear in the GROUP BY clause.

11. Filtering Groups with HAVING

WHERE filters rows; HAVING filters groups. You cannot use aggregate functions in WHERE.

Example: Find departments with more than 5 employees.

SELECT Department, COUNT(*) AS Headcount
FROM Employees
GROUP BY Department
HAVING COUNT(*) > 5;

12. Multiple Grouping Levels

You can group by multiple columns to create hierarchies Nothing fancy..

Example: Employee count by Department and SalaryBand (using the CASE logic from above).

SELECT Department,
       CASE 
           WHEN Salary < 50000 THEN 'Junior'
           WHEN Salary BETWEEN 50000 AND 100000 THEN 'Mid-Level'
           ELSE 'Senior'
       END AS SalaryBand,
       COUNT(*) AS Count
FROM Employees
GROUP BY Department, SalaryBand
ORDER BY Department, Count DESC;

Advanced Retrieval: Joining Tables

Relational databases normalize data across multiple tables. JOIN clauses recombine this data based on related columns (keys) No workaround needed..

Assume a second table: Departments (DeptID, DeptName, Location). Think about it: departmentlinks toDepartments. On the flip side, Employees. DeptName.

13. INNER JOIN (The

Freshly Written

Fresh Content

Explore a Little Wider

Continue Reading

Thank you for reading about Example Of Select Statement In Sql. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home