Mastering SELECT Statements and Basic Filtering

In continuation of last week’s foundational guide to SQL Server Management Studio (SSMS), this week we delve deeper into querying data in SQL Server. SQL queries are the backbone of database interactions, allowing us to retrieve, filter, sort, and analyze data. Let’s explore the essential query techniques you need to master.
Topics Covered:
- Retrieving Data with SELECT
- Filtering Results with WHERE
- Sorting Data with ORDER BY
- Using Aggregate Functions
1. Retrieving Data with SELECT
The SELECT statement is fundamental in SQL and allows you to retrieve data from one or more tables in a database.
Syntax:
SELECT*FROM Employees;
This retrieves all columns from the specified table. For example:
Output:
Selecting Specific Columns:
To retrieve specific columns, specify them after the SELECT keyword:
Output:
2. Filtering Results with WHERE
The WHERE clause is used to filter rows based on specific conditions.
Filter by Department:
Retrieve employees in the IT department:
Output:
Filter by Salary:
Find employees earning more than 55,000:
Combining Filters:
Use AND or OR to combine conditions:
3. Sorting Data with ORDER BY
The ORDER BY clause allows you to sort results in ascending or descending order.
Sorting by Salary in Descending Order:
4. Aggregate Functions
Aggregate functions summarize data, making them invaluable for analysis.
Counting Rows:
Find the total number of employees:
Output:
Calculating the Average Salary:
Determine the average salary of all employees:
Output:
Summing Salaries:
Calculate the total salary expenditure:
Output:
TotalSalaries |
---|
165000.00 |
Practice Tasks
Filter Employees: Write a query to find all employees in the HR department earning less than 55,000.
Total Salary Expenditure: Calculate the total salary expenditure for the IT department.
Conclusion
This week’s focus was on mastering the SELECT statement, filtering results with WHERE, sorting data using ORDER BY, and applying aggregate functions like COUNT, SUM, and AVG. These skills form the foundation for querying and analyzing data in SQL Server.!