SQL Queries
SQL Queries are used to retrieve, filter, sort and manipulate data stored in SQL Server databases.
In this module, we will learn commonly used SQL queries and clauses that help us work efficiently with database data.
What is a SQL Query?
A SQL query is a statement written using Structured Query Language (SQL) to communicate with a database.
Using SQL queries, we can retrieve data, filter records, sort results, group data and perform calculations.
Basic SQL Query
SELECT *
FROM Students;
This query retrieves all columns and all records from the Students table.
Common SQL Query Clauses
| Clause | Purpose |
|---|---|
| SELECT | Retrieves data from a table. |
| FROM | Specifies the table from which data is retrieved. |
| WHERE | Filters records based on a condition. |
| ORDER BY | Sorts the query result. |
| GROUP BY | Groups rows having similar values. |
| HAVING | Filters grouped results. |
Example – WHERE Clause
SELECT *
FROM Students
WHERE Age > 21;
This query returns only those students whose age is greater than 21.
Example – ORDER BY
SELECT *
FROM Students
ORDER BY StudentName ASC;
This query sorts the student records by StudentName in ascending order.
How a SQL Query Works
- The query is written using SQL syntax.
- SQL Server parses and validates the query.
- SQL Server determines how to execute the query.
- The requested result is returned to the user.
Important Points
- SQL queries are used to communicate with databases.
- SELECT is commonly used to retrieve data.
- WHERE is used to filter records.
- ORDER BY is used to sort results.
- GROUP BY is used to group records.
- HAVING is used to filter grouped results.
Summary
In this section, we introduced SQL Queries and learned the purpose of commonly used clauses such as SELECT, FROM, WHERE, ORDER BY, GROUP BY and HAVING.