Maulidya Yunanda Practice Sec 5 6

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

MAULIDYA YUNANDA

4617010051

PRACTICE 5.1
5-1: Conversion Functions
Practice Activities
Vocabulary
Identify the vocabulary word for each definition below.
 Used for text and character data of fixed length, including numbers, dashes, and special
characters. “CHAR “
 Used to remove padded blanks or to suppress leading zeros “fm “
 Functions that convert a value from one datatype to another. “conversion function “
 Used to store variable-length numeric data. “NUMBER “
 Used for character data of variable length, including numbers, special characters, and dashes.”
VARCHAR2 “
 Used for date and time values. “DATE “
 Converts dates or numbers to character strings with optional formatting “TO_CHAR “
 Century value depends on the specified year and the last two digits of the current year “RR “
 Converts a character string containing digits to a number with optional formatting “TO_NUMBER

 Numeric day of the month “DD “
 Converts a character string representing a date to a date value with op-tional formatting
“TO_DATE “

Try It / Solve It
1. List the last names and birthdays of Global Fast Food Employees. Convert the birth dates to
character data in the Month DD, YYYY format. Suppress any leading zeros..
SELECT last_name,TO_CHAR( birthdate, 'Month DD, YYYY') as birthdate
FROM f_staffs;

2. Convert January 3, 04, to the default date format 03-Jan-2004.


Application Express 5.0.3.00.03:
SELECT TO_DATE('January 3, 04', 'Month DD YY') as converted
FROM dual;

Application Express 4.0.2.00.09:


SELECT TO_CHAR( TO_DATE('January 3, 04', 'Month DD YY') , 'DD-Mon-YYYY') as
converted
FROM dual;
3. Format a query from the Global Fast Foods f_promotional_menus table to print out the start_date
of promotional code 110 as: The promotion began on the tenth of February 2004.
SELECT 'The promotion began on the ' || TO_CHAR(start_date, 'ddthsp "of" Month
YYYY') as output
FROM f_promotional_menus
WHERE code = 110;

4. Convert today’s date to a format such as: “Today is the Twentieth of March, Two Thousand Four”
SELECT 'Today is the ' || TO_CHAR(SYSDATE, 'fmDdthsp "of" Month, Year') as today
FROM dual;
Today is the Ninth of October , Twenty Sixteen
Today is the Ninth of October, Twenty Sixteen

5. List the ID, name, and salary for all Global Fast Foods employees. Display salary with a $ sign
and two decimal places.
SELECT id, first_name ||' '||last_name as name, TO_CHAR( salary, '$999999.99') as
salary
FROM f_staffs;
[salary column has datatype NUMBER(8,2)]

6. Ellen Abel is an employee who has received a $2,000 raise. Display her first name and last name,
her current salary, and her new salary. Display both salaries with a $ and two decimal places.
Label her new salary column AS New Salary.
SELECT first_name, last_name, TO_CHAR( salary, '$999999.99') as "Old Salary",
TO_CHAR( salary + 2000 , '$9999999.99') as "New Salary"
FROM employees
WHERE first_name = 'Ellen' AND last_name = 'Abel' ;

Please note extra digit here. Column Salary datatype is NUMBER(8,2). Suppose his
current salary is $999999.99, even if I add 0.01 and keep precision same, I will get:
SELECT first_name, last_name, TO_CHAR( salary, '$999999.99') as "Old Salary",
TO_CHAR( salary + 0.01 , '$999999.99') as "New Salary"
FROM employees
WHERE first_name = 'Ellen' AND last_name = 'Abel' ;

7. On what day of the week and date did Global Fast Foods’ promotional code 110 Valentine’s
Special begin?
SELECT TO_CHAR(start_date, 'fmdd-Mon-YYYY (Day)') as startdate
FROM f_promotional_menus
WHERE code = 110;
10-Feb-2004 (Tuesday ) – has extra space after day of week.
10-Feb-2004 (Tuesday) – no extra space after day of week
8. Create one query that will convert 25-Dec-2004 into each of the following (you will have to convert
25-Dec-2004 to a date and then to character data): December 25th, 2004 DECEMBER 25TH,
2004 25th december, 2004
December 25th, 2004

SELECT TO_CHAR(TO_DATE('25-Dec-2004', 'dd-Mon-yyyy'), 'Month ddth, yyyy') as


changeddate
FROM dual;

DECEMBER 25TH, 2004

SELECT TO_CHAR(TO_DATE('25-Dec-2004', 'dd-Mon-yyyy'), 'MONTH DDth, yyyy') as


changeddate
FROM dual;

25th december, 2004

SELECT TO_CHAR(TO_DATE('25-Dec-2004', 'dd-Mon-yyyy'), 'fmddth month, yyyy') as


changeddate
FROM dual;

9. Create a query that will format the DJs on Demand d_packages columns, low-range and high-
range package costs, in the format $2500.00.
SELECT code, TO_CHAR(low_range,'$999999.99') as low_range,
TO_CHAR(high_range,'$999999.99') as high_range
FROM d_packages ;
Data type is NUMBER(6,0), so after dot, I won’t eventually get anything else than 00 J

10. Convert JUNE192004 to a date using the fx format model.


SELECT TO_DATE('JUNE192004','fxfmMONTHddyyyy') as changeddate
FROM dual;
Application Express 5.0.3.00.03: 19-Jun-2004
Application Express 4.0.2.00.09: 06/19/2004
Why extra fm, just try: SELECT TO_CHAR(
TO_DATE('JUNE192004','fxMONTHddyyyy'), 'fxMONTHddyyyy')
FROM dual;

11. What is the distinction between implicit and explicit datatype conversion? Give an example of
each.
1). Implicit conversion:
SELECT SYSDATE
FROM dual;
Application Express 5.0.3.00.03: 19-Jun-2004
A date being converted to character data type using default format of 'DD-Mon-YYYY'
But in Application Express 4.0.2.00.09: 06/19/2004
That’s why I might not like implicit conversion and switch to explicit:
2). Explicit conversion:
SELECT TO_CHAR(SYSDATE, 'MONTH DDth, yyyy')
FROm dual;
A date being converted to character data type using non-default format 'MONTH DDth,
yyyy'

12. Why is it important from a business perspective to have datatype conversions?


This is required for database to meet the basic need of application - being of use to the
user. Date is saved as number internally in db which no user may be able to understand.
$ sign printed in front of a number gives idea which currency application is talking about.
It could have been euro dollar INR or anything a simple number that’s it. The value of
data in db lies in the fact that it conveys useful information and can be processed after
conversions.
Ini diperlukan untuk database untuk memenuhi kebutuhan dasar aplikasi - yang berguna
bagi pengguna. Tanggal disimpan sebagai nomor secara internal dalam db yang tidak
dapat dipahami oleh pengguna. Tanda $ yang tercetak di depan angka memberi ide
tentang aplikasi mata uang apa. Itu bisa saja euro dollar INR atau berapa pun jumlah
yang sederhana. Nilai data dalam db terletak pada fakta bahwa ia menyampaikan
informasi yang berguna dan dapat diproses setelah konversi.
PRACTICE 5.2

5-2: NULL Functions


Practice Activities
Vocabulary
Identify the vocabulary word for each definition below.
 Converts nulls to an actual value “NVL “
 Returns the first non-null expression in the list “COALESCE “
 Examines the first expression; if the first expression is not null, it returns the second expression;
if the first expression is null, it re-turns the third expression “NVL2 “
 Compares two expressions; if they are equal, the function returns null; if they are not equal, the
function returns the first expression “NULLIF “

Try It / Solve It
1. Create a report that shows the Global Fast Foods promotional name, start date, and end date
from the f_promotional_menus table. If there is an end date, temporarily replace it with “end in
two weeks.” If there is no end date, replace it with today’s date.
SELECT name, start_date, end_date, NVL2(end_date, 'end in two weeks', TO_CHAR(
SYSDATE, 'DD-Mon-YYYY')) as nvl2
FROM f_promotional_menus;

2. Not all Global Fast Foods staff members receive overtime pay. Instead of displaying a null value
for these employees, replace null with zero. Include the employee’s last name and overtime rate
in the output. Label the overtime rate as “Overtime Status”.
SELECT last_name, NVL(overtime_rate,0) as "Overtime Status"
FROM f_staffs;

3. The manager of Global Fast Foods has decided to give all staff who currently do not earn
overtime an overtime rate of $5.00. Construct a query that displays the last names and the
overtime rate for each staff member, substituting $5.00 for each null overtime value.
SELECT last_name, TO_CHAR( NVL(overtime_rate,5), '$999.99') as "Overtime Status"
FROM f_staffs;

4. Not all Global Fast Foods staff members have a manager. Create a query that displays the
employee last name and 9999 in the manager ID column for these employees
SELECT last_name, NVL(manager_id,9999) as manager_id
FROM f_staffs;

5. Which statement(s) below will return null if the value of v_sal is 50?
a. SELECT nvl(v_sal, 50) FROM emp;
b. SELECT nvl2(v_sal, 50) FROM emp;
c. SELECT nullif(v_sal, 50) FROM emp;
d. SELECT coalesce (v_sal, Null, 50) FROM emp;
c. SELECT nullif(v_sal, 50) FROM emp;

6. What does this query on the Global Fast Foods table return?
SELECT COALESCE(last_name, to_char(manager_id)) as NAME
FROM f_staffs;
Since last_name is not nullable, it will always return last_name. If last_name would have
been nullable and there had been a null last_name field, it would have fall back to
manager_id converted to varchar2.
Karena last_name tidak nullable, itu akan selalu mengembalikan last_name. Jika last_name
akan bisa ditukar dan ada bidang last_name null, itu akan jatuh kembali ke manager_id
dikonversi ke varchar2.

7.
a. Create a report listing the first and last names and month of hire for all employees in the
EMPLOYEES table (use TO_CHAR to convert hire_date to display the month).
SELECT NVL(first_name,'FNU') , last_name, TO_CHAR(hire_date, 'Month') as "month
of hire"
FROM employees;
First name is nullable, so print first name unknown (FNU in short)

b. Modify the report to display null if the month of hire is September. Use the NULLIF function.
SELECT NVL(first_name,'FNU') , last_name, NULLIF( TO_CHAR(hire_date, 'Month'),
'September') as "month of hire"
FROM employees;

8. For all null values in the specialty column in the DJs on Demand d_partners table, substi-tute
“No Specialty.” Show the first name and s

SELECT first_name, NVL(specialty, 'No Specialty') as specialty

FROM d_partners;
PRACTICE 5.3

5-3: Conditional Expressions


Practice Activities
Vocabulary
Identify the vocabulary word for each definition below.
 Compares an expression to each of the search values “DECODE “
 An if-then-else expression whose value depends on the truth-value of a Boolean expression.
“conditional expression “
 Implements conditional processing within a SQL statement; it “CASE “
 meets the ANSI standard. “ “

Try It / Solve It
1. From the DJs on Demand d_songs table, create a query that replaces the 2-minute songs with
“shortest” and the 10-minute songs with “longest”. Label the output column “Play Times”.
SELECT title,
CASE
WHEN TO_NUMBER(REPLACE(NVL(duration,'0 min'), ' min', '')) = 2 THEN 'Shortest'
WHEN TO_NUMBER(REPLACE(NVL(duration,'0 min'), ' min', '')) = 10 THEN 'Longest'
ELSE NVL(duration,'0 min')
END
as "Play Times"
FROM d_songs;

2. Use the Oracle database employees table and CASE expression to decode the depart-ment id.
Display the department id, last name, salary, and a column called “New Salary” whose value is
based on the following conditions:
If the department id is 10 then 1.25 * salary
If the department id is 90 then 1.5 * salary
If the department id is 130 then 1.75 * salary
Otherwise, display the old salary.
SELECT NVL(TO_CHAR(department_id), 'none') department_id , last_name,
NVL(salary,0) salary,
CASE department_id
WHEN 10 THEN 1.25*NVL(salary,0)
WHEN 90 THEN 1.5*NVL(salary,0)
WHEN 130 THEN 1.75*NVL(salary,0)
ELSE NVL(salary,0)
END
as "New Salary"
FROM employees;
3. Display the first name, last name, manager ID, and commission percentage of all employ-ees in
departments 80 and 90. In a 5 th column called “Review”, again display the manager ID. If they
don’t have a manager, display the commission percentage. If they don’t have a commission,
display 99999.
SELECT first_name, last_name, manager_id, commission_pct,
CASE
WHEN commission_pct IS NULL and manager_id IS NULL THEN 99999
WHEN manager_id IS NULL THEN commission_pct
ELSE manager_id
END
as "Review"
FROM employees
WHERE department_id in (80, 90);

OR
SELECT first_name, last_name, manager_id, commission_pct,
COALESCE(manager_id,commission_pct ,99999)
as "Review"
FROM employees
WHERE department_id in (80, 90);
PRACTICE 6.1

Practice Activities
CROSS JOIN Returns the Cartesian product from two tables.
NATURAL JOIN Joins two tables based on the same column name.

1. Create a cross-join that displays the last name and department name from the employees and
departments tables.
JAWAB :
SELECT last_name, first_name, department_name
FROM employees CROSS JOIN departments;

2. What is the result of the query that you have used for question 1?
JAWAB :
160 rows, with all possible combinations of employee being part of all departments.

3. Create a query that uses a natural join to join the departments table and the locations table by
the location_id column. Display the department id, department name, location id, and city.
JAWAB :
SELECT department_id,department_name, location_id, city
FROM departments NATURAL JOIN locations;

4. Rewrite problem 2 using equijoin syntax.


JAWAB :
SELECT department_id,department_name, location_id, city
FROM departments, locations
WHERE departments.location_id = locations.location_id;
Or
SELECT department_id,department_name, location_id, city
FROM departments JOIN locations ON departments.location_id =
locations.location_id;
Or
SELECT department_id,department_name, location_id, city
FROM departments INNER JOIN locations ON departments.location_id =
locations.location_id;

5. Create a query that uses a natural join to join the departments table by the location_id column.
Restrict the output to only department IDs of 20 and 50. Display the department id, department
name, location id, and city.
JAWAB :
SELECT department_id,department_name, location_id, city
FROM departments NATURAL JOIN locations
WHERE department_id in (20, 50);
6. Use an equijoin between the two DJs on Demand database tables: d_songs and d_types.
Display the type code, description, and title. Limit the rows returned to those type codes
between 70 and 80.
JAWAB :
SELECT d_songs.type_code, d_songs.title, d_types.description
FROM d_songs INNER JOIN d_types ON d_songs.type_code = d_types.code
WHERE d_songs.type_code BETWEEN 70 AND 80;

7. When creating a join, the join condition is always placed in the _______________ clause of the
SELECT statement.
JAWAB :
ON clause
WHERE clause

See Topic 4 above for example of on and where


8. A/an _______________ can be used to preface the column name in order to clarify which table
and column are participating in the join. - Table name itself or the alias
JAWAB :
SELECT sng.type_code, sng.title, typ.description
FROM d_songs sng INNER JOIN d_types typ ON sng.type_code = typ.code
WHERE sng.type_code BETWEEN 70 AND 80;
Or
SELECT d_songs.type_code, d_songs.title, d_types.description
FROM d_songs INNER JOIN d_types ON d_songs.type_code = d_types.code
WHERE d_songs.type_code BETWEEN 70 AND 80;

9. Table aliases are created in the ________________ clause of the SELECT statement.
JAWAB :
– AS (it is optional though)
PRACTICE 6.2

Practice Activities

ON clause Allows a natural join based on an arbitrary


condition or two columns with different names.
USING clause Performs an equijoin based on one specified
column name

1. Join the Oracle database locations and departments table using the location_id column. Limit the
results to location 1400 only.
JAWAB :
SELECT department_id,department_name, location_id, city
FROM departments JOIN locations USING (location_id)
WHERE location_id = 1400;

2. Join DJs on Demand d_play_list_items, d_track_listings, and d_cds tables with the JOIN USING
syntax. Include the song ID, CD number, title, and comments in the output.
JAWAB :
SELECT song_id, cd_number, title, comment
FROM d_cds JOIN d_track_listings USING (cd_number) JOIN d_play_list_items
USING (song_id);

3. Display the city, department name, location ID, and department ID for departments 10, 20, and 30
for the city of Seattle.
JAWAB :
SELECT city, department_name, location_id, department_id
FROM departments JOIN locations USING (location_id)
WHERE department_id in (10, 20 , 30) AND city = 'Seattle';
OR
SELECT loc.city, dp.department_name, dp.location_id, dp.department_id
FROM departments dp INNER JOIN locations loc ON dp.location_id = loc.location_id
WHERE dp.department_id in (10, 20 , 30) AND loc.city = 'Seattle';

4. Display country name, region ID, and region name for Americas.
JAWAB :
SELECT country_name, region_id, region_name
FROM countries JOIN regions USING(region_id)
WHERE region_name = 'Americas';
OR
SELECT ct.country_name, rg.region_id, rg.region_name
FROM countries ct INNER JOIN regions rg ON ct.region_id = rg.region_id
WHERE rg.region_name = 'Americas';
5. Write a statement joining the employees and jobs tables. Display the first and last names, hire
date, job id, job title, and maximum salary. Limit the query to those employees who are in jobs that
can earn more than $12,000.
JAWAB :
SELECT first_name, last_name, hire_date, job_id, job_title, max_salary
FROM employees JOIN jobs USING (job_id)
WHERE max_salary > 12000;
OR
SELECT emp.first_name, emp.last_name, emp.hire_date, emp.job_id, jb.job_title,
jb.max_salary
FROM employees emp INNER JOIN jobs jb ON emp.job_id = jb.job_id
WHERE jb.max_salary > 12000;

6. Display job title, employee first name, last name, and email for all employees who are stock clerks.
JAWAB :
SELECT job_title, first_name, last_name, LOWER(email) ||
'somecomname.sometld' as email
FROM employees JOIN jobs USING(job_id)
WHERE job_title = 'Stock Clerk' ;
OR
SELECT jb.job_title, emp.first_name, emp.last_name, LOWER(emp.email) ||
'somecomname.sometld' as email
FROM employees emp INNER JOIN jobs jb ON emp.job_id = jb.job_id
WHERE jb.job_title = 'Stock Clerk' ;

The following questions use the JOIN…ON syntax:


7. Write a statement that displays the employee ID, first name, last name, manager ID, manager first
name, and manager last name for every employee in the employees table. Hint: this is a self-join.
JAWAB :
SELECT emp.employee_id AS "employee ID", emp.first_name AS "first name",
emp.last_name "last name", emp.manager_id "manager ID", mgr.first_name
"manager first name", mgr.last_name "manager last name"
FROM employees emp LEFT JOIN employees mgr ON emp.manager_id =
mgr.employee_id;

8. Use JOIN ON syntax to query and display the location ID, city, and department name for all
Canadian locations.
JAWAB :
SELECT dp.location_id, loc.city, dp.department_name
FROM departments dp INNER JOIN locations loc ON dp.location_id =
loc.location_id INNER JOIN countries ct ON loc.country_id = ct.country_id
WHERE ct.country_name = 'Canada';

9. Query and display manager ID, department ID, department name, first name, and last name for all
employees in departments 80, 90, 110, and 190.
JAWAB :
SELECT emp.manager_id "Employee's Manager ID", emp.department_id
"Department ID", dpt.department_name "Department Name", emp.first_name "First
Name", emp.last_name "Last Name"
FROM employees emp INNER JOIN departments dpt ON emp.department_id =
dpt.department_id
WHERE emp.department_id in (80, 90, 110, 190);

10. Display employee ID, last name, department ID, department name, and hire date for those
employees whose hire date was June 7, 1994.
JAWAB :
SELECT emp.Employee_id "Employee ID", emp.last_name "Last Name" ,
emp.department_id "Department ID", dpt.department_name "Department Name",
emp.hire_date "Hire Date"
FROM employees emp LEFT JOIN departments dpt ON emp.department_id =
dpt.department_id

WHERE emp.hire_date = TO_DATE('June 7, 1994', 'fmMonth DD, YYYY');


PRACTICE 6.3

Practice Activities
FULL OUTER JOIN Performs a join on two tables, retrieves all the
rows in the Left table, even if there is no match in
the Right table. It also retrieves all the rows in the
Right table, even if there is no match in the Left
table.
Outer join A join that returns the unmatched rows as well as
matched rows
LEFT OUTER JOIN Performs a join on two tables, retrieves all the
rows in the Left table even if there is no match in
the Right table.
RIGHT OUTER JOIN Performs a join on two tables, retrieves all the
rows in the Right table even if there is no match
in the Left table.
INNER JOIN A join of two or more tables that returns only
matched rows
1. Return the first name, last name, and department name for all employees including those
employees not assigned to a department.
JAWAB :
SELECT emp.first_name "First Name", emp.last_name "Last Name" ,
dpt.department_name "Department Name"
FROM employees emp LEFT OUTER JOIN departments dpt ON emp.department_id
= dpt.department_id;

2. Return the first name, last name, and department name for all employees including those
departments that do not have an employee assigned to them.
JAWAB :
After reading next problem, I assume, that problem, says to miss an employee, if it
doesn’t have a department assigned.

SELECT emp.first_name "First Name", emp.last_name "Last Name" ,


dpt.department_name "Department Name"
FROM employees emp RIGHT OUTER JOIN departments dpt ON
emp.department_id = dpt.department_id.
OR
SELECT emp.first_name "First Name", emp.last_name "Last Name" ,
dpt.department_name "Department Name"
FROM departments dpt LEFT OUTER JOIN employees emp ON dpt.department_id
= emp.department_id;

3. Return the first name, last name, and department name for all employees including those
departments that do not have an employee assigned to them and those employees not
assigned to a department.
JAWAB :
SELECT emp.first_name "First Name", emp.last_name "Last Name" ,
dpt.department_name "Department Name"
FROM employees emp FULL OUTER JOIN departments dpt ON emp.department_id
= dpt.department_id;

4. Create a query of the DJs on Demand database to return the first name, last name, event date,
and description of the event the client held. Include all the clients even if they have not had an
event scheduled.
JAWAB :
SELECT ct.first_name, ct.last_name, ev.event_date, ev.description
FROM d_clients ct LEFT OUTER JOIN d_events ev ON ct.client_number = ev.client_number;

5. Using the Global Fast Foods database, show the shift description and shift assignment date
even if there is no date assigned for each shift description.
JAWAB :
SELECT f_shifts.description "shift description", f_shift_assignments.shift_assign_date AS "shift
assignment date"

FROM f_shifts LEFT OUTER JOIN f_shift_assignments ON f_shifts.code =


f_shift_assignments.code;

PRACTICE 6.4

Practice Activities
self join Joins a table to itself
hierarchical query Retrieves data based on a natural hierarchical
relationship between rows in a table
LEVEL Determines the number of steps down from the
beginning row that should be returned by a
hierarchical query
START WITH Identifies the beginning row for a hierarchical
query
CONNECT BY ( PRIOR on either side of equal Specifies the relationship between parent rows
sign e.g. …PRIOR abc = xyz / abc = and child rows of a hierarchical query
PRIOR xyz)

1. Display the employee’s last name and employee number along with the manager’s last name
and manager number. Label the columns: Employee, Emp#, Manager, and Mgr#, respectively.
JAWAB :
SELECT emp.last_name "Employee", emp.employee_id "Emp#", mgr.last_name "Manager",
mgr.employee_Id "Mgr#"
FROM employees emp LEFT OUTER JOIN employees mgr ON emp.manager_id =
mgr.employee_Id;
But Reading next question suggests, problem wanted INNER JOIN instead, to demonstrate the
difference

SELECT emp.last_name "Employee", emp.employee_id "Emp#", mgr.last_name "Manager",


mgr.employee_Id "Mgr#"
FROM employees emp INNER JOIN employees mgr ON emp.manager_id =
mgr.employee_Id;

2. Modify question 1 to display all employees and their managers, even if the employee does not
have a manager. Order the list alphabetically by the last name of the employee.
JAWAB :
SELECT emp.last_name "Employee", emp.employee_id "Emp#", mgr.last_name "Manager",
mgr.employee_Id "Mgr#"
FROM employees emp LEFT OUTER JOIN employees mgr ON emp.manager_id =
mgr.employee_Id

ORDER BY "Employee";
3. Display the names and hire dates for all employees who were hired before their managers,
along with their managers’ names and hire dates. Label the columns Employee, Emp Hired,
Manager and Mgr Hired, respectively.
JAWAB :
If I want to include King who has no manager, and he is the super boss:
SELECT emp.last_name "Employee", emp.hire_date "Emp Hired", mgr.last_name
"Manager", mgr.hire_date "Mgr Hired"
FROM employees emp LEFT OUTER JOIN employees mgr ON emp.manager_id =
mgr.employee_Id
WHERE emp.hire_date < NVL( mgr.hire_date, TO_DATE('31.12.9999 23:59:59', 'dd.mm.yyyy
hh24:mi:ss'))
ORDER BY "Employee";
If I don’t care for King, which is the most, probably scenario problem refers:
SELECT emp.last_name "Employee", emp.hire_date "Emp Hired", mgr.last_name
"Manager", mgr.hire_date "Mgr Hired"
FROM employees emp LEFT OUTER JOIN employees mgr ON emp.manager_id =
mgr.employee_Id
WHERE emp.hire_date < mgr.hire_date
ORDER BY "Employee";

4. Write a report that shows the hierarchy for Lex De Haans department. Include last name,
salary, and department id in the report.
JAWAB :
SELECT last_name, salary, department_id
FROM employees
START WITH first_name = 'Lex' AND last_name = 'De Haan'
CONNECT BY PRIOR employee_id = manager_id;
5. What is wrong in the following statement?

SELECT last_name, department_id, salary


FROM employees
START WITH last_name = 'King'
CONNECT BY PRIOR manager_id = employee_id;
JAWAB :
Query in problem says go from tree leave to tree base, but King is itself the base, so the result
of query in problem is only one row, the king itself. So there, is nothing wrong as per SQL in
the query in problem, but logically thinking considering the data we have, king is the super
boss.

To support my answer, let’s study similar case:


SELECT LEVEL, last_name, department_id, salary
FROM employees
START WITH first_name = 'Lex' AND last_name = 'De Haan'
CONNECT BY PRIOR manager_id = employee_id;
Gives same result as
SELECT LEVEL, last_name, department_id, salary
FROM employees
START WITH first_name = 'Lex' AND last_name = 'De Haan'
CONNECT BY employee_id = PRIOR manager_id;

6. Create a report that shows the organization chart for the entire employee table. Write the report
so that each level will indent each employee 2 spaces. Since Oracle Application Express
cannot display the spaces in front of the column, use - (minus) instead.
JAWAB :
SELECT LPAD(last_name, LENGTH(last_name) + (LEVEL-1)*2, '-') "organization chart "
FROM employees
START WITH last_name = ( SELECT last_name from employees WHERE manager_id IS
NULL)
CONNECT BY PRIOR employee_id = manager_id;
Super boss will be at level 1, not the zero.
7. Re-write the report from 6 to exclude De Haan and all the people working for him.
JAWAB :
SELECT LPAD(last_name, LENGTH(last_name) + (LEVEL-1)*2, '-') "organization chart "
FROM employees
START WITH last_name = ( SELECT last_name from employees WHERE manager_id IS
NULL)
CONNECT BY PRIOR employee_id = manager_id AND last_name != 'De Haan';

You might also like