Saturday, October 15, 2016

16 Join Clauses


  • ·         Allows a natural join based on an arbitrary condition or two columns with different names.-ON Clause
  • ·         Performs an equijoin based on one specified column name-USING clause

Use the Oracle database for problems 1-6.
1.  Join the Oracle database locations and departments table using the location_id column. Limit the results to location 1400 only.
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.
SELECT song_id, cd_number, title, comments

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.
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.
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.
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.
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.
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.
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.

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.
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');

15 Cross Joins and Natural Joins

  • ·         Returns the Cartesian product from two tables. –CROSS JOIN
  • ·         Joins two tables based on the same column name.-NATURAL JOIN

Use the Oracle database for problems 1-4.
1.  Create a cross-join that displays the last name and department name from the employees and departments tables.
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?
160 rows, with all possible combinations of employee being part of all departments.
https://drive.google.com/open?id=0B6dqipWMkn9XRlB1bE1BdEZ6OG8
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.
SELECT department_id,department_name, location_id, city
FROM departments NATURAL JOIN locations;
4.  Rewrite problem 2 using equijoin syntax.
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.
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.
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.
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
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.

 – AS (it is optional though)

14 Conditional Expressions


  • ·         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 meets the ANSI standard.-CASE


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 employees table and CASE expression to decode the department 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 employees in departments 80 and 90. In a 5th 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);

13 NULL Functions


  • ·         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


Use aliases to make the output more readable.

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

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.
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, substitute “No Specialty.” Show the first name and specialty.

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

FROM d_partners;

12 Date / Conversion Functions


  • ·         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 optional formatting.-TO_DATE 


In each of the following exercises, feel free to use labels for the converted column to make the output more readable.

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
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

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.

11 Date Functions


  • ·         A function that returns the current date and time of the database server.-SYSDATE
  • ·         Add calendar months to date- ADD_MONTHS
  • ·         Last day of the month- LAST_DAY
  • ·         Next day of the date specified- NEXT_DAY
  • ·         Number of months between due dates- MONTHS_BETWEEN


1.  For DJs on Demand, display the number of months between the event_date of the Vigil wedding and today’s date. Round to the nearest month.
SELECT name, event_date, ROUND(MONTHS_BETWEEN(SYSDATE, event_date)) as "number of months"
FROM d_events
WHERE name = 'Vigil wedding';
2.  Display the days between the start of last summer’s school vacation break and the day school started this year. Assume 30.5 days per month. Name the output “Days.”
SELECT TO_DATE('20-Sep-2016', 'dd-Mon-yyyy') - TO_DATE('05-Jun-2016', 'dd-Mon-yyyy') as "Actual Days", ROUND( MONTHS_BETWEEN(TO_DATE('20-Sep-2016', 'dd-Mon-yyyy'), TO_DATE('05-Jun-2016', 'dd-Mon-yyyy'))*30.5, 0) as "Days"
FROM dual;

3.  Display the days between January 1 and December 31. 
SELECT TO_DATE('31-Dec-2016', 'dd-Mon-yyyy') - TO_DATE('01-Jan-2016', 'dd-Mon-yyyy') as "Actual Days"
FROM dual;
4.  Using one statement, round today's date to the nearest month and nearest year, and truncate it to the nearest month and nearest year. Use an alias for each column.
SELECT ROUND(SYSDATE, 'Month') as "nearest first day of month", ROUND(SYSDATE, 'Year') as "nearest first day of Year", TRUNC(SYSDATE, 'Month') as "current month's 1st day", TRUNC(SYSDATE, 'Year') as "current year's 1st day"
FROM dual;
5.  What is the last day of the month for June 2005? Use an alias for the output.
SELECT LAST_DAY(To_date('01-Jun-2005', 'dd-Mon-yyyy'))
FROM dual;
6.  Display the number of years between the Global Fast Foods employee Bob Miller’s birth-day and today. Round to the nearest year.
SELECT first_name, last_name , ROUND(MONTHS_BETWEEN(SYSDATE, birthdate)/12) "No of Years"
FROM f_staffs
WHERE first_name || ' ' || last_name = 'Bob Miller';
7.  Your next appointment with the dentist is six months from today. On what day will you go to the dentist? Name the output, “Appointment.”
SELECT TO_CHAR(ADD_MONTHS(SYSDATE, 6),'dd-Mon-yyyy (DY)') as "Appointment"
FROM dual;
8.  The teacher said you have until the last day of this month to turn in your research paper. What day will this be? Name the output, “Deadline.”
SELECT TO_CHAR(LAST_DAY(SYSDATE),'dd-Mon-yyyy (Day)') as "Deadline"
FROM dual;
9.  How many months between your birthday this year and January 1 next year?
SELECT  TO_DATE('11/05/2016','mm/dd/yyyy') "B'Day current year", ADD_MONTHS(TO_DATE('11/05/2016','mm/dd/yyyy'),12)   "B'Day next year", TRUNC( ADD_MONTHS(TO_DATE('11/05/2016','mm/dd/yyyy'),12), 'Year') "1st day next Year"  , ROUND(MONTHS_BETWEEN( TRUNC( ADD_MONTHS(TO_DATE('11/05/2016','mm/dd/yyyy'),12), 'Year')    ,  TO_DATE('11/05/2016','mm/dd/yyyy'))) "Rounded Months to next 1st jan"
FROM dual;
10. What’s the date of the next Friday after your birthday this year? Name the output, “First Friday.”
SELECT  TO_DATE('11/05/2016','mm/dd/yyyy') "B'Day current year", NEXT_DAY(TO_DATE('11/05/2016','mm/dd/yyyy'), 'Friday') "First Friday"
FROM dual;

11. Name a date function that will return a number.
MONTHS_BETWEEN
12. Name a date function that will return a date.
ADD_MONTHS
13. Give one example of why it is important for businesses to be able to manipulate date data?
Say, my credit card payment is due on 09th every month. But if 09th is on weekend or bank holiday, this due date has to be shifted to next Monday while triggering late payment workflow. This is a very common and nearest to me example of why business needs to manipulate date data.

1. Using DUAL, write a statement that will convert 86.678 to 86.68.
SELECT  ROUND(86.678, 2)
FROM dual;
2.  Write a statement that will display the DJs on Demand CD titles for cd_numbers 90 and 91 in uppercase in a column headed “DJs on Demand Collections.”
SELECT  UPPER(title) "DJs on Demand Collections"
FROM d_cds
WHERE cd_number IN( 90, 91);
3.  Write a statement that will create computer usernames for the DJs on Demand partners. The usernames will be the lowercase letters of the last name + the uppercase first letter in the first name. Title the column “User Passwords.” For example, Mary Smythers would be smythersM.
SELECT LOWER(last_name) || UPPER(SUBSTR(first_name, 1,1) ) "User Passwords"
FROM d_partners;
4.  Write a statement that will convert “It’s a small world” to “HELLO WORLD.”
SELECT UPPER(REPLACE( 'It''s a small world' , 'It''s a small', 'hello' )) as converted
FROM dual;
5.  Write a statement that will remove the “fiddle” from “fiddledeedee” and the “dum” from “fiddledeedum.” Display the result “fiddledeedeedee” in a column with the heading “Non-sense.”
SELECT    REPLACE('fiddledeedum', 'dum') ||  REPLACE('fiddledeedee', 'fiddle') "Non-sense"
FROM dual;
6.  Replace every “i” in Mississippi with “$.”
SELECT    REPLACE('Mississippi ', 'i', '$') "Converted"
FROM dual;
7.  Using DUAL, convert 5332.342 to 5300.
SELECT    TRUNC(5332.342, -2) as "Truncated", ROUND(5332.342, -2) as "Rounded"
FROM dual;
Both will work here. But if input would have been 5362.342, trunc only had given desired output.
8.  Using DUAL, convert 3.14159 to 3.14.
SELECT    TRUNC(3.14159 , 2) as "Truncated", ROUND(3.14159 , 2) as "Rounded"
FROM dual;
Both will work here too.
9.  Using DUAL, convert 73.892 to 73.8.
SELECT    TRUNC(73.892  , 1) as "Truncated", ROUND(73.892  , 1) as "Rounded"
FROM dual;
Note: Here only trunc works. Round gives 73.9
10. What is the next Friday six months from now? Label the column “Future.”
SELECT TO_CHAR(  NEXT_DAY( ADD_MONTHS(SYSDATE,6), 'Friday'), 'dd-Mon-yyyy (Day)') "Future"
FROM dual;
11. What is the date 10 years from now? Label the column “Future.”
SELECT TO_CHAR(ADD_MONTHS(SYSDATE, 10*12), 'dd-Mon-yyyy (Day)') "Future"
FROM dual;
12. Leap years occur every four years. Remember, 2004 was a leap year. Now create a function that will show the date of the next leap year as 29-Feb-2008. Label the column “Future.”
SELECT TO_CHAR( LAST_DAY( To_Date('01-Feb-2008', 'dd-Mon-yyyy')  )        , 'dd-Mon-yyyy (Day)') "Future"
FROM dual;
13. Write a statement that will find any of the DJs on Demand CD themes that have an “ie” in their names.
SELECT description
FROM d_themes
WHERE description like '%ie%';
14. Write a statement that will return only the DJs on Demand CDs with years greater than 2000 but less than 2003. Display both the title and year.
SELECT title, year
FROM d_cds
WHERE year > 2000 AND year < 2003;
15. Write a statement that will return the employer database employee’s employee ID and his starting hire dates between January 1, 1997 and today. Display the result ordered from most recently hired to the oldest.
SELECT employee_id, hire_date
FROM employees
WHERE hire_date BETWEEN  TO_DATE( '01-Jan-1997', 'dd-Mon-yyyy') AND SYSDATE

ORDER BY hire_date DESC;

10 Number Functions


  • ·         Used to terminate the column, expression, or value to a specified number of decimal places-TRUNC
  • ·         These functions accept numeric input and return numeric values.-number functions
  • ·         Returns the remainder of a division.-MOD
  • ·         Rounds the column, expression, or value to a set number of decimal places.-ROUND

1.  Display Oracle database employee last_name and salary for employee_ids between 100 and 102. Include a third column that divides each salary by 1.55 and rounds the result to two decimal places.
SELECT last_name, salary, ROUND(salary/1.55,2) "Calculated Salary"
FROM employees
WHERE employee_id BETWEEN 100 AND 102;
2.  Display employee last_name and salary for those employees who work in department 80. Give each of them a raise of 5.33% and truncate the result to two decimal places.
SELECT last_name, salary, TRUNC(salary*1.0533,2) "Raised Salary"
FROM employees
WHERE department_id = 80;
3. Use a MOD number function to determine whether 38873 is an even number or an odd number.
SELECT CASE WHEN MOD(38873 , 2) = 1 THEN 'odd' ELSE 'even' END as "Odd or Even?"
FROM dual; 
4.  Use the DUAL table to process the following numbers:
845.553 - round to one decimal place
845.6
SELECT ROUND( 845.553 , 1)
FROM dual;
30695.348 - round to two decimal places
30695.35
SELECT ROUND( 30695.348  , 2)
FROM dual;

30695.348 - round to -2 decimal places
30700  :  one added to 9 at highlighted position
SELECT ROUND( 30695.348  , -2)
FROM dual;
2.3454 - truncate the 454 from the decimal place
2.3
SELECT TRUNC( 2.3454   , 1)
FROM dual;

5.  Divide each employee’s salary by 3. Display only those employees’ last names and salaries who earn a salary that is a multiple of 3.
SELECT last_name, salary
FROM employees
WHERE MOD(salary, 3) = 0;
6.  Divide 34 by 8. Show only the remainder of the division. Name the output as EXAMPLE.
SELECT MOD(34, 8) as example
FROM dual;
7.  How would you like your paycheck – rounded or truncated? What if your paycheck was calculated to be $565.784 for the week, but you noticed that it was issued for $565.78. The loss of .004 cent would probably make very little difference to you. However, what if this was done to one thousand people, one hundred thousand people, or one million people! Would it make a difference then? How much of a difference?
1K: $4 , 100K : $400,  1000K (1 million) :  $4000
SELECT (565.784 - ROUND(565.784, 2))*1000*(:xx) as diff

FROM dual;