0% found this document useful (0 votes)
6 views18 pages

SQL UNION vs UNION ALL & RANK vs DENSE_RANK

The document outlines the differences between SQL concepts such as UNION vs UNION ALL and RANK vs DENSE_RANK, providing examples and use cases for each. It also explains various SQL clauses, their purposes, and includes a list of common SQL interview questions with answers. Key takeaways include the importance of understanding these differences and clauses for effective SQL querying and interview preparation.

Uploaded by

shai_57744181
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)
6 views18 pages

SQL UNION vs UNION ALL & RANK vs DENSE_RANK

The document outlines the differences between SQL concepts such as UNION vs UNION ALL and RANK vs DENSE_RANK, providing examples and use cases for each. It also explains various SQL clauses, their purposes, and includes a list of common SQL interview questions with answers. Key takeaways include the importance of understanding these differences and clauses for effective SQL querying and interview preparation.

Uploaded by

shai_57744181
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

Here are the "difference between" questions and answers for UNION vs UNION ALL and

RANK vs DENSE_RANK, along with examples for clarity:

1. Difference between UNION and UNION ALL

UNION UNION ALL


Combines results from two or more SELECT Combines results from two or more SELECT
statements and removes duplicate rows. statements, including duplicates.
Performs additional processing to eliminate
Faster since it doesn’t eliminate duplicates.
duplicates.
Example use case: Ensuring unique records from Example use case: Preserving all records, even
two tables. duplicates.
Example: Example:
```sql ```sql
SELECT name FROM employees SELECT name FROM employees
UNION UNION ALL
SELECT name FROM contractors; SELECT name FROM contractors;
``` ```

 Key takeaway: Use UNION for distinct results and UNION ALL for faster queries with all
records.

2. Difference between RANK and DENSE_RANK

RANK DENSE_RANK
Assigns a rank to each row, skipping ranks
Assigns a rank to each row, without skipping ranks
after duplicates. after duplicates.
Gaps appear in ranking if there are ties.
No gaps in ranking, even with ties.
Example: Example:
```sql ```sql
SELECT name, salary, SELECT name, salary,
DENSE_RANK() OVER (ORDER BY salary
RANK() OVER (ORDER BY salary DESC)
DESC)
AS rank AS dense_rank
FROM employees; FROM employees;
``` ```

Example Output

For a table of employees with salaries:


Name Salary RANK DENSE_RANK
Alice 1000 1 1
Bob 1000 1 1
Charlie 900 3 2
David 800 4 3

 Key takeaway: Use RANK when gaps in rank values are acceptable and DENSE_RANK
when continuous ranking is needed.

Summary of Both Differences:

1. UNION vs UNION ALL:


o UNION removes duplicates, while UNION ALL retains them.
o Use UNION for unique results and UNION ALL for speed and complete data.
2. RANK vs DENSE_RANK:
o RANK skips ranks when there are ties, while DENSE_RANK assigns continuous ranks.
o Use RANK when skipping ranks after ties is required and DENSE_RANK for compact
ranking.

These differences are frequently asked in interviews, so practicing them with examples will
prepare you for follow-up questions.

In SQL, a clause is a building block of a query that performs a specific function. These clauses define the
structure and behavior of the query, allowing you to retrieve, manipulate, and organize data from a
database. Here's an overview of common SQL clauses:

CLAUSE AND ITS TYPE


In SQL, a clause is a building block of a query that performs a specific function. These clauses
define the structure and behavior of the query, allowing you to retrieve, manipulate, and organize
data from a database. Here's an overview of common SQL clauses:

1. SELECT Clause

 Purpose: Specifies the columns or expressions to retrieve from the database.


 Example:
 SELECT first_name, last_name FROM employees;
This retrieves the first_name and last_name columns from the employees table.

2. FROM Clause

 Purpose: Identifies the table(s) or source(s) of data for the query.


 Example:
 SELECT * FROM orders;

This retrieves all columns from the orders table.

3. WHERE Clause

 Purpose: Filters rows based on a specified condition.


 Example:
 SELECT * FROM customers WHERE country = 'USA';

This retrieves customers where the country column equals 'USA'.

4. GROUP BY Clause

 Purpose: Groups rows sharing a common value and is often used with aggregate
functions like COUNT, SUM, or AVG.
 Example:
 SELECT department_id, COUNT(*) FROM employees GROUP BY department_id;

This counts the number of employees in each department.

5. HAVING Clause

 Purpose: Filters groups based on a condition (used after GROUP BY).


 Example:
 SELECT department_id, AVG(salary) FROM employees
 GROUP BY department_id
 HAVING AVG(salary) > 50000;

This retrieves departments with an average salary greater than $50,000.


6. ORDER BY Clause

 Purpose: Sorts the results by one or more columns in ascending (ASC) or descending
(DESC) order.
 Example:
 SELECT * FROM products ORDER BY price DESC;

This sorts the products by price in descending order.

7. JOIN Clause

 Purpose: Combines rows from two or more tables based on a related column.
 Example:
 SELECT employees.first_name, [Link]
 FROM employees
 INNER JOIN departments
 ON employees.department_id = [Link];

This joins the employees and departments tables based on the department ID.

8. LIMIT Clause

 Purpose: Restricts the number of rows returned by the query (specific to databases like
MySQL and PostgreSQL).
 Example:
 SELECT * FROM customers LIMIT 10;

This retrieves the first 10 rows from the customers table.

9. INSERT Clause

 Purpose: Adds new rows to a table.


 Example:
 INSERT INTO employees (first_name, last_name) VALUES ('John', 'Doe');

This inserts a new row into the employees table.

10. UPDATE Clause


 Purpose: Modifies existing rows in a table.
 Example:
 UPDATE employees SET salary = salary * 1.1 WHERE department_id = 5;

This updates salaries for employees in department 5.

11. DELETE Clause

 Purpose: Removes rows from a table.


 Example:
 DELETE FROM employees WHERE department_id = 10;

This deletes rows where the department ID is 10.

12. UNION Clause

 Purpose: Combines the results of two or more SELECT statements (removing duplicates
unless UNION ALL is used).
 Example:
 SELECT name FROM employees
 UNION
 SELECT name FROM contractors;

This combines the names from employees and contractors.

13. DISTINCT Clause

 Purpose: Removes duplicate rows from the result set.


 Example:
 SELECT DISTINCT country FROM customers;

This retrieves unique countries from the customers table.

14. EXISTS Clause

 Purpose: Checks for the existence of rows in a subquery.


 Example:
 SELECT name FROM employees WHERE EXISTS (
 SELECT 1 FROM projects WHERE [Link] = projects.manager_id
 );

This retrieves employees who manage at least one project.

Summary

 Clauses are combined in SQL queries to achieve specific tasks like retrieving, filtering,
grouping, and sorting data.
 The order of execution generally follows: FROM, WHERE, GROUP BY, HAVING,
SELECT, ORDER BY, LIMIT.

Here’s a comprehensive list of SQL interview questions based on clauses, along with well-
crafted answers to each question:

Basic Questions

1. What are SQL clauses, and why are they important?

 Answer: SQL clauses are the components of a query that define its functionality, such as
selecting, filtering, grouping, and sorting data. They are essential because they allow
precise control over how data is retrieved or manipulated in a database.

2. Explain the SELECT clause.

 Answer: The SELECT clause specifies the columns or expressions to retrieve from a table.
For example:
 SELECT name, age FROM users;

This query retrieves the name and age columns from the users table.

3. What does the WHERE clause do?

 Answer: The WHERE clause filters rows based on a condition. For example:
 SELECT * FROM orders WHERE amount > 1000;
This retrieves all orders where the amount is greater than 1000.

4. What is the purpose of the GROUP BY clause?

 Answer: The GROUP BY clause groups rows with the same values in specified columns,
often used with aggregate functions. For example:
 SELECT category, COUNT(*) FROM products GROUP BY category;

This counts the number of products in each category.

5. How is HAVING different from WHERE?

 Answer: The WHERE clause filters rows before grouping, while HAVING filters groups
created by GROUP BY. For example:
 SELECT category, SUM(sales)
 FROM products
 GROUP BY category
 HAVING SUM(sales) > 5000;

Here, HAVING filters categories with total sales above 5000.

6. How does the ORDER BY clause work?

 Answer: The ORDER BY clause sorts query results in ascending (ASC) or descending
(DESC) order. For example:
 SELECT name, age FROM users ORDER BY age DESC;

This sorts users by age in descending order.

7. Explain the DISTINCT clause with an example.

 Answer: The DISTINCT clause removes duplicate rows in the result set. For example:
 SELECT DISTINCT country FROM customers;

This retrieves unique country names from the customers table.

8. What is a JOIN clause, and what are its types?


 Answer: The JOIN clause combines rows from two or more tables based on a related
column. Types of joins include:
o INNER JOIN: Returns rows with matching values in both tables.
o LEFT JOIN: Returns all rows from the left table, even if there's no match in the
right table.
o RIGHT JOIN: Returns all rows from the right table, even if there's no match in
the left table.
o FULL JOIN: Returns rows with matches in either or both tables.

Example of INNER JOIN:

SELECT [Link], d.department_name


FROM employees e
INNER JOIN departments d
ON e.department_id = [Link];

Intermediate Questions

9. Can you explain the LIMIT clause with an example?

 Answer: The LIMIT clause restricts the number of rows returned by a query. For
example:
 SELECT * FROM employees LIMIT 5;

This retrieves the first 5 rows from the employees table.

10. What is the purpose of the UNION clause?

 Answer: The UNION clause combines results from two or more SELECT statements,
removing duplicates by default. For example:
 SELECT name FROM employees
 UNION
 SELECT name FROM contractors;

This retrieves a unique list of names from both employees and contractors.

If duplicates are allowed, use UNION ALL.

11. Explain the EXISTS clause.

 Answer: The EXISTS clause checks for the existence of rows in a subquery. For example:
 SELECT name FROM employees
 WHERE EXISTS (
 SELECT 1 FROM projects WHERE [Link] = projects.manager_id
 );

This retrieves employees who manage at least one project.

12. How can you use the CASE statement within the SELECT clause?

 Answer: The CASE statement is used for conditional logic. For example:
 SELECT name,
 CASE
 WHEN age < 18 THEN 'Minor'
 WHEN age BETWEEN 18 AND 60 THEN 'Adult'
 ELSE 'Senior'
 END AS age_group
 FROM users;

This categorizes users into age groups.

13. What is the difference between ALL and ANY in a WHERE clause?

 Answer:
o ALL: The condition must be true for all values in a subquery.
o ANY: The condition must be true for at least one value in a subquery.

Example:

SELECT * FROM products WHERE price > ALL (SELECT price FROM discounts);

This retrieves products priced higher than all discounted prices.

Advanced Questions

14. How is the OVER clause used in SQL?

 Answer: The OVER clause defines a window for analytic functions. For example:
 SELECT name,
 salary,
 RANK() OVER (ORDER BY salary DESC) AS rank
 FROM employees;

This assigns a rank to employees based on their salary.


15. Can you explain the use of CTE with clauses like WHERE and GROUP BY?

 Answer: Common Table Expressions (CTEs) simplify queries and can be used with other
clauses. For example:
 WITH SalesData AS (
 SELECT region, SUM(sales) AS total_sales
 FROM orders
 GROUP BY region
 )
 SELECT region FROM SalesData WHERE total_sales > 50000;

This creates a temporary result set (SalesData) and filters regions with total sales above
50,000.

16. How do window functions differ from GROUP BY?

 Answer: Window functions perform calculations across a set of rows related to the
current row, while GROUP BY aggregates rows into a single result per group. Window
functions do not reduce the number of rows in the result set.

Here’s a list of "difference between" SQL questions with clear and concise answers. These
types of questions are common in interviews to test your understanding of key concepts.

1. Difference between WHERE and HAVING clauses

WHERE HAVING

Filters rows before grouping. Filters groups after grouping.

Cannot be used with aggregate functions. Can use aggregate functions.

Example: Example:

```sql ```sql

SELECT * FROM sales SELECT region, SUM(sales)

WHERE region = 'North'; FROM sales GROUP BY region


WHERE HAVING

HAVING SUM(sales) > 10000;

``` ```

2. Difference between JOIN and UNION

JOIN UNION

Combines columns from multiple tables based on a Combines results from multiple SELECT statements
related column. into a single result set.

Merges data horizontally. Merges data vertically.

Requires a relationship (e.g., ON clause). Does not require a relationship between datasets.

Example (INNER JOIN): Example (UNION):

```sql ```sql

SELECT [Link], d.department_name SELECT name FROM employees

FROM employees e UNION

INNER JOIN departments d SELECT name FROM contractors;

ON e.department_id = [Link]; ```

```

3. Difference between INNER JOIN and OUTER JOIN

INNER JOIN OUTER JOIN

Returns only matching rows from both Returns all rows from one or both tables, with NULLs for
tables. unmatched rows.

Excludes non-matching rows. Includes non-matching rows.

Types: N/A Types: LEFT, RIGHT, FULL

Example (INNER JOIN): Example (LEFT JOIN):


INNER JOIN OUTER JOIN

```sql ```sql

SELECT [Link], d.department_name SELECT [Link], d.department_name

FROM employees e FROM employees e

INNER JOIN departments d LEFT JOIN departments d

ON e.department_id = [Link]; ON e.department_id = [Link];

``` ```

4. Difference between DELETE and TRUNCATE

DELETE TRUNCATE

Removes specific rows using a condition. Removes all rows from a table.

Slower because it logs individual row deletions. Faster because it doesn't log individual rows.

Can use WHERE clause. Cannot use WHERE clause.

Rows deleted can be rolled back. Cannot roll back rows.

Example: Example:

```sql ```sql

DELETE FROM employees WHERE id = 5; TRUNCATE TABLE employees;

``` ```

5. Difference between PRIMARY KEY and UNIQUE Key

PRIMARY KEY UNIQUE Key

Ensures uniqueness and cannot contain NULLs. Ensures uniqueness but can contain a single NULL.

Only one per table. Multiple UNIQUE keys allowed per table.
PRIMARY KEY UNIQUE Key

Implicitly creates a clustered index. Creates a non-clustered index.

Example: Example:

```sql ```sql

CREATE TABLE users ( CREATE TABLE users (

id INT PRIMARY KEY); email VARCHAR(100) UNIQUE);

``` ```

6. Difference between UNION and UNION ALL

UNION UNION ALL

Removes duplicate rows. Includes all rows, including duplicates.

Slower due to duplicate elimination. Faster as it doesn’t remove duplicates.

Example: Example:

```sql ```sql

SELECT name FROM employees SELECT name FROM employees

UNION UNION ALL

SELECT name FROM contractors; SELECT name FROM contractors;

``` ```

7. Difference between NATURAL JOIN and INNER JOIN

NATURAL JOIN INNER JOIN

Matches columns with the same name and type Matches rows based on explicitly defined
automatically. conditions.
NATURAL JOIN INNER JOIN

No need to specify ON clause. Requires ON or USING clause.

Can lead to unintended matches if column names


Offers precise control over join conditions.
overlap.

Example (NATURAL JOIN): Example (INNER JOIN):

```sql ```sql

SELECT * FROM employees SELECT [Link], [Link]

NATURAL JOIN departments; FROM employees e

``` INNER JOIN departments d

ON e.department_id = [Link];

```

8. Difference between ROW_NUMBER() and RANK()

ROW_NUMBER() RANK()

Assigns a unique number to each row, regardless Assigns the same rank to duplicate values, skipping
of duplicates. subsequent ranks.

Example: Example:

```sql ```sql

SELECT name, SELECT name,

ROW_NUMBER() OVER (ORDER BY salary) RANK() OVER (ORDER BY salary)

AS row_num AS rank_num

FROM employees; FROM employees;

``` ```

9. Difference between VIEW and TABLE


VIEW TABLE

A virtual table derived from a query. A physical database object that stores data.

Does not store data physically. Stores data physically.

Changes do not reflect elsewhere unless explicitly


Changes in underlying tables reflect in the view.
joined.

Example: Example:

```sql ```sql

CREATE VIEW active_users AS CREATE TABLE users (

SELECT * FROM users WHERE status='active'; id INT, name VARCHAR(100));

``` ```

10. Difference between CLUSTERED and NON-CLUSTERED Index

CLUSTERED INDEX NON-CLUSTERED INDEX

Sorts and stores rows physically in the table. Stores a pointer to the actual data.

Only one clustered index per table. Multiple non-clustered indexes allowed.

Faster for range queries. Slower for range queries but good for specific lookups.

Example: Example:

```sql ```sql

CREATE CLUSTERED INDEX idx_name CREATE NONCLUSTERED INDEX idx_name

ON employees (id); ON employees (salary);

``` ```

11. Difference between TEMPORARY and GLOBAL TEMPORARY TABLES


TEMPORARY TABLE GLOBAL TEMPORARY TABLE

Available only to the session that created it. Accessible by all sessions.

Dropped automatically when the session ends. Dropped when all sessions using it close.

Example: Example:

```sql ```sql

CREATE TEMPORARY TABLE temp_users ( CREATE GLOBAL TEMPORARY TABLE gtemp_users (

id INT, name VARCHAR(100)); id INT, name VARCHAR(100));

``` ```

These differences clarify many key concepts in SQL and prepare you to tackle detailed interview
questions effectively.

Here are the "difference between" questions and answers for UNION vs UNION ALL and
RANK vs DENSE_RANK, along with examples for clarity:

1. Difference between UNION and UNION ALL

UNION UNION ALL


Combines results from two or more SELECT Combines results from two or more SELECT
statements and removes duplicate rows. statements, including duplicates.
Performs additional processing to eliminate
Faster since it doesn’t eliminate duplicates.
duplicates.
Example use case: Ensuring unique records from Example use case: Preserving all records, even
two tables. duplicates.
Example: Example:
```sql ```sql
SELECT name FROM employees SELECT name FROM employees
UNION UNION ALL
SELECT name FROM contractors; SELECT name FROM contractors;
``` ```

 Key takeaway: Use UNION for distinct results and UNION ALL for faster queries with all
records.
2. Difference between RANK and DENSE_RANK

RANK DENSE_RANK
Assigns a rank to each row, skipping ranks
Assigns a rank to each row, without skipping ranks
after duplicates. after duplicates.
Gaps appear in ranking if there are ties.
No gaps in ranking, even with ties.
Example: Example:
```sql ```sql
SELECT name, salary, SELECT name, salary,
DENSE_RANK() OVER (ORDER BY salary
RANK() OVER (ORDER BY salary DESC)
DESC)
AS rank AS dense_rank
FROM employees; FROM employees;
``` ```

Example Output

For a table of employees with salaries:

Name Salary RANK DENSE_RANK


Alice 1000 1 1
Bob 1000 1 1
Charlie 900 3 2
David 800 4 3

 Key takeaway: Use RANK when gaps in rank values are acceptable and DENSE_RANK
when continuous ranking is needed.

Summary of Both Differences:

1. UNION vs UNION ALL:


o UNION removes duplicates, while UNION ALL retains them.
o Use UNION for unique results and UNION ALL for speed and complete data.
2. RANK vs DENSE_RANK:
o RANK skips ranks when there are ties, while DENSE_RANK assigns continuous ranks.
o Use RANK when skipping ranks after ties is required and DENSE_RANK for compact
ranking.

These differences are frequently asked in interviews, so practicing them with examples will
prepare you for follow-up questions.

You might also like