SELECT Statement

Retrieves rows from one or more tables or views. The T-SQL SELECT statement is the foundation for querying data in SQL Server.

Syntax

The basic syntax of the SELECT statement is as follows:

SELECT
    [ ALL | DISTINCT ]
    
    [ INTO new_table ]
    [ FROM
        {  } [ ,...n ]
    ]
    [ WHERE
        
    ]
    [ GROUP BY
        [ ALL ] <group_by_expression> [ ,...n ]
    ]
    [ HAVING
        
    ]
    [ ORDER BY
         [ ASC | DESC ] [ ,...n ]
    ]
    [ OFFSET { integer_constant | <rows_or_range> { SUB செலட் |NEXT } row }
        [ FETCH { FIRST | NEXT } { integer_constant | <rows_or_range> } { ROW | ROWS } { ONLY | WITH TIES } ]
    ];

Parameters

The SELECT statement has several optional and required clauses:

Clause Description
SELECT Specifies the columns to retrieve. Use * to select all columns.
ALL Returns all rows that match the query, including duplicates. This is the default.
DISTINCT Returns only unique rows. Duplicate rows are removed.
INTO Creates a new table and inserts the result set into it.
FROM Specifies the tables or views from which to retrieve data. Supports joins.
WHERE Filters the rows based on a specified condition.
GROUP BY Groups rows that have the same values in specified columns into summary rows.
HAVING Filters groups based on a specified condition. Used with GROUP BY.
ORDER BY Sorts the result set by one or more columns.
OFFSET / FETCH Paginates the result set, skipping a specified number of rows and then fetching a certain number.

Examples

Example 1: Select all columns from a table

This query retrieves all columns and all rows from the Customers table.

SELECT *
FROM dbo.Customers;

Example 2: Select specific columns

This query retrieves the FirstName and LastName columns from the Employees table.

SELECT FirstName, LastName
FROM dbo.Employees;

Example 3: Using WHERE clause to filter rows

This query retrieves customers from the Customers table who are located in 'London'.

SELECT CustomerID, CompanyName, City
FROM dbo.Customers
WHERE City = 'London';

Example 4: Using ORDER BY clause

This query retrieves product names and prices from the Products table, ordered by price in descending order.

SELECT ProductName, UnitPrice
FROM dbo.Products
ORDER BY UnitPrice DESC;

Example 5: Using GROUP BY and HAVING

This query counts the number of customers in each city and only shows cities with more than 5 customers.

SELECT City, COUNT(*) AS NumberOfCustomers
FROM dbo.Customers
GROUP BY City
HAVING COUNT(*) > 5
ORDER BY NumberOfCustomers DESC;
Note: This documentation provides a high-level overview. For detailed syntax, specific options, and advanced usage, please refer to the official Microsoft SQL Server documentation.