T-SQL Tutorial

SQL SELECT


The SELECT statement in SQL Server is used to retrieve data from one or more tables in a database.


SELECT syntax

The basic syntax of a SELECT statement is as follows:

SELECT column(s)FROM table WHERE condition;
SELECT * FROM table WHERE condition;


You can select one or more columns from a table by specifying their names, separated by commas, after the SELECT keyword. The FROM keyword is followed by the name of the table from which you want to retrieve data. The WHERE clause is used to filter the data based on certain conditions.


You can also use the JOIN keyword to combine data from multiple tables. For example, to select data from two tables called "orders" and "customers", you can use the following query:

SELECT o.order_id, o.order_date, c.name
FROM orders o JOIN customers c
ON o.customer_id = c.customer_id;

This query will return the order_id, order_date, and customer name for all orders in the "orders" table that have a matching customer ID in the "customers" table.


You can also use the GROUP BY and HAVING clauses to group and filter the data based on aggregate functions such as COUNT, SUM, AVG, etc.

SELECT COUNT(*) as Total_Orders,
SUM(order_total) as Total_Sale
FROM orders
GROUP BY order_date
HAVING COUNT(*) > 10;

This query will return the total number of orders and the total sales for each day, but only for days where there are more than 10 orders. The above is just a basic overview of the SELECT statement in SQL Server, there are many other clauses and options available to retrieve, filter and aggregate data.


Examples

For the following examples we will use the store table.

OBJECT_IDPRICE
1100
2300
3800
4300

Example 1:

Return all rows with all columns from the table.

SELECT * FROM store;

OBJECT_IDPRICE
1100
2300
3800
4300

Example 2:

Select from store table all rows for price column.

SELECT price FROM store;

PRICE
100
300
800
300