Simple SQL Queries
Simple SQL Queries
Here are some basic SQL queries that can be used to perform common database operations like
retrieving, filtering, and sorting data. These examples work with a simple table of students and
courses.
This query retrieves all rows and columns from a table. It’s the most basic query and is used when
you need to view all the data in the table.
Example:
Query:
Result:
When you want to view only specific columns, you can use the projection feature of SQL to retrieve
only the desired columns from a table.
Example:
Query: Retrieve the `Name` and `Course` of students from the `Students` table.
Result:
Name Course
Alice Computer Science
Bob Engineering
Charlie Mathematics
3. Filtering Rows (`WHERE` clause)
The `WHERE` clause is used to filter rows based on a condition. You can apply this to retrieve only
those rows that meet certain criteria.
Example:
Result:
You can use the `ORDER BY` clause to sort the data in ascending (`ASC`) or descending (`DESC`) order
based on one or more columns.
Example:
Query: Retrieve the student details and sort them by `Name` in ascending order
Result:
If you want to retrieve a specific number of rows from the result set, you can use the `LIMIT` clause.
Example:
Query: Retrieve the first two rows from the `Students` table.
Result:
The `LIKE` operator is used to search for a specific pattern in a column. You can use `%` as a wildcard
to match any sequence of characters.
Example:
Result:
You can use SQL aggregate functions like `COUNT`, `SUM`, and `AVG` to perform calculations on
columns.
Result:
Count
3
Result:
AverageAge
22.00
The `GROUP BY` clause is used with aggregate functions to group the result set by one or more
columns.
Example:
Course NumStudents
Computer Science 1
Engineering 1
Mathematics 1
These examples cover some of the fundamental SQL operations that you will frequently use when
interacting with databases. By understanding these basic queries, you’ll be able to retrieve, filter, and
manipulate data efficiently in a DBMS.