A SELECT
query in MS SQL (Microsoft SQL Server) is used to retrieve data from a database. The basic syntax of a SELECT
query is:
SELECT column1, column2, ... FROM table_name WHERE condition ORDER BY column1, column2, ... GROUP BY column1, column2, ... HAVING condition;
Here's a breakdown of each clause:
SELECT
: Specifies the columns you want to retrieve.FROM
: Specifies the table from which to retrieve the data.WHERE
: Filters the rows based on a specified condition.ORDER BY
: Sorts the result set based on one or more columns.GROUP BY
: Groups rows that have the same values into summary rows.HAVING
: Filters groups based on a specified condition (used withGROUP BY
).
Examples:
-
Basic Query: Retrieve all columns from a table named
Employees
.SELECT * FROM Employees; -
Select Specific Columns: Retrieve only
FirstName
andLastName
from theEmployees
table.SELECT FirstName, LastName FROM Employees; -
With a Condition: Retrieve employees with a salary greater than 50,000.
SELECT FirstName, LastName, Salary FROM Employees WHERE Salary > 50000; -
Sorting Results: Retrieve all employees, sorted by
LastName
in ascending order.SELECT FirstName, LastName FROM Employees ORDER BY LastName ASC; -
Grouping and Aggregating: Count the number of employees in each department.
SELECT Department, COUNT(*) AS NumberOfEmployees FROM Employees GROUP BY Department; -
Filtering Groups: Retrieve departments with more than 10 employees.
SELECT Department, COUNT(*) AS NumberOfEmployees FROM Employees GROUP BY Department HAVING COUNT(*) > 10;