SELECT Statement
SELECT statement is used to fetch the data from database tables, the data is returned in the form of result tables.
These result tables are also called result sets. The SELECT statement provides almost all the features of the SELECT statement in standard ANSI 89 SQL.
The Order in which Columns are returned is not guaranteed, always use the name of column instead of column index in your .Net code.
To understand each part of select statement, use the following list to decide when to use what.
- Use DISTINCT clause to query unique rows in a table.
- Use INNER JOIN or LEFT JOIN to query data from multiple tables.
- Use WHERE clause to filter rows in tables
- Use ORDER BY clause to sort the result set in required order.
- Use LIMIT OFFSET clauses to constrain the number of rows returned.
- Use GROUP BY to get the rows as groups and apply aggregate function for each group.
- Use HAVING clause to filter groups.
Syntax
Following is the full syntax of SELECT statement.
SELECT [DISTINCT] [ * OR] Column_List
FROM Table_List
[JOIN TABLE ON Join Condition(s)]
[WHERE row Filter(s)]
[ORDER BY column(s)]
[LIMIT count OFFSET offset]
[GROUP BY Column(s)]
[HAVING Group Filter];
Example
The following are examples of select statement.
SELECT * FROM Customers;
SELECT FirstName, LastName FROM Customers;
SELECT FirstName, LastName
FROM Customers
ORDER BY LastName;
SELECT FirstName, LastName
FROM Customers
WHERE Id = 1;
SELECT FirstName, LastName
FROM Customers
WHERE Id IN (1 , 2, 3, 4);
SELECT FirstName, LastName
FROM Customers
WHERE LastName = 'Smith'
LIMIT 10 OFFSET 0;