In this tutorial introduces you to the basics of the SQL Server Select statement, focusing on how to query SELECT with WHERE, GROUP BY, and ORDER BY against a single table.
Database tables are objects that store all the data in a database. In a table, data is logically organized in a row-and-column format. Select is the most commonly used statement in SQL. The SELECT Statement in SQL is used to retrieve or fetch data from a database. We can fetch either the entire table or according to some specified rules.
In this case, SQL Server processes the clauses in the following sequence order:
FROM -> WHERE -> GROUP BY -> HAVING -> SELECT -> DISTINCT -> ORDER BY
SQL Query mainly works in three phases to execute following clauses.
We will explain with an example. Suppose we have a students table as follows:
CREATE TABLE [students](
[StudentID] [int] IDENTITY(1,1) NOT NULL,
[StudentName] [varchar](100) NULL,
Marks [int],
Section [varchar](100),
[StudentAge] [int] NULL
) ON [PRIMARY]
GO
Now insert some data in students table. It looks like that:
The following query finds the StudentName and Marks of all students:
SELECT StudentName, Marks
FROM students
Here is the result:
The following query finds all the columns of students table:
SELECT * FROM students
Here is the result:
Advantage - Retrieve All Columns of a Table
Disadvantage - Retrieve All Columns of a Table
To filter rows based on one or more conditions on table, you use a WHERE clause as shown in the following example:
SELECT * FROM students where Section='A'
Here is the result:
To sort the result set based on one or more columns, you use the ORDER BY clause as shown in the following example:
SELECT
*
FROM
students WHERE Section='A' ORDER BY studentName
Here is the result:
To group rows into groups, you use the GROUP BY clause. you use the GROUP BY clause as shown in the following example:
SELECT
studentage,
count(*)
FROM
students where studentage<20 group by student age ORDER BY studentage
Here is the result:
To filter groups based on one or more conditions, you use the HAVING clause. as shown in the following example:
SELECT
studentage,
count(*)
FROM
students where studentage<20 group by studentage HAVING COUNT (*) > 1 ORDER BY studentage
Here is the result: