SQL Clauses and Operators Explained with Examples
In SQL, clauses define the structure of a query, and operators help filter and compare data. This guide covers the most common clauses and logical operators every SQL beginner must know.
What are SQL Clauses?
SQL clauses are components of SQL statements that define actions, filtering, grouping, and sorting.
1. SELECT Clause
SELECT name, age FROM students;
Fetches name and age columns from the students
table.
2. FROM Clause
Specifies the table name:
SELECT * FROM employees;
3. WHERE Clause
SELECT * FROM employees WHERE department = 'Sales';
Filters rows based on a condition.
4. ORDER BY Clause
SELECT name, salary FROM employees ORDER BY salary DESC;
Sorts results in descending order of salary.
5. GROUP BY Clause
SELECT department, COUNT(*) FROM employees GROUP BY department;
Groups results and performs aggregate functions.
6. HAVING Clause
SELECT department, COUNT(*) FROM employees GROUP BY department HAVING COUNT(*) > 5;
Filters groups after GROUP BY
.
7. LIMIT Clause
SELECT * FROM products LIMIT 10;
Limits results to the top 10 rows.
SQL Operators (AND, OR, IN, NOT, LIKE)
1. AND Operator
SELECT * FROM users WHERE age > 18 AND city = 'New York';
2. OR Operator
SELECT * FROM users WHERE city = 'New York' OR city = 'Chicago';
3. NOT Operator
SELECT * FROM products WHERE NOT price < 100;
4. IN Operator
SELECT * FROM orders WHERE status IN ('Pending', 'Shipped');
5. LIKE Operator
SELECT * FROM customers WHERE name LIKE 'A%';
Finds names starting with 'A'.
Best Practices
- Always use
WHERE
to avoid full-table scans. - Combine
AND
/OR
wisely to avoid logic errors. - Use
LIMIT
when previewing large datasets.
Also Read:
FAQs: SQL Clauses and Operators
- Q: What is the difference between WHERE and HAVING?
A: WHERE filters rows before grouping; HAVING filters groups after grouping. - Q: What does IN operator do?
A: It checks if a value exists in a set of values. - Q: Can I use multiple clauses in a single SQL query?
A: Yes! Example:SELECT ... FROM ... WHERE ... ORDER BY ...
Stay tuned for advanced SQL tutorials in our next posts.
Comments
Post a Comment