{"id":39035,"date":"2024-01-29T10:30:00","date_gmt":"2024-01-29T05:00:00","guid":{"rendered":"https:\/\/www.guvi.in\/blog\/?p=39035"},"modified":"2026-10-27T03:27:12","modified_gmt":"2026-10-26T21:57:12","slug":"sql-queries-with-examples","status":"publish","type":"post","link":"https:\/\/www.guvi.in\/blog\/sql-queries-with-examples\/","title":{"rendered":"SQL Queries with Examples: Complete Guide from Basic to Advanced (2026)"},"content":{"rendered":"\n<p>SQL is one of the most valuable skills for anyone working with databases, data analytics, or software development. However, knowing SQL syntax is only the beginning. The real challenge is writing queries that retrieve accurate results, combine information from multiple tables, and solve practical business problems.<\/p>\n\n\n\n<p>A simple SELECT statement can retrieve employee records, whereas JOINs connect related datasets. GROUP BY helps summarise sales figures, and window functions support advanced calculations without removing individual rows.<\/p>\n\n\n\n<p>This guide covers the most commonly used SQL queries with examples, expected outputs, difficulty levels, and practical applications. You will also learn important SQL interview queries, common mistakes, and the differences between SQL and NoSQL.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Quick Answer<\/h2>\n\n\n\n<p>SQL queries help you retrieve, filter, combine, summarise, and analyse structured data for reporting, applications, and technical interviews. <\/p>\n\n\n\n<ul>\n<li><strong>Basic Retrieval:<\/strong> <code>SELECT<\/code>, <code>WHERE<\/code>, and <code>ORDER BY<\/code><\/li>\n\n\n\n<li><strong>Combine Tables:<\/strong> <code>JOIN<\/code> statements<\/li>\n\n\n\n<li><strong>Summarise Data:<\/strong> <code>GROUP BY<\/code>, <code>COUNT()<\/code>, <code>SUM()<\/code>, and <code>AVG()<\/code><\/li>\n\n\n\n<li><strong>Filter Groups:<\/strong> <code>HAVING<\/code><\/li>\n\n\n\n<li><strong>Advanced Logic:<\/strong> Subqueries and CTEs<\/li>\n\n\n\n<li><strong>Analytical Queries:<\/strong> Window functions such as <code>RANK()<\/code>, <code>ROW_NUMBER()<\/code>, and <code>LAG()<\/code><\/li>\n\n\n\n<li><strong>Interview Focus:<\/strong> JOINs, duplicates, second-highest values, running totals, and growth calculations<\/li>\n<\/ul>\n\n\n\n<div style=\"background-color: #099f4e; border: 3px solid #110053; border-radius: 12px; padding: 18px 22px; color: #ffffff; font-size: 18px; font-family: Montserrat, Helvetica, sans-serif; line-height: 1.6; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); max-width: 750px;\"><strong style=\"font-size: 22px; color: #ffffff;\">\ud83d\udca1 Did You Know?<\/strong><br \/><br \/>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.<\/div>\n\n\n\n<h2 class=\"wp-block-heading\">What Are SQL Queries?<\/h2>\n\n\n\n<p>SQL queries are commands used to retrieve, filter, combine, update, and analyse data stored in relational databases. Common SQL queries include <code>SELECT<\/code>, <code>WHERE<\/code>, <code>JOIN<\/code>, <code>GROUP BY<\/code>, subqueries, CTEs, and window functions, which help users solve everything from basic data retrieval tasks to advanced reporting and business analysis.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Some of the Most Common SQL Queries<\/strong><\/h2>\n\n\n\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" width=\"1200\" height=\"675\" src=\"https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/07\/ChatGPT-Image-Jul-6-2026-09_32_44-PM-1200x675.webp\" alt=\"Some of the Most Common SQL Queries\" class=\"wp-image-121394\" srcset=\"https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/07\/ChatGPT-Image-Jul-6-2026-09_32_44-PM-1200x675.webp 1200w, https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/07\/ChatGPT-Image-Jul-6-2026-09_32_44-PM-300x169.webp 300w, https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/07\/ChatGPT-Image-Jul-6-2026-09_32_44-PM-768x432.webp 768w, https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/07\/ChatGPT-Image-Jul-6-2026-09_32_44-PM-1536x864.webp 1536w, https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/07\/ChatGPT-Image-Jul-6-2026-09_32_44-PM-150x84.webp 150w, https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/07\/ChatGPT-Image-Jul-6-2026-09_32_44-PM.webp 1672w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" title=\"\"><\/figure>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Query<\/th><th>Function<\/th><\/tr><\/thead><tbody><tr><td>SELECT * FROM table_name;<\/td><td>Retrieve all columns and rows from the specified table.<\/td><\/tr><tr><td>SELECT column1, column2 FROM table_name;<\/td><td>Retrieve specific columns from the specified table.<\/td><\/tr><tr><td>SELECT DISTINCT column FROM table_name;<\/td><td>Retrieve unique values from a specific column in the table.<\/td><\/tr><tr><td>WHERE condition;<\/td><td>Filter rows based on a specified condition in the WHERE clause.<\/td><\/tr><tr><td>ORDER BY column ASC\/DESC;<\/td><td>Sort the result set in ascending (ASC) or descending (DESC) order based on a specified column.<\/td><\/tr><tr><td>GROUP BY column;<\/td><td>Group rows based on the values in a specific column.<\/td><\/tr><tr><td>HAVING condition;<\/td><td>Filter groups based on a specified condition in the HAVING clause (used with GROUP BY).<\/td><\/tr><tr><td>INSERT INTO table_name (column1, column2) VALUES (value1, value2);<\/td><td>Insert new records into a table with specified column values.<\/td><\/tr><tr><td>UPDATE table_name SET column1 = value1 WHERE condition;<\/td><td>Update existing records in a table based on a specified condition.<\/td><\/tr><tr><td>DELETE FROM table_name WHERE condition;<\/td><td>Delete rows from a table based on a specified condition.<\/td><\/tr><tr><td>CREATE TABLE table_name (column1 datatype, column2 datatype, &#8230;);<\/td><td>Create a new table with specified columns and data types.<\/td><\/tr><tr><td>ALTER TABLE table_name ADD column_name datatype;<\/td><td>Add a new column to an existing table.<\/td><\/tr><tr><td>DROP TABLE table_name;<\/td><td>Delete an entire table along with its data.<\/td><\/tr><tr><td>SELECT COUNT(*) FROM table_name;<\/td><td>Count the number of rows in a table.<\/td><\/tr><tr><td>SELECT AVG(column) FROM table_name;<\/td><td>Calculate the average value of a numeric column in a table.<\/td><\/tr><\/tbody><\/table><figcaption class=\"wp-element-caption\">SQL Queries<\/figcaption><\/figure>\n\n\n\n<p>Need to change a column name after the table is created? Here is how to <a href=\"https:\/\/www.guvi.in\/blog\/how-to-rename-a-column-in-sql\/\" target=\"_blank\" rel=\"noreferrer noopener\">rename a column in SQL<\/a>.<\/p>\n\n\n\n<p><em>SQL is a core skill for data analysts, data scientists, and business intelligence professionals. However, building a career in data requires applying SQL alongside Python, statistics, visualisation, and practical problem-solving. Take the next step with HCL GUVI\u2019s <a href=\"https:\/\/www.guvi.in\/courses\/databases\/masteringmysql\/?utm_source=blog&amp;utm_medium=hyperlink&amp;utm_campaign=sql-queries-with-examples-complete-guide-from-basic-to-advanced-2026\">Data Science Course<\/a>. Develop job-ready skills through live online classes, expert mentorship, hands-on projects, and placement assistance.<\/em><\/p>\n\n\n<div class=\"wp-block-guvi-cta-button\" style=\"justify-content:center;\"><a href=\"https:\/\/www.guvi.in\/courses\/databases\/masteringmysql\/?utm_source=blog&#038;utm_medium=hyperlink&#038;utm_campaign=sql-queries-with-examples-complete-guide-from-basic-to-advanced-2026\" class=\"guvi-btn-enquire\" target=\"_blank\" rel=\"noopener noreferrer\">Enroll in HCL GUVI\u2019s Data Science Course.<\/a><\/div>\n\n\n<h2 class=\"wp-block-heading\">1. <strong>SELECT Statement<\/strong><\/h2>\n\n\n\n<p><strong>Difficulty: Beginner<\/strong><\/p>\n\n\n\n<p>SELECT retrieves data from a table. It&#8217;s the query you&#8217;ll write most often.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT first_name, last_name, salary\nFROM employees\nWHERE salary &gt; 70000;<\/code><\/pre>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>first_name<\/th><th>last_name<\/th><th>salary<\/th><\/tr><\/thead><tbody><tr><td>Rohan<\/td><td>Mehta<\/td><td>82000<\/td><\/tr><tr><td>Vikram<\/td><td>Singh<\/td><td>91000<\/td><\/tr><\/tbody><\/table><figcaption class=\"wp-element-caption\"><strong>Output<\/strong><\/figcaption><\/figure>\n\n\n\n<p>Keep these in mind:<\/p>\n\n\n\n<ul>\n<li>Avoid <code>SELECT *<\/code> in production code \u2014 it&#8217;s slower and breaks silently when columns change<\/li>\n\n\n\n<li>Combine with WHERE, ORDER BY, and LIMIT to control exactly what comes back<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">2. <strong>JOIN Statements<\/strong><\/h2>\n\n\n\n<p><strong>Difficulty: Intermediate<\/strong><\/p>\n\n\n\n<p>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.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT s.first_name, c.course_name\nFROM students s\nJOIN courses c ON s.student_id = c.student_id;<\/code><\/pre>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>first_name<\/th><th>course_name<\/th><\/tr><\/thead><tbody><tr><td>Ananya<\/td><td>Data Science<\/td><\/tr><tr><td>Rohan<\/td><td>Web Development<\/td><\/tr><\/tbody><\/table><figcaption class=\"wp-element-caption\"><strong>Output<\/strong><\/figcaption><\/figure>\n\n\n\n<p>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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">3. <strong>GROUP BY Clause<\/strong><\/h2>\n\n\n\n<p><strong>Difficulty: Intermediate<\/strong><\/p>\n\n\n\n<p><a href=\"https:\/\/learn.microsoft.com\/en-us\/sql\/t-sql\/queries\/select-group-by-transact-sql\" target=\"_blank\" data-type=\"link\" data-id=\"https:\/\/learn.microsoft.com\/en-us\/sql\/t-sql\/queries\/select-group-by-transact-sql\" rel=\"noreferrer noopener nofollow\">GROUP BY<\/a> summarizes rows into groups, usually paired with COUNT, SUM, or AVG.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT department_id, AVG(salary) AS avg_salary\nFROM employees\nGROUP BY department_id;<\/code><\/pre>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>department_id<\/th><th>avg_salary<\/th><\/tr><\/thead><tbody><tr><td>101<\/td><td>78500<\/td><\/tr><tr><td>102<\/td><td>85200<\/td><\/tr><\/tbody><\/table><figcaption class=\"wp-element-caption\"><strong>Output<\/strong><\/figcaption><\/figure>\n\n\n\n<p>Use HAVING (not WHERE) if you need to filter after grouping \u2014 for example, showing only departments where the average salary exceeds \u20b980,000.<\/p>\n\n\n\n<p><strong>Also Read:<\/strong> <a href=\"https:\/\/www.guvi.in\/blog\/guide-on-sql-for-data-science\/\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>SQL for Data Science<\/strong><\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">4. <strong>Subqueries<\/strong><\/h2>\n\n\n\n<p><strong>Difficulty: Advanced<\/strong><\/p>\n\n\n\n<p>A subquery is a query nested inside another query. It&#8217;s useful when a filter depends on a result you don&#8217;t know in advance.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT first_name\nFROM employees\nWHERE salary &gt; (SELECT AVG(salary) FROM employees);<\/code><\/pre>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>first_name<\/th><\/tr><\/thead><tbody><tr><td>Rohan<\/td><\/tr><tr><td>Vikram<\/td><\/tr><\/tbody><\/table><figcaption class=\"wp-element-caption\"><strong>Output<\/strong><\/figcaption><\/figure>\n\n\n\n<p>CTEs (<code>WITH<\/code> clauses) do the same job with better readability for multi-step logic, and are the modern preference over deeply nested subqueries.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">5. <strong>Window Functions<\/strong><\/h2>\n\n\n\n<p><strong>Difficulty: Advanced<\/strong><\/p>\n\n\n\n<p>Window functions calculate across related rows without collapsing them, using <code>OVER()<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT first_name, department_id, salary,\nRANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS dept_rank\nFROM employees;<\/code><\/pre>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>first_name<\/th><th>department_id<\/th><th>salary<\/th><th>dept_rank<\/th><\/tr><\/thead><tbody><tr><td>Vikram<\/td><td>101<\/td><td>91000<\/td><td>1<\/td><\/tr><tr><td>Rohan<\/td><td>101<\/td><td>82000<\/td><td>2<\/td><\/tr><\/tbody><\/table><figcaption class=\"wp-element-caption\"><strong>Output<\/strong><\/figcaption><\/figure>\n\n\n\n<p>RANK() skips numbers on ties, ROW_NUMBER() never ties, and LAG()\/LEAD() pull values from neighboring rows \u2014 handy for period-over-period comparisons.<\/p>\n\n\n\n<p><strong><em>Know More About <a href=\"https:\/\/www.guvi.in\/blog\/sql-window-functions\/\" target=\"_blank\" data-type=\"link\" data-id=\"https:\/\/www.guvi.in\/blog\/sql-window-functions\/\" rel=\"noreferrer noopener\">SQL Window Functions<\/a><\/em><\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>SQL Interview Queries Asked at Amazon, Flipkart, TCS, Infosys<\/strong><\/h2>\n\n\n\n<p><strong>Difficulty: Intermediate to Advanced<\/strong><\/p>\n\n\n\n<p>These companies tend to test the same handful of query patterns. A few you should be able to write cold:<\/p>\n\n\n\n<ol>\n<li><strong>Find the second-highest salary (a favorite at TCS and Infosys):<\/strong><\/li>\n<\/ol>\n\n\n\n<p>sql<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT MAX(salary) AS second_highest\nFROM employees\nWHERE salary &lt; (SELECT MAX(salary) FROM employees);<\/code><\/pre>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>second_highest<\/th><\/tr><\/thead><tbody><tr><td>82000<\/td><\/tr><\/tbody><\/table><figcaption class=\"wp-element-caption\"><strong>Output<\/strong><\/figcaption><\/figure>\n\n\n\n<p>2. <strong>Find duplicate records (common at Amazon and Flipkart data-heavy rounds):<\/strong><\/p>\n\n\n\n<p>sql<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT email, COUNT(*) \nFROM users\nGROUP BY email\nHAVING COUNT(*) &gt; 1;<\/code><\/pre>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>email<\/th><th>count<\/th><\/tr><\/thead><tbody><tr><td><a href=\"mailto:test@mail.com\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">test@mail.com<\/a><\/td><td>2<\/td><\/tr><\/tbody><\/table><figcaption class=\"wp-element-caption\"><strong>Output<\/strong><\/figcaption><\/figure>\n\n\n\n<p>3. <strong>Find employees with no matching department (LEFT JOIN + IS NULL, a classic Flipkart question):<\/strong><\/p>\n\n\n\n<p>sql<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT e.first_name\nFROM employees e\nLEFT JOIN departments d ON e.department_id = d.department_id\nWHERE d.department_id IS NULL;<\/code><\/pre>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>first_name<\/th><\/tr><\/thead><tbody><tr><td>Priya<\/td><\/tr><\/tbody><\/table><figcaption class=\"wp-element-caption\"><strong>Output<\/strong><\/figcaption><\/figure>\n\n\n\n<p>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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Advanced SQL Interview Queries With Examples<\/h2>\n\n\n\n<p>Advanced SQL interviews test your ability to solve business problems using multiple SQL concepts. Employers may ask you to calculate rankings, identify missing records, analyse customer behaviour, or compare performance across reporting periods.<\/p>\n\n\n\n<p>Here are five advanced SQL interview queries worth practising:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">1. Find the Top Three Highest-Paid Employees in Each Department<\/h3>\n\n\n\n<p>Difficulty: Advanced<\/p>\n\n\n\n<p>This query uses DENSE_RANK() to rank employees by salary within each department.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>WITH ranked_employees AS (\n    SELECT\n        first_name,\n        department_id,\n        salary,\n        DENSE_RANK() OVER (\n            PARTITION BY department_id\n            ORDER BY salary DESC\n        ) AS salary_rank\n    FROM employees\n)\nSELECT *\nFROM ranked_employees\nWHERE salary_rank &lt;= 3;<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><th>first_name<\/th><th>department_id<\/th><th>salary<\/th><th>salary_rank<\/th><\/tr><tr><td>Vikram<\/td><td>101<\/td><td>91000<\/td><td>1<\/td><\/tr><tr><td>Rohan<\/td><td>101<\/td><td>82000<\/td><td>2<\/td><\/tr><tr><td>Ananya<\/td><td>101<\/td><td>78000<\/td><td>3<\/td><\/tr><tr><td>Priya<\/td><td>102<\/td><td>95000<\/td><td>1<\/td><\/tr><tr><td>Neha<\/td><td>102<\/td><td>85000<\/td><td>2<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>DENSE_RANK() assigns the same rank to employees with equal salaries. It does not skip ranking numbers after ties. Consequently, the query may return more than three employees per department.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2. Calculate a Running Total of Monthly Sales<\/h3>\n\n\n\n<p>Difficulty: Advanced<\/p>\n\n\n\n<p>Running totals help analysts track cumulative revenue and business growth.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT\n    sale_month,\n    revenue,\n    SUM(revenue) OVER (\n        ORDER BY sale_month\n        ROWS BETWEEN UNBOUNDED PRECEDING\n        AND CURRENT ROW\n    ) AS running_total\nFROM monthly_sales;<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><th>sale_month<\/th><th>revenue<\/th><th>running_total<\/th><\/tr><tr><td>2026-01<\/td><td>50000<\/td><td>50000<\/td><\/tr><tr><td>2026-02<\/td><td>65000<\/td><td>115000<\/td><\/tr><tr><td>2026-03<\/td><td>70000<\/td><td>185000<\/td><\/tr><tr><td>2026-04<\/td><td>80000<\/td><td>265000<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>The SUM() window function calculates cumulative revenue without combining individual monthly records.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">3. Find Customers Who Have Never Placed an Order<\/h3>\n\n\n\n<p>Difficulty: Intermediate to Advanced<\/p>\n\n\n\n<p>This query identifies customers without matching transactions using NOT EXISTS.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT\n    c.customer_id,\n    c.customer_name\nFROM customers c\nWHERE NOT EXISTS (\n    SELECT 1\n    FROM orders o\n    WHERE o.customer_id = c.customer_id\n);<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><th>customer_id<\/th><th>customer_name<\/th><\/tr><tr><td>103<\/td><td>Ananya<\/td><\/tr><tr><td>107<\/td><td>Priya<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>NOT EXISTS checks whether a matching order exists for each customer. This approach is useful for identifying inactive customers and investigating conversion problems.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">4. Calculate Month-over-Month Revenue Growth<\/h3>\n\n\n\n<p>Difficulty: Advanced<\/p>\n\n\n\n<p>Month-over-month analysis measures how revenue changes between consecutive reporting periods.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>WITH revenue_comparison AS (\n    SELECT\n        sale_month,\n        revenue,\n        LAG(revenue) OVER (\n            ORDER BY sale_month\n        ) AS previous_revenue\n    FROM monthly_sales\n)\nSELECT\n    sale_month,\n    revenue,\n    ROUND(\n        (revenue - previous_revenue) * 100.0\n        \/ NULLIF(previous_revenue, 0),\n        2\n    ) AS growth_percentage\nFROM revenue_comparison;<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><th>sale_month<\/th><th>revenue<\/th><th>growth_percentage<\/th><\/tr><tr><td>2026-01<\/td><td>50000<\/td><td>NULL<\/td><\/tr><tr><td>2026-02<\/td><td>65000<\/td><td>30.00<\/td><\/tr><tr><td>2026-03<\/td><td>70000<\/td><td>7.69<\/td><\/tr><tr><td>2026-04<\/td><td>80000<\/td><td>14.29<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>LAG() retrieves revenue from the preceding row. NULLIF() prevents division-by-zero errors when previous revenue is zero.<\/p>\n\n\n\n<p>The first month returns NULL because no earlier period exists.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">5. Find Products Generating More Revenue Than Their Category Average<\/h3>\n\n\n\n<p>Difficulty: Advanced<\/p>\n\n\n\n<p>This query compares individual product revenue against the average revenue within its category.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>WITH product_comparison AS (\n    SELECT\n        product_name,\n        category,\n        revenue,\n        AVG(revenue) OVER (\n            PARTITION BY category\n        ) AS category_avg\n    FROM products\n)\nSELECT\n    product_name,\n    category,\n    revenue\nFROM product_comparison\nWHERE revenue &gt; category_avg;<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><th>product_name<\/th><th>category<\/th><th>revenue<\/th><\/tr><tr><td>Laptop<\/td><td>Electronics<\/td><td>150000<\/td><\/tr><tr><td>Smartphone<\/td><td>Electronics<\/td><td>120000<\/td><\/tr><tr><td>Office Chair<\/td><td>Furniture<\/td><td>45000<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>The window function calculates category-level averages while retaining individual product records. The outer query then identifies products performing above their category average.<\/p>\n\n\n\n<p>These examples use illustrative datasets. Actual outputs depend on the underlying records and database system.<\/p>\n\n\n\n<p><strong>Related Blog:<\/strong> <a href=\"https:\/\/www.guvi.in\/blog\/sql-interview-questions\/\" data-type=\"link\" data-id=\"https:\/\/www.placementpreparation.io\/blog\/sql-interview-questions-for-freshers\/?utm_source=guviblog&amp;utm_medium=hyperlink&amp;utm_campaign=sql-queries-with-examples\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>SQL Interview Questions<\/strong><\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>SQL vs NoSQL- When to Use Which?<\/strong><\/h2>\n\n\n\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" width=\"1200\" height=\"675\" src=\"https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/07\/ChatGPT-Image-Jul-6-2026-09_35_15-PM-1200x675.webp\" alt=\"SQL vs NoSQL \u2014 When to Use Which?\" class=\"wp-image-121395\" srcset=\"https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/07\/ChatGPT-Image-Jul-6-2026-09_35_15-PM-1200x675.webp 1200w, https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/07\/ChatGPT-Image-Jul-6-2026-09_35_15-PM-300x169.webp 300w, https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/07\/ChatGPT-Image-Jul-6-2026-09_35_15-PM-768x432.webp 768w, https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/07\/ChatGPT-Image-Jul-6-2026-09_35_15-PM-1536x864.webp 1536w, https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/07\/ChatGPT-Image-Jul-6-2026-09_35_15-PM-150x84.webp 150w, https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/07\/ChatGPT-Image-Jul-6-2026-09_35_15-PM.webp 1672w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" title=\"\"><\/figure>\n\n\n\n<p><strong>Difficulty: Beginner<\/strong><\/p>\n\n\n\n<p>This question comes up constantly once you move past query basics, especially in system design rounds.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Factor<\/th><th>SQL<\/th><th>NoSQL<\/th><\/tr><\/thead><tbody><tr><td>Data structure<\/td><td>Fixed schema, tables<\/td><td>Flexible, documents\/key-value<\/td><\/tr><tr><td>Relationships<\/td><td>Strong (joins)<\/td><td>Weak or none<\/td><\/tr><tr><td>Scaling<\/td><td>Vertical (mostly)<\/td><td>Horizontal, built for scale<\/td><\/tr><tr><td>Best for<\/td><td>Transactions, finance, ERP<\/td><td>Real-time apps, catalogs, logs<\/td><\/tr><tr><td>Examples<\/td><td>MySQL, PostgreSQL<\/td><td>MongoDB, Cassandra, Redis<\/td><\/tr><\/tbody><\/table><figcaption class=\"wp-element-caption\"><strong>SQL vs NoSQL \u2014 When to Use Which?<\/strong><\/figcaption><\/figure>\n\n\n\n<p>Simple rule of thumb: if your data has clear relationships and needs strong consistency, go SQL. If it&#8217;s high-volume, semi-structured, and needs to scale horizontally, <a href=\"https:\/\/www.guvi.in\/blog\/what-is-nosql\/\" target=\"_blank\" rel=\"noreferrer noopener\">NoSQL<\/a> fits better. Many real systems use both.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Common Mistakes to Avoid<\/strong><\/h2>\n\n\n\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" width=\"1200\" height=\"675\" src=\"https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/07\/ChatGPT-Image-Jul-6-2026-09_36_49-PM-1200x675.webp\" alt=\"Common Mistakes to Avoid\" class=\"wp-image-121393\" srcset=\"https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/07\/ChatGPT-Image-Jul-6-2026-09_36_49-PM-1200x675.webp 1200w, https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/07\/ChatGPT-Image-Jul-6-2026-09_36_49-PM-300x169.webp 300w, https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/07\/ChatGPT-Image-Jul-6-2026-09_36_49-PM-768x432.webp 768w, https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/07\/ChatGPT-Image-Jul-6-2026-09_36_49-PM-1536x864.webp 1536w, https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/07\/ChatGPT-Image-Jul-6-2026-09_36_49-PM-150x84.webp 150w, https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/07\/ChatGPT-Image-Jul-6-2026-09_36_49-PM.webp 1672w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" title=\"\"><\/figure>\n\n\n\n<ul>\n<li>Confusing INNER JOIN with LEFT JOIN and losing rows silently<\/li>\n\n\n\n<li>Ignoring NULLs \u2014 use IS NULL or COALESCE instead of <code>= NULL<\/code><\/li>\n\n\n\n<li>Writing unindexed queries on large tables, which slows everything down<\/li>\n\n\n\n<li>Skipping practice on real datasets and only memorizing syntax<\/li>\n<\/ul>\n\n\n\n<p><em>Master SQL queries from basic to advanced with HCL GUVI\u2019s Mastering<a href=\"https:\/\/www.guvi.in\/courses\/databases\/masteringmysql\/?utm_source=blog&amp;utm_medium=hyperlink&amp;utm_campaign=sql-queries-with-examples-complete-guide-from-basic-to-advanced-2026\" target=\"_blank\" rel=\"noreferrer noopener\"> MySQL Course<\/a>. Learn database fundamentals, SQL commands, joins, subqueries, and practical query writing to strengthen your data management and analysis skills. Enrol today to build confidence in writing SQL queries for real-world applications.<\/em><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Common Mistakes Beginners Make in SQL<\/strong><\/h2>\n\n\n\n<p>Beginners often know basic SQL syntax but struggle with query logic, data relationships, and result accuracy.<\/p>\n\n\n\n<p>Common mistakes include:<\/p>\n\n\n\n<ul>\n<li><strong>Using the Wrong JOIN:<\/strong> Choosing an incorrect join type can remove needed rows or create unexpected duplicates.<\/li>\n\n\n\n<li><strong>Ignoring NULL Values:<\/strong> Comparisons with <code>NULL<\/code> require <code>IS NULL<\/code> or <code>IS NOT NULL<\/code>, not standard equality operators.<\/li>\n\n\n\n<li><strong>Forgetting GROUP BY Rules:<\/strong> Selecting non-aggregated columns without grouping them correctly can cause errors or misleading results.<\/li>\n\n\n\n<li><strong>Confusing WHERE and HAVING:<\/strong> Use <code>WHERE<\/code> before aggregation and <code>HAVING<\/code> to filter grouped results.<\/li>\n\n\n\n<li>*<em>Overusing SELECT :<\/em> Retrieving every column can reduce readability and increase unnecessary processing.<\/li>\n\n\n\n<li><strong>Missing JOIN Conditions:<\/strong> Incomplete join logic can produce duplicate-heavy or Cartesian results.<\/li>\n\n\n\n<li><strong>Ignoring Duplicate Records:<\/strong> Duplicate rows can distort counts, averages, and business metrics.<\/li>\n\n\n\n<li><strong>Writing Complex Queries Too Early:<\/strong> Beginners often combine too much logic in one query instead of breaking it into smaller steps.<\/li>\n\n\n\n<li><strong>Not Checking Data Types:<\/strong> Comparing incompatible data types can cause errors or incorrect filtering.<\/li>\n\n\n\n<li><strong>Using Incorrect Aggregate Logic:<\/strong> Functions such as <code>COUNT<\/code>, <code>SUM<\/code>, and <code>AVG<\/code> can produce misleading results when grouping is poorly defined.<\/li>\n\n\n\n<li><strong>Skipping Query Validation:<\/strong> Always check row counts, sample records, and expected outputs before trusting results.<\/li>\n\n\n\n<li><strong>Ignoring Query Readability:<\/strong> Poor aliases, inconsistent formatting, and deeply nested logic make SQL harder to debug and maintain.<\/li>\n\n\n\n<li><strong>Memorising Without Practising:<\/strong> SQL becomes easier through hands-on problems involving joins, filtering, aggregation, and real datasets.<\/li>\n\n\n\n<li><strong>Not Considering Performance:<\/strong> Repeated subqueries, unnecessary columns, and inefficient filtering can slow large database queries.<\/li>\n<\/ul>\n\n\n\n<p><strong><em>Know About <a href=\"https:\/\/www.guvi.in\/blog\/sql-project-ideas\/\" target=\"_blank\" data-type=\"link\" data-id=\"https:\/\/www.guvi.in\/blog\/sql-project-ideas\/\" rel=\"noreferrer noopener\">SQL Project Ideas<\/a><\/em><\/strong><\/p>\n\n\n\n<p class=\"has-text-align-center\"><strong><em>Ready to go from SQL beginner to pro?HCL GUVI\u2019s <a href=\"https:\/\/www.guvi.in\/hub\/dbms-and-sql-tutorial?utm_source=blog&amp;utm_medium=hyperlink&amp;utm_campaign=sql-queries-with-examples\" target=\"_blank\" rel=\"noreferrer noopener\">SQL Handbook<\/a><\/em><\/strong> <strong><em>guides you through practical examples, real-world projects, and hands-on exercises \u2014 all online and self-paced.<\/em><\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Wrapping it Up<\/strong><\/h2>\n\n\n\n<p>Mastering SQL requires more than memorising commands. Understanding how SELECT, JOIN, GROUP BY, subqueries, and window functions work together helps you solve real database problems confidently.<\/p>\n\n\n\n<p>Start with basic retrieval and filtering queries before progressing towards complex joins and analytical functions. Practise each concept using real datasets and review your results for accuracy.<\/p>\n\n\n\n<p>Consistent practice will strengthen your SQL fundamentals and prepare you for technical interviews, data analysis projects, and database-related roles.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>FAQs<\/strong><\/h2>\n\n\n<div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-question-1791749937935\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">What Are the Most Commonly Used SQL Queries?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>SELECT, INSERT, UPDATE, DELETE, JOIN, GROUP BY, and ORDER BY are among the most commonly used SQL commands and clauses. They help retrieve, modify, combine, summarise, and organise database records.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1791749949445\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">Which SQL Queries Are Most Important for Interviews?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>SQL interviews frequently test JOINs, GROUP BY, HAVING, subqueries, CTEs, and window functions. Candidates should also practise finding duplicate records, calculating rankings, and retrieving the second-highest salary.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1791749960545\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">What Is the Difference Between WHERE and HAVING in SQL?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>WHERE filters individual rows before grouping, whereas HAVING filters grouped results. HAVING is commonly used with aggregate functions such as COUNT, SUM, and AVG.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1791749973778\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">Which SQL Query Is Used to Find Duplicate Records?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>GROUP BY combined with HAVING COUNT(*) > 1 identifies repeated values. Analysts commonly use this approach to detect duplicate email addresses, customer IDs, or transaction records.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1791749987245\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">What Is the Difference Between JOIN and Subquery in SQL?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>JOIN combines related information from multiple tables. A subquery places one query inside another to support filtering, comparisons, or calculations. The appropriate choice depends on the required result and query structure.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1791750000961\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">How Long Does It Take to Learn Basic SQL Queries?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Beginners can learn basic SQL queries within two to four weeks of consistent practice. Advanced concepts such as window functions, query optimisation, and complex joins generally require additional hands-on experience.<\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div>","protected":false},"excerpt":{"rendered":"<p>SQL is one of the most valuable skills for anyone working with databases, data analytics, or software development. However, knowing SQL syntax is only the beginning. The real challenge is writing queries that retrieve accurate results, combine information from multiple tables, and solve practical business problems. A simple SELECT statement can retrieve employee records, whereas [&hellip;]<\/p>\n","protected":false},"author":60,"featured_media":144673,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[325,16],"tags":[],"views":"150033","authorinfo":{"name":"Vaishali","url":"https:\/\/www.guvi.in\/blog\/author\/vaishali\/"},"thumbnailURL":"https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2024\/01\/22736280-762D-4411-9889-DF87C19CDEA4-300x116.png","_links":{"self":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/39035"}],"collection":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/users\/60"}],"replies":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/comments?post=39035"}],"version-history":[{"count":101,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/39035\/revisions"}],"predecessor-version":[{"id":143865,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/39035\/revisions\/143865"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/media\/144673"}],"wp:attachment":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/media?parent=39035"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/categories?post=39035"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/tags?post=39035"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}