Open In App

SQL Clauses

Last Updated : 31 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Structured Query Language (SQL) is a powerful language used to manage and manipulate relational databases. One of the essential features of SQL is its clauses, which allow users to filter, sort, group, and limit data efficiently. SQL clauses simplify querying and enhance database performance by retrieving only the necessary records based on specific conditions.

This article provides a comprehensive guide to SQL clauses, including their types, uses, and real-world examples with proper explanations. Whether you're a beginner or an experienced developer, this guide will help you understand SQL clauses and their practical applications.

What is Clauses in SQL?

SQL clauses are built-in functions that define specific conditions within an SQL statement to retrieve, update, or manipulate data from a database. These clauses work alongside SELECT, UPDATE, DELETE, and INSERT queries to refine results and ensure efficient data handling.

Key Functions of SQL Clauses

  • Filter and retrieve specific records from a database.
  • Group data based on certain attributes.
  • Sort query results in ascending or descending order.
  • Limit the number of records displayed in a query result.

SQL clauses are integral to writing optimized queries that return precise results without scanning unnecessary data

Types of SQL Clauses

ClauseDescription
WHEREThe WHERE clause is used to filter records based on specific conditions. It is typically used in SELECT, UPDATE, and DELETE queries to restrict the data that is affected by these statements. For example, retrieving all employees with a salary above 50,000.
ORDER BYThe ORDER BY clause is used to sort the query results in either ascending or descending order. It is commonly used with numeric, date, and text fields to organize data meaningfully, such as sorting employees by their joining date.
GROUP BYThe GROUP BY clause groups records with the same values in specified columns and is used with aggregate functions like COUNT(), SUM(), AVG(), etc. For example, calculating total sales per region.
HAVINGThe HAVING clause is similar to WHERE but is used to filter grouped records. It is used with GROUP BY to apply conditions on aggregated results, such as filtering groups where the total revenue exceeds a certain amount.
LIMITThe LIMIT clause restricts the number of rows returned in a query result. This is especially useful in large databases where retrieving all records could be inefficient. For example, fetching the top 5 highest-paid employees.
TOPThe TOP clause, similar to LIMIT, is used in SQL Server to limit the number of rows returned. It helps in retrieving a specific subset of records efficiently.
LIKEThe LIKE clause filters results using pattern matching with wildcards (% for multiple characters and _ for a single character). It is useful for searching partial matches in text fields, such as finding all customers whose names start with 'J'.
FROMThe FROM clause specifies the database table from which records will be retrieved. It is a fundamental part of SQL queries as it defines the source of data for SELECT, DELETE, and UPDATE statements.
ANDThe AND clause is used to combine multiple conditions in a query, ensuring that all conditions must be met. It is useful in complex filtering scenarios, such as retrieving employees who work in a specific department and have a salary above 60,000.
ORThe OR clause is used to combine multiple conditions where at least one must be true. It is useful when searching for multiple criteria, such as retrieving customers from either New York or Los Angeles.

Uses of SQL Clauses

SQL clauses have multiple applications in data filtering, sorting, and aggregation. Below are some common use cases:

  • WHERE Clause: Used to filter records that meet specific conditions, such as retrieving employees with a salary greater than 50,000.
  • ORDER BY Clause: Helps in sorting the retrieved data in either ascending or descending order, such as sorting students based on their marks.
  • GROUP BY Clause: Used to group records with identical values, often combined with aggregate functions like SUM() or COUNT(), for example, calculating total sales per region.
  • HAVING Clause: Applies conditions on grouped data, such as filtering groups where the total sales exceed 100,000.
  • LIMIT Clause: Restricts the number of rows displayed in the query result, useful in paginated applications.
  • TOP Clause: Similar to LIMIT, it is used in SQL Server to limit the number of records retrieved, for example, selecting the top 3 highest-paid employees.
  • LIKE Clause: Used for pattern matching, such as retrieving all employees whose names start with 'A'.
  • FROM Clause: Specifies the table from which records are fetched, fundamental for all SQL queries.
  • AND Clause: Combines multiple conditions where all conditions must be true, such as retrieving employees in the IT department with salaries above 80,000.
  • OR Clause: Combines multiple conditions where at least one condition must be true, such as retrieving customers from either New York or Los Angeles

Examples of SQL Clauses

Consider the below Students table, which is used as a reference for all the examples that are mentioned below. The Students table contains information about students, including their ID, name, fees, subject, age, and class. This table helps in performing various SQL operations such as filtering, grouping, and sorting records.

students-table
Students Table

Example 1: Using the WHERE Clause

The WHERE clause is used to filter records that meet a specific condition. In this example, we retrieve students whose fees are less than 3500.

Query:

SELECT * FROM Students
WHERE stu_fees < 3500;

Output:

Using-Where-Clause
Using WHERE Clause

Explanation:

  • The query filters students whose stu_fees is less than 3500.
  • Students with fees 4500 and 4000 are excluded from the result.
  • The remaining students whose fees meet the condition are displayed

Example 2: Using the GROUP BY Clause

The GROUP BY clause is used to group records with the same values in a column and perform aggregate functions such as SUM(), COUNT(), etc. This example calculates the total student fees per class.

Query:

SELECT stu_class, SUM(stu_fees) AS total_fees
FROM Students
GROUP BY stu_class;

Output

stu_classtotal_fees
109000
114500
97500

Explanation:

  • The query groups students based on their stu_class.
  • It calculates the total fees per class using the SUM(stu_fees) function.
  • For example, in class 10, the total fees sum up to 9000, and for class 9, it sums up to 7500.

Example 3: Using the ORDER BY Clause

The ORDER BY clause is used to sort query results in ascending or descending order. This example sorts students by their fees in ascending order

Query:

SELECT * FROM Students
ORDER BY stu_fees ASC;

Output:

stu_idstu_namestu_feesstu_subjectstu_agestu_class
2Mayra Pandit2000Social Science1510
4Manvi Tyagi2000Social Science169
6Tisha Shah2500Science159
1Divyesha Patil3000Maths1610
5Joy Yadav3000Maths169
7Surbhi Soni4000Chemistry1710
3Kunal Purohit4500Chemistry1711

Explanation:

  • The ORDER BY clause sorts the students based on their stu_fees in ascending order (lowest to highest).
  • The student with the lowest fees (2000) appears first, while the student with the highest fees (4500) appears last.
  • Sorting helps in analyzing data in a structured way, such as identifying the most or least expensive students

Conclusion

SQL clauses are essential for writing efficient and optimized queries. They help filter, sort, group, and limit data retrieval for better performance and accuracy. Mastering these clauses allows developers to handle databases more effectively, making data analysis faster and more structured. Understanding where to use each clause and how they interact is crucial for writing professional SQL queries. By practicing the examples and concepts shared in this guide, you can enhance your SQL skills and work confidently with relational databases


Next Article
Article Tags :

Similar Reads