0% found this document useful (0 votes)
19 views11 pages

Five SQL Tricks Every DBA Should Know

The document outlines five essential SQL tricks for Oracle DBAs aimed at improving efficiency and simplifying tasks. These tricks include using LISTAGG for string concatenation, the WITH clause for manageable queries, MERGE for upserts, PIVOT for transforming rows into columns, and DBMS_PARALLEL_EXECUTE for parallel processing. Each trick is accompanied by examples demonstrating its practical application and benefits.

Uploaded by

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

Five SQL Tricks Every DBA Should Know

The document outlines five essential SQL tricks for Oracle DBAs aimed at improving efficiency and simplifying tasks. These tricks include using LISTAGG for string concatenation, the WITH clause for manageable queries, MERGE for upserts, PIVOT for transforming rows into columns, and DBMS_PARALLEL_EXECUTE for parallel processing. Each trick is accompanied by examples demonstrating its practical application and benefits.

Uploaded by

sud2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Five SQL Tricks Every DBA Should Know

SQL, PL/SQL Scripts

Asfaw Gedamu

Download this and similar documents from:


https://t.me/paragonacademy
Are you an Oracle DBA looking to level up your SQL game? Here are five not-so-obvious
tricks that many DBAs might overlook but can save you time, simplify your tasks, and make
your life easier! Each trick includes a brief explanation, sample input/output data, and how
it can make a DBA's life easier.

Why These Tricks Matter

1. Save Time: Automate repetitive tasks and process data faster.

2. Simplify Code: Write cleaner, more maintainable queries.

3. Boost Performance: Leverage Oracle’s built-in features for efficiency.

Now to the list:

1. Use `LISTAGG` for Concatenating Strings

Tired of writing complex loops to concatenate strings? LISTAGG is your new best friend! It
aggregates strings into a single value, perfect for reporting.

Example 1:

Input Data: `Orders` and `OrderDetails` tables.

1. | OrderID | CustomerID | ProductID |


2. |---------|------------|-----------|
3. | 1 | 101 | 201 |
4. | 1 | 101 | 202 |
5. | 2 | 102 | 201 |
6. | 3 | 101 | 203 |
7. | 4 | 103 | 202 |
8. | 5 | 104 | 201 |
9. | 6 | 105 | 204 |
10. | 7 | 106 | 205 |
11. | 8 | 107 | 201 |
12. | 9 | 108 | 202 |
13. | 10 | 109 | 203 |
14. | 11 | 110 | 204 |
15.

1. SELECT
2. CustomerID,
3. LISTAGG(ProductID, ', ') WITHIN GROUP (ORDER BY ProductID) AS Products
4. FROM
5. OrderDetails
6. JOIN
7. Orders ON OrderDetails.OrderID = Orders.OrderID
8. GROUP BY
9. CustomerID;
10.

Output:

1. | CustomerID | Products |
2. |------------|------------------------|
3. | 101 | 201, 202, 203 |
4. | 102 | 201 |
5. | 103 | 202 |
6. | 104 | 201 |
7. | 105 | 204 |
8. | 106 | 205 |
9. | 107 | 201 |
10. | 108 | 202 |
11. | 109 | 203 |
12. | 110 | 204 |
13.

Why It Helps:

- Combines multiple rows into a single string, simplifying reporting.

- Eliminates the need for complex PL/SQL loops or external scripting.

Example 2:

1. SELECT department_id,
2. LISTAGG(employee_name, ', ') WITHIN GROUP (ORDER BY employee_name) AS employee_names
3. FROM employees
4. GROUP BY department_id;
5.

Input Data for employees

employee_id employee_name department_id

1 Alice 10

2 Bob 10

3 Charlie 20
employee_id employee_name department_id

4 David 20

Output Data

department_id employee_names

10 Alice, Bob

20 Charlie, David

Benefits

- Reporting: Simplifies the creation of comma-separated lists for reporting.


- Efficiency: Reduces the need for complex string manipulation in application
code.

2. Use `WITH` Clause (Common Table Expressions - CTEs)

Complex queries can be a nightmare to maintain. The WITH clause breaks them into
manageable chunks, improving readability and performance.

CTEs simplify querying hierarchical data by allowing recursion. This is particularly useful for
organizational structures.

Example 1:

Input Data: `Orders` table.

1. | OrderID | CustomerID | TotalAmount |


2. |---------|------------|-------------|
3. | 1 | 101 | 200.00 |
4. | 2 | 102 | 150.00 |
5. | 3 | 101 | 300.00 |
6. | 4 | 103 | 100.00 |
7. | 5 | 104 | 250.00 |
8. | 6 | 105 | 400.00 |
9. | 7 | 106 | 50.00 |
10. | 8 | 107 | 300.00 |
11. | 9 | 108 | 200.00 |
12. | 10 | 109 | 150.00 |
13. | 11 | 110 | 500.00 |
14.

1. WITH CustomerSales AS (
2. SELECT
3. CustomerID,
4. SUM(TotalAmount) AS TotalSales
5. FROM
6. Orders
7. GROUP BY
8. CustomerID
9. )
10. SELECT
11. CustomerID,
12. TotalSales
13. FROM
14. CustomerSales
15. WHERE
16. TotalSales > 200;
17.

Output:

1. | CustomerID | TotalSales |
2. |------------|------------|
3. | 101 | 500.00 |
4. | 104 | 250.00 |
5. | 105 | 400.00 |
6. | 107 | 300.00 |
7. | 108 | 200.00 |
8. | 110 | 500.00 |
9.

Why It Helps:

- Breaks down complex queries into manageable parts.

- Improves readability and maintainability.

- Can be reused multiple times in the same query.

Example 2:

Input Data: employees table.

1. employee_id first_name last_name manager_id


2. 1 Alice Green NULL
3. 2 Bob Brown 1
4. 3 Charlie Black 1
5. 4 David White 2
6. 5 Emily Davis 2
7.

Recursive CTE for Hierarchical Query


1. WITH RECURSIVE employee_hierarchy AS (
2. SELECT employee_id, manager_id, first_name, last_name
3. FROM employees
4. WHERE manager_id IS NULL
5. UNION ALL
6. SELECT e.employee_id, e.manager_id, e.first_name, e.last_name
7. FROM employees e
8. JOIN employee_hierarchy eh ON e.manager_id = eh.employee_id
9. )
10. SELECT * FROM employee_hierarchy;
11.

Output Data (Employee Hierarchy)

1. employee_id manager_id first_name last_name


2. 1 NULL Alice Green
3. 2 1 Bob Brown
4. 3 1 Charlie Black
5. 4 2 David White
6. 5 2 Emily Davis
7.

Summary of Changes

- The output shows the complete hierarchy starting from the top-level manager (Alice)
down to her direct reports (Bob and Charlie), and then to their reports (David and Emily).

- Each employee's relationship is clear, illustrating who reports to whom.

3. Use `MERGE` for Upserts (Update or Insert)

Why write separate INSERT and UPDATE statements when you can do both in one go?
MERGE is a game-changer for data synchronization.

The `MERGE` statement performs an "upsert" operation (update if exists, insert if not) in a
single query.

Example 1:

Input Data: `Customers` table.

1. | CustomerID | CustomerName | JoinDate |


2. |------------|--------------|------------|
3. | 101 | John Doe | 2022-12-01 |
4. | 102 | Jane Smith | 2023-01-01 |
5. | 103 | Alice Brown | 2023-02-01 |
6. | 104 | Bob Johnson | 2023-03-01 |
7. | 105 | Charlie Lee | 2023-04-01 |
8. | 106 | David Kim | 2023-05-01 |
9. | 107 | Eve Wilson | 2023-06-01 |
10. | 108 | Frank White | 2023-07-01 |
11. | 109 | Grace Hall | 2023-08-01 |
12. | 110 | Henry Adams | 2023-09-01 |
13.

1. MERGE INTO Customers c


2. USING (
3. SELECT 111 AS CustomerID, 'Ivy Clark' AS CustomerName, SYSDATE AS JoinDate FROM dual
4. UNION ALL
5. SELECT 101 AS CustomerID, 'John Doe Updated' AS CustomerName, SYSDATE AS JoinDate FROM dual
6. ) new_customer
7. ON (c.CustomerID = new_customer.CustomerID)
8. WHEN MATCHED THEN
9. UPDATE SET c.CustomerName = new_customer.CustomerName, c.JoinDate = new_customer.JoinDate
10. WHEN NOT MATCHED THEN
11. INSERT (CustomerID, CustomerName, JoinDate)
12. VALUES (new_customer.CustomerID, new_customer.CustomerName, new_customer.JoinDate);
13.

Output:

- Updates `CustomerID = 101` with the new name `John Doe Updated`.

- Inserts a new row for `CustomerID = 111` with the name `Ivy Clark`.

Why It Helps:

- Simplifies data synchronization tasks.

- Reduces the need for separate `INSERT` and `UPDATE` logic.

Example 2.

1. employee_id first_name last_name salary


2. 1 John Doe 70000
3. 2 Jane Smith 80000
4. 3 Emily Johnson 72000
5.

Input Data for new_employees (new records)

1. employee_id first_name last_name salary


2. 1 John Doe 75000
3. 2 Jane Smith 80000
4. 3 Mark Taylor 90000
5. 4 Alice Green 65000
6.

MERGE Statement
1. MERGE INTO employees e
2. USING (SELECT * FROM new_employees) n
3. ON (e.employee_id = n.employee_id)
4. WHEN MATCHED THEN
5. UPDATE SET e.salary = n.salary
6. WHEN NOT MATCHED THEN
7. INSERT (employee_id, first_name, last_name, salary)
8. VALUES (n.employee_id, n.first_name, n.last_name, n.salary);
9.

Output Table: employees

employee_id first_name last_name salary


1 John Doe 75000
2 Jane Smith 80000
3 Emily Johnson 72000
3 Mark Taylor 90000

Summary of Changes

• Employees with employee_id 1 and 2 had their salaries updated from 70000 to
75000 and 80000, respectively.

• Two new employees (Mark Taylor and Alice Green) were inserted into the table.

4. Use `PIVOT` for Transforming Rows into Columns

Need to generate summary reports? PIVOT transforms rows into columns, making your life
so much easier to generate summary reports.

Input Data: `Orders` and `OrderDetails` tables.

1. | CustomerID | ProductID | Quantity |


2. |------------|-----------|----------|
3. | 101 | 201 | 2 |
4. | 101 | 202 | 1 |
5. | 102 | 201 | 3 |
6. | 103 | 202 | 2 |
7. | 104 | 201 | 1 |
8. | 105 | 204 | 4 |
9. | 106 | 205 | 1 |
10. | 107 | 201 | 2 |
11. | 108 | 202 | 3 |
12. | 109 | 203 | 1 |
13. | 110 | 204 | 2 |
14.
1. SELECT *
2. FROM (
3. SELECT
4. CustomerID,
5. ProductID,
6. Quantity
7. FROM
8. OrderDetails
9. JOIN
10. Orders ON OrderDetails.OrderID = Orders.OrderID
11. )
12. PIVOT (
13. SUM(Quantity)
14. FOR ProductID IN (201 AS Product201, 202 AS Product202, 203 AS Product203, 204 AS
Product204, 205 AS Product205)
15. );
16.

Output:

1. | CustomerID | Product201 | Product202 | Product203 | Product204 | Product205 |


2. |------------|------------|------------|------------|------------|------------|
3. | 101 | 2 | 1 | null | null | null |
4. | 102 | 3 | null | null | null | null |
5. | 103 | null | 2 | null | null | null |
6. | 104 | 1 | null | null | null | null |
7. | 105 | null | null | null | 4 | null |
8. | 106 | null | null | null | null | 1 |
9. | 107 | 2 | null | null | null | null |
10. | 108 | null | 3 | null | null | null |
11. | 109 | null | null | 1 | null | null |
12. | 110 | null | null | null | 2 | null |
13.

Why It Helps:

- Simplifies reporting by transforming rows into columns.

- Reduces the need for complex `CASE` statements or manual transformations.

5. Use `DBMS_PARALLEL_EXECUTE` for Parallel Processing

Got a massive dataset to process? DBMS_PARALLEL_EXECUTE package breaks large tasks


into smaller chunks and runs them in parallel, speeding up bulk operations and saving you
hours!

Input Data: `Orders` table.


1. | OrderID | TotalAmount |
2. |---------|-------------|
3. | 1 | 200.00 |
4. | 2 | 150.00 |
5. | 3 | 300.00 |
6. | 4 | 100.00 |
7. | 5 | 250.00 |
8. | 6 | 400.00 |
9. | 7 | 50.00 |
10. | 8 | 300.00 |
11. | 9 | 200.00 |
12. | 10 | 150.00 |
13. | 11 | 500.00 |
14.

1. BEGIN
2. DBMS_PARALLEL_EXECUTE.CREATE_TASK('apply_discount_task');
3.
4. DBMS_PARALLEL_EXECUTE.CREATE_CHUNKS_BY_ROWID(
5. TASK_NAME => 'apply_discount_task',
6. TABLE_OWNER => 'YOUR_SCHEMA',
7. TABLE_NAME => 'Orders',
8. BY_ROW => TRUE,
9. CHUNK_SIZE => 100
10. );
11.
12. DBMS_PARALLEL_EXECUTE.RUN_TASK(
13. TASK_NAME => 'apply_discount_task',
14. SQL_STATEMENT => 'UPDATE Orders SET TotalAmount = TotalAmount * 0.9 WHERE rowid BETWEEN
:start_id AND :end_id',
15. LANGUAGE_FLAG => DBMS_SQL.NATIVE
16. );
17.
18. DBMS_PARALLEL_EXECUTE.DROP_TASK('apply_discount_task');
19. END;
20.

Output:

All orders are updated with a 10% discount applied.

Why It Helps:

- Speeds up large-scale data operations by leveraging parallel processing.

- Reduces the time required for bulk updates or inserts.


Summary of Benefits

1. Simplifies Reporting: `LISTAGG` and `PIVOT` make it easier to generate complex


reports.

2. Improves Query Readability: `WITH` clause and `MERGE` make queries easier to
understand and maintain.

The MERGE statement consolidates updates and inserts into one operation, while the
recursive CTE effectively reveals hierarchical relationships within employee data. Both
techniques enhance the efficiency and clarity of database management tasks for DBAs.

3. Speeds Up Operations: `DBMS_PARALLEL_EXECUTE` enables parallel processing for


large tasks.

4. Reduces Code Complexity: These tricks eliminate the need for verbose PL/SQL or
external scripts.

Let me know if you need further clarification! If you found these tips helpful, give this post a
and share it with your network!

You might also like