SQL Server Tutorialprovides basic and advanced concepts of C# for beginners and professionals.

SQL SELECT Query

Back to: SQL Server Tutorial

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 with GROUP BY).

Examples:

  1. Basic Query: Retrieve all columns from a table named Employees.

    SELECT * FROM Employees;
  2. Select Specific Columns: Retrieve only FirstName and LastName from the Employees table.

    SELECT FirstName, LastName FROM Employees;
  3. With a Condition: Retrieve employees with a salary greater than 50,000.

    SELECT FirstName, LastName, Salary FROM Employees WHERE Salary > 50000;
  4. Sorting Results: Retrieve all employees, sorted by LastName in ascending order.

    SELECT FirstName, LastName FROM Employees ORDER BY LastName ASC;
  5. Grouping and Aggregating: Count the number of employees in each department.

    SELECT Department, COUNT(*) AS NumberOfEmployees FROM Employees GROUP BY Department;
  6. Filtering Groups: Retrieve departments with more than 10 employees.

    SELECT Department, COUNT(*) AS NumberOfEmployees FROM Employees GROUP BY Department HAVING COUNT(*) > 10;
Scroll to Top