SQL Queries with Examples: Complete Guide from Basic to Advanced (2026)
Nov 06, 2026 4 Min Read 150475 Views
(Last Updated)
SQL is an essential skill for professionals working in data analytics, software development, and database management. From retrieving customer records to analysing business performance, SQL queries help you access and work with information stored in relational databases.
However, learning SQL involves more than memorising commands. You need to understand how to filter records, combine tables, summarize information, and solve practical problems using query logic.
This guide covers commonly used SQL queries with examples, expected outputs, and practical applications. Whether you’re a beginner or preparing for technical interviews, you’ll learn how to progress from basic retrieval to advanced analytical queries.
Table of contents
- TL;DR
- What Are SQL Queries?
- Common SQL Queries With Examples
- SELECT Statement
- JOIN Statements
- GROUP BY Clause
- Subqueries
- Window Functions
- Advanced SQL Interview Queries With Examples
- Find the Second-Highest Salary
- Find Duplicate Email Addresses
- Find the Top Three Salaries in Each Department
- Calculate a Running Total of Monthly Sales
- Find Customers Who Have Never Placed an Order
- SQL vs NoSQL: When Should You Use Each?
- Common SQL Mistakes to Avoid
- How Can You Improve Your SQL Skills?
- Conclusion
- FAQs
- What are the most commonly used SQL queries?
- Which SQL queries are important for interviews?
- What is the difference between WHERE and HAVING?
- Which SQL query is used to find duplicate records?
- What is the difference between JOIN and a subquery?
- How long does it take to learn basic SQL queries?
TL;DR
- Learn SQL queries from basic to advanced with practical examples.
- Understand essential commands such as SELECT, INSERT, UPDATE, DELETE, JOIN, GROUP BY, and ORDER BY.
- Explore advanced concepts, including subqueries, window functions, and aggregate functions.
- Practice real-world SQL queries for filtering data, finding duplicates, ranking records, and analyzing results.
- Understand common SQL mistakes and how to write efficient, reliable queries.
- Strengthen your database skills with hands-on SQL practice for real-world projects and interviews.
What Are SQL Queries?

SQL queries are commands used to communicate with relational databases. They allow you to retrieve, insert, update, delete, and analyse information stored in tables.
For example, a data analyst might use SQL to retrieve customer orders, calculate monthly revenue, identify duplicate records, or compare sales across regions.
Strengthen your SQL skills and learn how to work with databases, retrieve information, and analyze data effectively. HCL GUVI’s Data Science Course helps you build practical skills in SQL, Python, statistics, and data analysis through hands-on projects.
Common SQL Queries With Examples
Consider an employees table containing employee names, department IDs, and salaries.
1. SELECT Statement
<badge color=”success”>Beginner</badge>
The SELECT statement retrieves specific columns or all columns from a table.
SELECT first_name, salary
FROM employees
WHERE salary > 70000;
Example output:
| first_name | salary |
|---|---|
| Rohan | 82000 |
| Vikram | 91000 |
Use SELECT with WHERE to retrieve only the records that meet your conditions.
2. JOIN Statements
<badge color=”info”>Intermediate</badge>
JOINs combine information from related tables using a common column.
SELECT s.first_name, c.course_name
FROM students s
INNER JOIN courses c
ON s.student_id = c.student_id;
An INNER JOIN returns matching records, while a LEFT JOIN retains all records from the left table, including those without a match.
3. GROUP BY Clause
<badge color=”info”>Intermediate</badge>
GROUP BY organizes records into groups so aggregate functions can summarize them.
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
HAVING AVG(salary) > 80000;
This query calculates the average salary for each department and returns only departments with an average above 80,000.
4. Subqueries
<badge color=”warning”>Advanced</badge>
A subquery is a query written inside another SQL query. It is useful when the outer query depends on a result calculated by the inner query.
SELECT first_name, salary
FROM employees
WHERE salary > (
SELECT AVG(salary)
FROM employees
);
This retrieves employees earning more than the overall average salary.
5. Window Functions
<badge color=”warning”>Advanced</badge>
Window functions perform calculations across related rows without combining them into a single summary row.
SELECT
first_name,
department_id,
salary,
RANK() OVER (
PARTITION BY department_id
ORDER BY salary DESC
) AS dept_rank
FROM employees;
This ranks employees by salary within each department. RANK() assigns equal ranks to ties and skips the next rank, while ROW_NUMBER() assigns a unique sequential number to each row.
Pro Tip: Learn
PARTITION BYandORDER BYinside window functions carefully. They are especially useful for ranking, running totals, and comparing records across periods.
Advanced SQL Interview Queries With Examples
Interviewers often use practical scenarios to test whether you can apply SQL concepts rather than simply explain their definitions.
1. Find the Second-Highest Salary
SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (
SELECT MAX(salary)
FROM employees
);
This finds the second-highest distinct salary. If no second distinct salary exists, the result is NULL.
2. Find Duplicate Email Addresses
SELECT email, COUNT(*) AS occurrences
FROM users
GROUP BY email
HAVING COUNT(*) > 1;
This identifies email addresses appearing more than once.
3. Find the Top Three Salaries in Each Department
WITH ranked AS (
SELECT *,
DENSE_RANK() OVER (
PARTITION BY department_id
ORDER BY salary DESC
) AS salary_rank
FROM employees
)
SELECT *
FROM ranked
WHERE salary_rank <= 3;
DENSE_RANK() includes employees with tied salaries and may return more than three employees in a department.
4. Calculate a Running Total of Monthly Sales
SELECT
sale_month,
revenue,
SUM(revenue) OVER (
ORDER BY sale_month
ROWS BETWEEN UNBOUNDED PRECEDING
AND CURRENT ROW
) AS running_total
FROM monthly_sales;
This calculates cumulative revenue while retaining each month’s individual record.
5. Find Customers Who Have Never Placed an Order
SELECT c.customer_id, c.customer_name
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
);
This identifies customers without matching order records.
Best Practice: When solving interview questions, explain the logic before writing the query. Discuss how your approach handles duplicate values, NULLs, and ties.
SQL vs NoSQL: When Should You Use Each?

Both SQL and NoSQL databases store information, but they differ in structure and typical use cases.
| Feature | SQL | NoSQL |
|---|---|---|
| Data structure | Relational tables | Documents, key-value, and other models |
| Schema | Generally predefined | Often flexible |
| Relationships | Supports joins | Depends on database model |
| Examples | MySQL, PostgreSQL | MongoDB, Cassandra |
| Common use cases | Financial and transactional systems | Flexible or distributed data workloads |
Choose a database based on data structure, consistency requirements, query patterns, and scalability needs. Neither option is universally better.
SQL can analyse millions of database records without requiring you to manually open and inspect each row, making it an essential tool for data-driven applications and reporting.
Common SQL Mistakes to Avoid
- Confusing JOIN types: An incorrect JOIN can remove records or introduce unexpected duplicates.
- Ignoring NULL values: Use
IS NULLorIS NOT NULLinstead of comparing NULL with=. - Misusing WHERE and HAVING:
WHEREfilters rows before grouping;HAVINGfilters groups after aggregation. - Forgetting JOIN conditions: Missing conditions can create unintended Cartesian results.
- Using SELECT * unnecessarily: Retrieve only the columns your query needs.
- Ignoring duplicate records: Duplicates can distort counts, totals, and averages.
<badge color=”warning”>Warning</badge> Always validate your query results before using them in reports. Check sample records, row counts, and aggregate values to catch unexpected results.
How Can You Improve Your SQL Skills?
Start with basic retrieval and filtering before moving towards joins, aggregation, subqueries, and window functions.
Practise using sample databases involving employees, customers, orders, and sales. Try solving business questions such as identifying top-performing products, calculating monthly revenue, and finding inactive customers.
If you want to strengthen your foundation before building these projects, HCL GUVI’s Certified Data Science Course can help you develop practical skills in Python, data analysis, machine learning, and real-world project implementation.
Conclusion
Learning SQL is about understanding how to retrieve and interpret data accurately. Basic commands help you access records, while joins, aggregations, subqueries, and window functions allow you to solve increasingly complex problems.
Start with simple queries, practise using realistic datasets, and gradually work towards advanced interview questions. Consistent hands-on practice will help you build confidence in SQL for data analytics, software development, and database-related roles.
FAQs
1. What are the most commonly used SQL queries?
SELECT, WHERE, ORDER BY, JOIN, GROUP BY, HAVING, INSERT, UPDATE, and DELETE are among the most commonly used SQL commands.
2. Which SQL queries are important for interviews?
Practise JOINs, duplicate detection, second-highest salary, GROUP BY, subqueries, CTEs, and window functions.
3. What is the difference between WHERE and HAVING?
WHERE filters individual rows before grouping, whereas HAVING filters grouped results after aggregation.
4. Which SQL query is used to find duplicate records?
Use GROUP BY with HAVING COUNT(*) greater than 1 to identify repeated values in a column.
5. What is the difference between JOIN and a subquery?
JOIN combines related records from multiple tables, while a subquery uses the result of one query inside another. Both can solve similar problems, depending on the requirement.
6. How long does it take to learn basic SQL queries?
The time depends on your learning pace and practice. With consistent study, beginners can understand basic queries in a few weeks and gradually progress to advanced concepts.



Thank you
I was looking for such type of short intro to SQL Queries with few useful examples as I am going to appear for an interview of SQL Server Database. Example given are well understandable and useful with daily life examples.
Very helpful for today's external exam
Thanks
Ease to understand for beginners