0% found this document useful (0 votes)
7 views2 pages

SQL Concepts and Real-World Scenarios

The document outlines key differences in SQL concepts such as WHERE vs. HAVING, various types of JOINs, and aggregate functions. It also presents real-world SQL questions for practice, including queries to find top customers, calculate growth rates, and identify duplicates. Additionally, it includes basic string and date function-related questions to enhance SQL skills.

Uploaded by

Su Kem
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views2 pages

SQL Concepts and Real-World Scenarios

The document outlines key differences in SQL concepts such as WHERE vs. HAVING, various types of JOINs, and aggregate functions. It also presents real-world SQL questions for practice, including queries to find top customers, calculate growth rates, and identify duplicates. Additionally, it includes basic string and date function-related questions to enhance SQL skills.

Uploaded by

Su Kem
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Key Differences:

1- WHERE vs. HAVING


2- UNION vs. UNION ALL
3-INNER JOIN vs. LEFT JOIN vs. RIGHT JOIN vs. FULL JOIN
4-RANK() vs. DENSE_RANK() vs. ROW_NUMBER()
5-EXCEPT (MINUS) vs. INTERSECT
6-Subqueries vs. CTEs
7-JOINs vs. Subqueries
8-Aggregate functions with GROUP BY vs. Window functions
9-Temporary Table vs Table Variable
10-COALESCE vs. ISNULL
11-CHAR vs. VARCHAR
12-DELETE vs. TRUNCATE vs. DROP
13-Stored Procedures vs. User-Defined Functions
14- VIEWs vs MATERLIZED VIEW
15- PRIMARY KEY vs UNIQUE KEY

Real-World SQL Questions and Scenarios for your practice.

1-Find the top 5 customers with the highest average order value in the
last quarter.
2-Identify customers who have made purchases in consecutive months.
3- Calculate the month-over-month growth rate of sales revenue.
4- Identify duplicate records in a table and remove them.
5- Find nth Highest Salary.
6- Find the employee who have salary more than his manager.
7- Find the customers who have placed orders in both 2022 and 2023.
8-Calculate the running total of sales for each product category.
9- Retrieve the first order date for each customer.
10- List all customers who have made more than 3 orders.
11- Find the customers who have the same last name.
12- Create a query to find the top 3 products in each category by sales.

Some Basic STRING & DATE functions related questions:

1-Extract the month from a date column.


2- Convert a string date to a date format.
3-Replace all null values in a column with a specific value.
4-Concatenate two string columns.
5-Split a comma separated string into individual values.
6-Find the longest string in a column.
7-Create a query to find the percentage of total sales for each product.
8- Find the average time between customer orders.
9- Identify customers who have churned (not placed an order in the last 6
months).
10-Find the number of customers who joined each month/Quarter etc.

Common questions

Powered by AI

Window functions compute results across a specified range of rows relative to the current row without collapsing the results into a single output row, unlike aggregate functions used with GROUP BY which condense multiple input rows into a single output row. Window functions allow calculations such as rank, moving averages, and cumulative sums to be performed while keeping the original row data intact for further analysis .

Stored procedures are precompiled collections of one or more SQL statements that act like executable programs in the database, supporting transactions and allowing multiple operations, while user-defined functions are routines that return a value and cannot modify database states. Stored procedures can execute a set of tasks, accept input/output parameters, and typically perform broader tasks involving multiple steps, whereas functions are designed for simple computations and can be used in SELECT, WHERE, or GROUP BY clauses, restricted to returning a single value .

The WHERE clause is used to filter records before any groupings are made, typically working directly with individual rows, whereas the HAVING clause filters records after the group-by operation is performed, making it suitable for conditions on aggregate functions. Consequently, WHERE is used in pre-aggregation filtration, while HAVING serves post-aggregation filtration purposes .

The SQL UNION operator combines result sets of two or more SELECT queries into a single result set, removing duplicate rows in the process. In contrast, UNION ALL selects all rows from each query, including duplicates, which generally results in faster execution because it does not require an additional step to sort and eliminate duplicates. Therefore, UNION is beneficial when distinct results are necessary, while UNION ALL is suitable for performance optimization when duplicate entry removal is not required .

CTEs provide improved readability and organization for complex SQL queries by allowing separation of logical parts into named expressions, which can be easier to write, read, and debug compared to deeply nested subqueries. They support recursive queries which simplify operations that require iteration, such as hierarchical data queries, whereas subqueries do not natively handle recursion and can become difficult to manage as complexity increases .

Temporary tables are created in the tempdb database and are capable of efficient handling of large datasets, permitting indexing and transaction logging, which makes them more suitable for advanced, resource-intensive operations. Table variables, in contrast, are stored in memory with minimal transaction logs, affecting performance on larger datasets as they do not provide index support or statistics update, making them better for smaller datasets and requiring simpler concurrency considerations .

DELETE removes rows one at a time and logs individual row deletions, allowing the possibility of rollback and triggering of delete triggers, thus preserving data integrity. TRUNCATE, while non-logged and faster for large deletions, removes all rows without triggering delete triggers and cannot be reverted if the operation is not part of a transaction block. DROP completely removes a table structure, including data, triggers, and permissions, making rollback impossible and resulting in permanent data loss .

COALESCE follows the SQL standard, making it portable across different SQL dialects, and it can handle multiple arguments, returning the first non-null value from the list provided, offering flexibility beyond the single input argument limitation of ISNULL. ISNULL is specific to certain SQL dialects like SQL Server, where it is implemented for backward compatibility, and typically used for replacing NULLs with a specified value but lacks the versatility that COALESCE provides in complex expressions .

Primary keys uniquely identify each row within a table and enforce entity integrity by not allowing NULL values in the key column(s). They always create a clustered index on the primary key column by default. Unique keys also ensure uniqueness for each row but, unlike primary keys, they allow one NULL value per column and create a non-clustered index. Both keys maintain data integrity, with primary keys serving as the table's primary identifier and unique keys preventing duplicate values .

INNER JOIN returns rows when there is a match in both participating tables. LEFT JOIN returns all rows from the left table, with matching rows in the right table, or NULL if there is no match. RIGHT JOIN behaves inversely, returning all rows from the right table with matching rows from the left table. FULL JOIN combines the results of both LEFT and RIGHT joins, returning all records when there is a match, and filling in NULLs where data is missing on either side .

You might also like