Apply Now Apply Now Apply Now
header_logo
Post thumbnail
DATABASE

SQL Queries with Examples: Complete Guide from Basic to Advanced (2026)

By Lukesh S

SQL queries are commands used to retrieve, insert, update, and delete data in a relational database. If you can write a SELECT, a JOIN, and a GROUP BY confidently, you can handle most real-world database tasks, and most SQL interview rounds too.

Table of contents


  1. TL;DR Summary
  2. Some of the Most Common SQL Queries
  3. SELECT Statement
  4. JOIN Statements
  5. GROUP BY Clause
  6. Subqueries
  7. Window Functions
  8. SQL Interview Queries Asked at Amazon, Flipkart, TCS, Infosys
  9. SQL vs NoSQL — When to Use Which?
  10. Common Mistakes to Avoid
  11. Common Mistakes Beginners Make in SQL
  12. Wrapping it Up
  13. FAQs
    • Q1. What is SQL?
    • Q2. Which databases use SQL?
    • Q3. How do I retrieve specific columns from a table?
    • Q4. What is a subquery?
    • Q5. Are subqueries slower than JOINs?
    • Q6. What's the fastest way to get better at SQL interviews?

TL;DR Summary

  • SELECT, WHERE, and ORDER BY handle basic data retrieval
  • JOINs combine data across multiple tables
  • GROUP BY and aggregate functions summarize data
  • Subqueries and window functions solve advanced, interview-favorite problems
  • SQL fits structured data; NoSQL fits flexible, high-volume data
💡 Did You Know?

SQL was originally called SEQUEL (Structured English Query Language), built by IBM in the 1970s. Nearly 60% of developers worldwide still use it today, making it one of the most durable languages in tech.

Some of the Most Common SQL Queries

Some of the Most Common SQL Queries
QueryFunction
SELECT * FROM table_name;Retrieve all columns and rows from the specified table.
SELECT column1, column2 FROM table_name;Retrieve specific columns from the specified table.
SELECT DISTINCT column FROM table_name;Retrieve unique values from a specific column in the table.
WHERE condition;Filter rows based on a specified condition in the WHERE clause.
ORDER BY column ASC/DESC;Sort the result set in ascending (ASC) or descending (DESC) order based on a specified column.
GROUP BY column;Group rows based on the values in a specific column.
HAVING condition;Filter groups based on a specified condition in the HAVING clause (used with GROUP BY).
INSERT INTO table_name (column1, column2) VALUES (value1, value2);Insert new records into a table with specified column values.
UPDATE table_name SET column1 = value1 WHERE condition;Update existing records in a table based on a specified condition.
DELETE FROM table_name WHERE condition;Delete rows from a table based on a specified condition.
CREATE TABLE table_name (column1 datatype, column2 datatype, …);Create a new table with specified columns and data types.
ALTER TABLE table_name ADD column_name datatype;Add a new column to an existing table.
DROP TABLE table_name;Delete an entire table along with its data.
SELECT COUNT(*) FROM table_name;Count the number of rows in a table.
SELECT AVG(column) FROM table_name;Calculate the average value of a numeric column in a table.
SQL Queries

Also Read | How To Learn SQL Using Squid Games?

SELECT Statement

Difficulty: Beginner

SELECT retrieves data from a table. It’s the query you’ll write most often.

SELECT first_name, last_name, salary
FROM employees
WHERE salary > 70000;

Output:

first_namelast_namesalary
RohanMehta82000
VikramSingh91000
Output

Keep these in mind:

  • Avoid SELECT * in production code — it’s slower and breaks silently when columns change
  • Combine with WHERE, ORDER BY, and LIMIT to control exactly what comes back
MDN

JOIN Statements

Difficulty: Intermediate

JOINs combine rows from two or more tables using a shared column. Most real applications store data across multiple tables, so this is non-negotiable.

SELECT s.first_name, c.course_name
FROM students s
JOIN courses c ON s.student_id = c.student_id;

Output:

first_namecourse_name
AnanyaData Science
RohanWeb Development
Output

INNER JOIN returns only matching rows. LEFT JOIN keeps every row from the first table even without a match. Mixing these up is one of the most common beginner errors.

GROUP BY Clause

Difficulty: Intermediate

GROUP BY summarizes rows into groups, usually paired with COUNT, SUM, or AVG.

SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id;

Output:

department_idavg_salary
10178500
10285200
Output

Use HAVING (not WHERE) if you need to filter after grouping — for example, showing only departments where the average salary exceeds ₹80,000.

Subqueries

Difficulty: Advanced

A subquery is a query nested inside another query. It’s useful when a filter depends on a result you don’t know in advance.

SELECT first_name
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);

Output:

first_name
Rohan
Vikram
Output

CTEs (WITH clauses) do the same job with better readability for multi-step logic, and are the modern preference over deeply nested subqueries.

Window Functions

Difficulty: Advanced

Window functions calculate across related rows without collapsing them, using OVER().

SELECT first_name, department_id, salary,
RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS dept_rank
FROM employees;

Output:

first_namedepartment_idsalarydept_rank
Vikram101910001
Rohan101820002
Output

RANK() skips numbers on ties, ROW_NUMBER() never ties, and LAG()/LEAD() pull values from neighboring rows — handy for period-over-period comparisons.

SQL Interview Queries Asked at Amazon, Flipkart, TCS, Infosys

Difficulty: Intermediate to Advanced

These companies tend to test the same handful of query patterns. A few you should be able to write cold:

Find the second-highest salary (a favorite at TCS and Infosys):

sql

SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);

Output:

second_highest
82000
Output

Find duplicate records (common at Amazon and Flipkart data-heavy rounds):

sql

SELECT email, COUNT(*) 
FROM users
GROUP BY email
HAVING COUNT(*) > 1;

Output:

emailcount
[email protected]2
Output

Find employees with no matching department (LEFT JOIN + IS NULL, a classic Flipkart question):

sql

SELECT e.first_name
FROM employees e
LEFT JOIN departments d ON e.department_id = d.department_id
WHERE d.department_id IS NULL;

Output:

first_name
Priya
Output

Interviewers are usually less interested in the exact syntax and more in whether you can explain your logic out loud. Practice narrating your thought process, not just typing the query.

SQL vs NoSQL — When to Use Which?

SQL vs NoSQL — When to Use Which?

Difficulty: Beginner

This question comes up constantly once you move past query basics, especially in system design rounds.

FactorSQLNoSQL
Data structureFixed schema, tablesFlexible, documents/key-value
RelationshipsStrong (joins)Weak or none
ScalingVertical (mostly)Horizontal, built for scale
Best forTransactions, finance, ERPReal-time apps, catalogs, logs
ExamplesMySQL, PostgreSQLMongoDB, Cassandra, Redis
SQL vs NoSQL — When to Use Which?

Simple rule of thumb: if your data has clear relationships and needs strong consistency, go SQL. If it’s high-volume, semi-structured, and needs to scale horizontally, NoSQL fits better. Many real systems use both.

Common Mistakes to Avoid

Common Mistakes to Avoid
  • Confusing INNER JOIN with LEFT JOIN and losing rows silently
  • Ignoring NULLs — use IS NULL or COALESCE instead of = NULL
  • Writing unindexed queries on large tables, which slows everything down
  • Skipping practice on real datasets and only memorizing syntax

Take your SQL skills to the next level with the MySQL Course. Gain hands-on experience in database management, query optimization, and real-world projects designed to build confidence and practical expertise. Master relational databases and strengthen your career prospects with industry-relevant skills.

Related Blog: SQL Interview Questions

Common Mistakes Beginners Make in SQL

Learning SQL becomes easier when you understand the mistakes that beginners often make. Avoiding these errors helps in building confidence and accuracy:

  • Using Wrong Joins: Beginners often confuse inner joins with left joins. This creates incomplete or incorrect results in the output.
    The solution is to practice join queries with small datasets until the difference becomes clear.
  • Ignoring NULL Values: Many learners forget to handle NULL values, which leads to misleading query results. The fix is to use functions like IS NULL or COALESCE to handle such cases.
  • Writing Unoptimized Queries: Long queries without indexing increase response time. Optimizing queries improves database performance. The improvement comes from using indexes and breaking queries into smaller parts.
  • Not Practicing with Real Data: Working only on theory prevents learners from understanding how SQL performs on large datasets. Practical exposure builds better skills. The best way to correct this is to practice with open-source datasets that simulate real projects.

Ready to go from SQL beginner to pro?
HCL GUVI’s SQL Handbook
guides you through practical examples, real-world projects, and hands-on exercises — all online and self-paced.

Wrapping it Up

These top SQL queries will give you an idea of how to work with databases efficiently. There are many SQL queries, but you can get started with these to kickstart your SQL journey. These SQL queries will help you to deal with databases, whether you’re a beginner or an experienced developer. You should get handy with these queries to enhance your SQL skills and become a proficient data professional.

FAQs

Q1. What is SQL?

Ans. SQL (Structured Query Language) is a standard programming language designed for managing and manipulating relational databases. It enables users to perform various operations such as querying data, updating records, inserting new data, and more.

Q2. Which databases use SQL?

Ans. SQL is used by various relational database management systems (RDBMS) such as MySQL, PostgreSQL, SQLite, Microsoft SQL Server, and Oracle Database, among others.

Q3. How do I retrieve specific columns from a table?

Ans. You can use this query to retrieve specific columns from a table: SELECT column1, column2 FROM table;

Q4. What is a subquery?

Ans. A subquery is a query nested within another query. It can be used to retrieve data that will be used by the main query’s condition.
Example: SELECT column FROM table WHERE column IN (SELECT column FROM another_table);

Q5. Are subqueries slower than JOINs?

Not always, but JOINs are often more efficient for large datasets. Test both and check the execution plan when performance matters.

MDN

Q6. What’s the fastest way to get better at SQL interviews?

Practice writing joins and subqueries by hand instead of just reading solutions — recall matters more than recognition.

Success Stories

Did you enjoy this article?

Comments

Vince Wilson
4 months ago
Star Selected Star Selected Star Selected Star Selected Star Selected

Thank you

Shabbir Shah
7 months ago
Star Selected Star Selected Star Selected Star Selected Star Unselected

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.

Yogita kumpawat
11 months ago
Star Selected Star Selected Star Selected Star Selected Star Selected

Very helpful for today's external exam

Raja
11 months ago
Star Selected Star Selected Star Selected Star Selected Star Selected

Thanks

Foluke
9 days ago
Star Selected Star Selected Star Selected Star Selected Star Unselected

Ease to understand for beginners

Schedule 1:1 free counselling

Similar Articles

Loading...
Get in Touch
Chat on Whatsapp
Request Callback
Share logo Copy link
Table of contents Table of contents
Table of contents Articles
Close button

  1. TL;DR Summary
  2. Some of the Most Common SQL Queries
  3. SELECT Statement
  4. JOIN Statements
  5. GROUP BY Clause
  6. Subqueries
  7. Window Functions
  8. SQL Interview Queries Asked at Amazon, Flipkart, TCS, Infosys
  9. SQL vs NoSQL — When to Use Which?
  10. Common Mistakes to Avoid
  11. Common Mistakes Beginners Make in SQL
  12. Wrapping it Up
  13. FAQs
    • Q1. What is SQL?
    • Q2. Which databases use SQL?
    • Q3. How do I retrieve specific columns from a table?
    • Q4. What is a subquery?
    • Q5. Are subqueries slower than JOINs?
    • Q6. What's the fastest way to get better at SQL interviews?