Oracle SQL. Revision Notes

Similar documents
Database Programming with SQL 5-1 Conversion Functions. Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Conversion Functions

GIFT Department of Computing Science. [Spring 2016] CS-217: Database Systems. Lab-3 Manual. Single Row Functions in SQL

Oracle Database SQL Basics

Database Programming with SQL

MANAGING DATA(BASES) USING SQL (NON-PROCEDURAL SQL, X401.9)

Course Outline and Objectives: Database Programming with SQL

Oracle Database 12c SQL Fundamentals

SQL. - single row functions - Database Design ( 데이터베이스설계 ) JUNG, Ki-Hyun ( 정기현 )

Topics Fundamentals of PL/SQL, Integration with PROIV SuperLayer and use within Glovia

Introduction to Computer Science and Business

Oracle Syllabus Course code-r10605 SQL

Oracle Database 11g: SQL and PL/SQL Fundamentals

Using the Set Operators. Copyright 2006, Oracle. All rights reserved.

ITEC212 Database Management Systems Laboratory 2

1 Writing Basic SQL SELECT Statements 2 Restricting and Sorting Data

Chapter-14 SQL COMMANDS

normalization are being violated o Apply the rule of Third Normal Form to resolve a violation in the model

Restricting and Sorting Data. Copyright 2004, Oracle. All rights reserved.

Restricting and Sorting Data. Copyright 2004, Oracle. All rights reserved.

Oracle Database: SQL and PL/SQL Fundamentals NEW

Oracle Database: SQL and PL/SQL Fundamentals Ed 2

RESTRICTING AND SORTING DATA

TO_CHAR Function with Dates

Manipulating Data. Copyright 2004, Oracle. All rights reserved.

Relational Database Language

Braindumps.1z QA

chapter 2 G ETTING I NFORMATION FROM A TABLE

1Z Oracle Database 11g - SQL Fundamentals I Exam Summary Syllabus Questions

What are temporary tables? When are they useful?

Intermediate SQL: Aggregated Data, Joins and Set Operators

Database Foundations. 6-4 Data Manipulation Language (DML) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Oracle Database: Introduction to SQL Ed 2

Data Manipulation Language

AO3 - Version: 2. Oracle Database 11g SQL

Join, Sub queries and set operators

GIFT Department of Computing Science Data Selection and Filtering using the SELECT Statement

CS Week 10 - Page 1

Topics - System Administration for Glovia

Oracle Database 10g: Introduction to SQL

Getting Information from a Table

Oracle Database: SQL Fundamentals I. Oracle Internal & Oracle Academy Use Only. Volume II Student Guide. D64258GC10 Edition 1.0 January 2010 D65028

DB2 SQL Class Outline

RMS Report Designing

SQL is an English like language consisting of commands to store, retrieve, maintain & regulate access to your database.

Oracle Database: Introduction to SQL

Database Programming with SQL

Retrieving Data Using the SQL SELECT Statement. Copyright 2004, Oracle. All rights reserved.

Table of Contents. PDF created with FinePrint pdffactory Pro trial version

ÇALIŞMA TEST SORULARI

Oracle Database 11g: SQL Fundamentals I

COSC344 Database Theory and Applications. Lecture 5 SQL - Data Definition Language. COSC344 Lecture 5 1

Oracle Database: Introduction to SQL

Exam Questions 1Z0-051

Oracle Database 11g: SQL Fundamentals I

Retrieving Data Using the SQL SELECT Statement. Copyright 2009, Oracle. All rights reserved.

Oracle Database: Introduction to SQL

Database Foundations. 6-3 Data Definition Language (DDL) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

SELF TEST. List the Capabilities of SQL SELECT Statements

Retrieving Data from Multiple Tables

Oracle Database 11g: Introduction to SQLRelease 2

INDEX. 1 Basic SQL Statements. 2 Restricting and Sorting Data. 3 Single Row Functions. 4 Displaying data from multiple tables

UNIT III INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL)

MANAGING DATA(BASES) USING SQL (NON-PROCEDURAL SQL, X401.9)

Writing PL/SQL Executable Statements. Copyright 2007, Oracle. All rights reserved.

Using DDL Statements to Create and Manage Tables. Copyright 2006, Oracle. All rights reserved.

SQL FUNCTIONS. Prepared By:Dr. Vipul Vekariya.

Oracle Database: SQL and PL/SQL Fundamentals

COURSE STUDENT LEARNING OUTCOMES: See attached or in course s learn.unm.edu

Test: Mid Term Exam Semester 2 Part 1 Review your answers, feedback, and question scores below. An asterisk (*) indica tes a correct answer.

Táblák tartalmának módosítása. Copyright 2004, Oracle. All rights reserved.

Greenplum SQL Class Outline

COSC 304 Lab 5 Week of October 22, 2018

KORA. RDBMS Concepts II

ORACLE CERTIFIED ASSOCIATE ORACLE DATABASE 11g ADMINISTRATOR

Topic 8 Structured Query Language (SQL) : DML Part 2

Oracle SQL & PL SQL Course

SQL Functions (Single-Row, Aggregate)

5. Single-row function

SQL Structured Query Language Introduction

HR Database. Sample Output from TechWriter 2007 for Databases


Oracle Database: Introduction to SQL/PLSQL Accelerated

Additional Practice Solutions

Learn Well Technocraft

SQL Structured Query Language (1/2)

Retrieving Data Using the SQL SELECT Statement. Copyright 2004, Oracle. All rights reserved.

@vmahawar. Agenda Topics Quiz Useful Links

Oracle Database 10g: SQL Fundamentals I

The Newest Certifytools 1Z0-061 Dumps! 100% Pass Guarantee! (339 Q&As) Oracle. Exam Questions 1Z0-061

Creating and Managing Tables Schedule: Timing Topic

Introduction to SQL/PLSQL Accelerated Ed 2

ORACLE TRAINING. ORACLE Training Course syllabus ORACLE SQL ORACLE PLSQL. Oracle SQL Training Syllabus

Série n 6 Bis : Ateliers SQL Data Modeler (Oracle)

Bsc (Hons) Software Engineering. Examinations for / Semester 1. Resit Examinations for BSE/15A/FT & BSE/16A/FT

GIFT Department of Computing Science. CS-217/224: Database Systems. Lab-5 Manual. Displaying Data from Multiple Tables - SQL Joins

Lab # 4. Data Definition Language (DDL)

Oracle Database 10g: SQL Fundamentals I

Oracle Database 10g: SQL Fundamentals I

Oracle 12C DBA Online Training. Course Modules of Oracle 12C DBA Online Training: 1 Oracle Database 12c: Introduction to SQL:

Transcription:

Oracle SQL Revision Notes 1 - Oracle Server, technology and the relational paradigm. 2 - Data retrieval using the select statement. 3 - Restricting and sorting data. 4 - Single row functions. 5 - Using conversion functions and conditional expressions. 6 - Reporting aggregated data using the group function. 7 - Displaying data from multiple tables. 8 - Using sub queries to solve problems. 9 - Using the st operators. 10 - Manipulating data. 11 - Using DDL statements to create and manage tables. 12 - Creating other schema objects.

1.01 Position the server technologies. 1.02 Understand relational structures. 1.03 Summarise the SQL language. 1.04 Use the client tool. 1.05 Create the demonstration schema. 1 - Oracle server, technology and the relational paradigm. 1.01 Position the server technologies. These 4 make up the grid: Oracle Database (repository). Oracle Application Server (User Interface). Oracle Enterprise Server (Tuning). Oracle Development tool and languages. Client Tier -------------------------> Server Tier Generates SQL Executes SQL User and user process. Server process, the instance and the database. Client side components Server side components User <---> User process <-----> Server process <----> Instance ------------------------------------------------ Session components 1.02 Understand relational structures. Oracle application server develops, deploys and manages web applications. A table consists of a number of rows each consisting of a number of columns. Data normalisation - The process of modelling data into relational tables. Primary key - Unique identifier of a row. More than one is a composite key. Foreign key - Column(s) that can be used to identify a related row in another table. Primary key # Foreign key \ Mandatory column * Optional column o

Language Functions Data Manipulation Language Select - Chapters 2 to 9 Insert - All these in Chapter 10 Update Delete Merge Data Definition Language Create - All these in Chapter 11 and 12 Alter Drop Rename Truncate Comment Data Control Language Grant Revoke 2.01 List the capabilities of the select statement. 2.02 Execute a basic select statement. 2 - Data retrieval using select statement. The structure metadata of a table can be returned using the describe command. Typical Data Types. desc <schema> tablename Every schema has a spacial table called dual which belongs to the sys schema. number(8,2) A number 8 numbers long of which 2 must be to the right of the decimal places. varchar2(20) Can store up to 20 characters. char(size) Fixed length column. The data must be predictable and constant. date Moment in time including day, month, year, hours, minutes and seconds. timestamp(f) Stores the same as date but with fractional seconds. Capabilities of the select statement. Projection Selection Joining Transaction Control Language Commit - Both Chapter 10 Rollback Savepoint The restriction of columns selected from a relation or table. The restriction of rows from a table. The interaction of tables with each other in a query. Two mandatory clauses are select and from. The pipe is used to denote or. Aliases are used to display output in a user-friendly way as well as shorthand for referring to columns or expressions. The distinct keyword allows duplicate rows to be eliminated from the result set.

Expressions and Operators - precedence level. Highest 0 Medium / * Lowest - + Column Aliasing. select employee_id, job_id, start_date, end_date, (end_date - start_date) + 1 Days Employed // note use of to preserver char case from job_history; Or we can use the more formal as keyword: select employee_id as Employee ID, job_id as Description, (end_date - start_date) + 1 Days Employed from job_history; Literals and the dual table. The dual table allows literal expressions to be selected for processing and returns the result in its single row. Two single quotes or the Alternative Quote Operator. What about literals that contain single quotation marks? select Plural s have one quote too many from dual; Two mechanisms to cope, add an additional single quotation mark: select Plural s have one quote too many from dual; or use the Alternative Quote Operator (q). This enables you to choose from a set of possible pairs of wrapping symbols for character literals as alternatives to the single quote symbol. The options are any single byte. select q < Plural s can be specified with the alternative quote operators > q<> from dual;select q [ Even square brackets [] can be used for plurals] q[] from dual; Note the use of () {} or <> to signify a single quote. The character delimiter can effectively be changed from a single quotation to any other character.

Null Any arithmetic calculation with a null always returns a null. Division by null returns null, unlike division by zero which produces an error. Foreign keys and nullable columns. Data model design sometimes lead to problematic situations when tables are related to each other via a primary or secondary key relationship but the column that the foreign key is based is nullable. Departments Table Department_id (primary key - cannot be null) Employee Table Department_id (foreign key - can be null) The department_id column in the employee table is actually nullable, therefore the risk exists that there can be records with null values in this table. It is possible to miss or exclude certain records that contain nulls in the join column.

3 - Restricting and Sorting Data. 3.01 - Limit the rows returned by a query. 3.02 - Sort the rows returned by a query. 3.03 - Ampersand substitution. 3.01 - Limit the rows returned by a query. Numeric based conditions. Both of these formats are accepted since an implicit data type conversion is performed. select last_name, salary where salary = 10000; select last_name, salary where salary = 10000 ; The where clause also allows expressions either side of the comparator operator. Date Literals select last_name, salary where salary / 10 department_id * 10; Date literals must be enclosed in single quotation marks. The literals are automatically converted into date values based on the default format: DD-MON-RR. DD Days MON First three letters of the month. RR Year. If RR is between 50 and 99 then returns the previous century else the current century. The full four-digit year YYYY can also be specified. Examples: This only works if day, month, year, minutes and seconds are all the same. select employee_id from job_history where start_date = end_date;

Four digit year is fine: select employee_id from job_history where start_date = 01-JAN-2001 ; Two digit is fine: select employee_id from job_history where start_date = 01-JAN-01 ; Arithmetic in dates. Only values with a date of 01-Jan-1999 in the start-date column will be retrieved. select employee_id from job_history where start_date + 30 = 01-JAN-99 ; Comparison Operators. Equality Inequality between in is null Equality with Dates. = < > <= >= = less than greater than equal to Tests whether a column value lies between two values. Tests set membership. Returns rows where the column value contains a null. select employee_id from job_history where start_date = 01-JAN-2001 ; select employee_id from job_history where start_date < 01-JAN-2001 ; The between operator. Retrieves each employee containing a hire_date earlier than 01-jan-2000. select last_name where salary between 3400 and 4000; select last_name, hire_date where hire_date between 24-JUL-1994 and 07-JUN-1996 ;

Set comparison with the in operator. select last_name where salary in (1000, 4000, 6000); Pattern comparison with the like operator. % Specifies zero or more wildcard character. - Specifies one wildcard character. Every row containing a first_name value that is not null will be returned. select first_name where first_name like % ; The following two statements are equivalent. where first_name like King ; where first_name = King ; The underscore symbol substitutes one character. where first_name like K_ing ; / / This would return King, Kong etc. The escape identifier instructs the server to treat any character found after the backslash as a regular non-special symbol with no wildcard meaning. select job_id from jobs where job_id like SA\_% escape \ ; This example uses the dollar symbol as the escape character instead: select job_id from jobs where job_id like SA$_% escape $ ; Any job_id vales that begins with the three characters SA_ will be returned. Null comparison with the is null operator. select last_name where commission_pct is null;

Boolean operators. and, or, not select first_name, last_name, commission_pct, hire_date where first_name like J% and commission_pct > 0.1; or commission _pct > 0.1 select first_name, last_name, commission_pct, hire_date where first_name not like J% or not (commission_pct > 0.1); order by clause. select last_name, hire_date, salary where job_id in ( sa_rep, mk_man ) order by last_name; Ascending and descending order. select last_name, salary, commission_pct where job_id in ( sa_map, mk_man ) order by commission_pct desc; select last_name, salary, commission_pct where job_id in ( sa_map, mk_man ) order by commission_pct desc nulls last; Positional Sorting select last_name, hire_date, salary where job_id in ( sa_man, mk_man ); order by 2;

Composite Sorting select last_name, hire_date, salary where job_id in ( sa_man, mk_man ); order by job_id desc, last_name, 2 desc; Sort in reverse alphabetical order by job_id then by ascending order by last_name and finally by numerically descending order based on salary. Substituting Variables Single Ampersand Substitution. Regard them as placeholders. You insert values into the variables. The oracle server produces the statement then notices the substitution variable and attempts to resolve the variable in one of two ways: 1 - Checks the variable is defined in the user session - using the define command. 2 - The user is prompted for a value that will be used in place of the variable. select employee_id, last_name, phone_number where last_name = &lastname or employee_id = &empno; If the variable is meant to substitute a character or date value then the literal needs to be enclosed in single quotes. A useful technique is to enclose the ampersand substitution variable in single quotes when dealing with character and date values. In this way the user is required to submit a literal value without worrying about enclosing it in quotes. select employee_id, last_name, phone_number where last_name = &lastname or employee_id = &empno; Double Ampersand Substitution select first_name, last_name where last_name like %&&search% // prompt here and first_name like %&search%; // no prompt here - value above automatically // inserted here

The Define and Undefine Commands select last_name, &&colname where department_id = 20 order by &colname The first time you run this you are prompted to input a value for colname. We assume you enter a salary and the value is substituted. A subsequent execution of this statement does not prompt for another value as salary is already defined in the context of this session and can only be undefined with the undefine command. sql>undefine colname; The define command serves two purposes. It can retrieve a list of all the variables currently defined in your session. It can explicitly define a value for a variable referenced as a substitute variable. sql>define variable=value; You can switch off session-persistent variables using the set command. sql>set define off The set define on/off command therefore determines whether or not ampersand substitution is available in your life. The Verify Command. Controls whether the substitution variable is displayed onscreen so you can verify the correct substitution has occurred. set verify on/off

4 - Single Rows Functions. SQL functions are divided into those that calculate and return a value for every row in a data set and those that return a single aggregated value for all the rows. Defining a function. A sql function is a program written to optionally accept input parameters, perform an operation and return a single result. A function returns only one value per execution. Three parts: 1 - Input parameter list. 2 - Data type of of its resultant value. 3 - Details of the processing. Operating on character data. Functions that operate on character data are broadly classified as case conversion and character manipulation functions. Function Description lower( SQL ) = sql upper( sql ) = SQL initcap( sql ) = Sql length(string) length( A short string ) = 14 concat(string1, string2) concat( SQL is, easy to learn ) = SQL is easy to learn substr(string, start position, number of characters) substr( http://www.domain.com,12,6) = domain instr(source string, search item, start position, nth occurrence of item) instr( http://www.domain.com,.,1,2) = 18 Start at position 1 and look for 2nd occurrence of. Change all to lower case. Change all to upper case. Initialize the first letter. Use a character string and returns the numeric length. Takes two strings and joins them the same way as operator. Accepts three parameters and returns a string consisting of the number of characters extracted at the beginning of the specified start position. Returns a number that represents the position in the source string beginning from the start position where the nth occurrence occurs. lpad(string, length after padding, padding string) or rpad(string, length after padding, padding string) rpad( #PASSWORD#,11, # ) = #PASSWORD# trim( # from #PASSWORD# ) = PASSWORD replace(string, search item, replacement item) replace( #PASSWORD#, WORD, PORT ) = #PASSPORT# Adds padding to a string to the left or right until it reaches the specified length. Trims off leading and/or trailing. Locates the search item in a given string and replaces it with the replaceable item, returning a string with replacement values.

Operating on Numeric Functions. Function Description round(number, decimal precision) round(42.39, 1) = 42 Rounds off a number to the lowest or highest value given a decimal precision. If the number is >= 5 then round up otherwise round down. trunc(42.39, 1) = 42.3 mod(33, 10) = 3 Drops off a number given a decimal precision value. Does not attempt to round up or down. The remainder of a division. Operating on date information. Function Description months_between(date1, date2) months_between( 01-feb-2008, 01-jan-2008 ) add_months(date1, number of months) add_months( 01-jan-2008,1) = 01-feb-2008 last_day(date1) last_day( 01-feb-2008 ) = 29-feb-2008 next_day(date1, day of the week) next_day( 01-feb-2008, Friday ) = 08-feb-2008 sysdate round(date, date precision) trunc(date, date precision) sysdate = 17-dec-2007 round(sysdate, month ) = 01-jan-2008 trunc(sysdate, month ) = 01-dec-2007 Returns the number of months between 2 dates. Add a specified number of months to a date. Last day of month. Returns the date on which the next specified day of the week falls after the given date. Returns the date that represents the current servers date and time. Round and truncate a given date value value to the nearest date precision format like day, month or year.

Single Row Functions. We focus on the char, numeric and date single-row functions. They operate on one row at a time. If a query selects 10 rows then the function executes 10 times. select region_id, region_name, length(region_name) from regions. The length of the region_name is calculated for each row proving that the function has executed at least 4 times. General Functions. They simplify working with nulls and facilitate logic within a select statement. These include nvl1, nvl2, nullif, coalesce, case and decode functions. Multiple Row Functions Operate on more than one row at a time. Including sum or average of numeric columns or counting the total number of records in a set.

to_char to_number to_date 5 - Using conversion functions and conditional expressions. Converts numeric and date info into chars. Converts character data into numbers. Converts characters into dates. Both number and date info can be stored in a varchar2 field. If a function that accepts a char input field finds a number instead then it automatically converts it into a char. Implicit data type conversions. select length(1234567890) from dual; Converts ok. Changes to 01234567890. select length(sysdate) from dual; Converts ok. Changes to 08-apr-38. The length function and date info can be stored in a varchar2 field. If a function that accepts a char input field finds a number instead then it automatically converts it into a char. Implicit data type conversion. select length(1234567890) from dual; Converts ok. Changes to 01234567890. select length(sysdate) from dual; Converts ok. Changes to 08-apr-83. The length function takes a string. These examples are implicitly converted to a a char. In these examples mod takes a numeric. Char string 11 will convert to a number but 11.123.456 will not be. select mod( 11, 2) from dual; Implicitly converted to 11. select mod( 11.123, 2) from dual; Implicitly converted to 11.123 select mod( 11.123.456, 2) from dual; select mod( $11, 2) from dual; Implicit char to date conversion. Invalid number error. Invalid number error. Are possible when the char string conforms to D DD MON MONTH R RR YY YYYY D and DD represent a single and two digit day of the month. MON is a 2 char abbreviation. MONTH is the full name. R and RR represent a single and two digit year. YY and YYYY represent a 2 and 4 digit year.

The separators may be most punctuation marks, spaces and tabs. Function Call Format Results add_month( 24-JAN-09,1) DD-MON-RR 24/FEB/09 add_month( 1/january/8, 1) d/month/r 01/FEB/08 months_between( 13 jan 8, 13/feb/2008 ) DD MON R DD/MON/YYYY -1 Explicit Data Type Conversion. to_char, to_number and to_date. Single row explicit data type conversions. add_months( 01$jan/08, 1) DD$MON$RR 01/FEB/08 add_months( 12 jaba08, 1) to_number(char1, [format-mask], [nls_parameters]) = num1 to_char(num1, [format-mask], [nls_parameters]) = char1 to_date(char1, [format-mask], [nls_parameters]) = date1 Number to Char using to_char The optional national language support parameters (nls) are useful for specifying the language and format and are not usually used. select to_char(00001) is a special number from dual; 1 is a special number (Note that it removes the leading zeros before turning it into a char) select to_char(00001, 0999999 ) is a special number from dual; 0000001 is a special number (Note the mask used forces the number format) jaba is an invalid month.

Format Element Element Description Format Number Character Result 9 Numeric width 9999 12 12 0 Displays leading zeros. Position of decimal point 9999 12 12 9999.999 30.4 30.4 D Decimal separator position (period is default) 09999D999 3040 30.4, Position of comma separator 9999.999 3040 0003,040 G Group separator position (comma is default) 09999G999 3040 3.04 $ Dollar sign $99999 3040 $3040 L Local currency L099999 3040 GBP03040 id nls_currency is set to GBP. MI PR Position of minus sign for negatives Wrap negatives in parenthesis 99999MI -3040 3040-99999PR -3040 <3040> EEEE Scientific notation 99.99999EEEE 121.976 1.22E+02 U nls_dual_currency U099999 3040 CAD003040 if nls_dual_currency is set to CAD (Canadian Dollar) V S Multiplies by 10n times (n is the number of nines after V) + or - sign is prefixed 9999V99 3040 30400 S999999 3040 +3040

Dates to char using to_char. to_char(date1, [format-mask], [pls_parameters]); Format Element Description Result Y Last digit of year 5 YY Last two digits of year 75 YYY Last three digits of year 975 YYYY Four digit year 1975 RR Two digit year 75 YEAR Case sensitive spelling of year Nineteen seventy five MM Two digit month 6 MON Three letter abbreviation of month JUN select to_char(sysdate) is todays date from dual; 03/jan/09 is todays date select to_char(sysdate, MONTH )) is a special time from dual; MONTH Case sensitive spelling of month June D Day of the week 2 DD Two digit day of the week 2 DDD Day of the year 153 DY Three letter abbreviation of day MON DAY Case sensitive spelling of day Monday January is a special date

Format Element Description Result W Week of month 4 WW Week of year 39 Q Quarter of year 3 CC Century 10 S proceeding CC, YYYY or YEAR IYYYY, IYYY, IY I ISO If date is BC then minus prefixed to result. Dates of four, three, two and one digit -10, -1000 or -ONE THOUSAND 1000, 000,00,0 BC AD B.C A.D BC and AD or B.C. or A.D. BC J Julian day - days since 31 December 4713 BC. 1356075 RM Roman numerical month IX Time Components. IW ISO standard week (1 to 53) 39 Assume these tables use: 27-JUN-2001 21:35:13 Format Element Description Result AM PM A.M P.M Meridian indicators PM HH HH12 HH24 Hour of day 1-12 and 0-23 09, 21 MI Minute 0-59 35 SS Second 0-59 13 SSSSS Seconds past midnight 0-86399 77713 Misc Data Format Masks. Format Element Description and Format Masks Result - /.,? # Punctuation marks MM. YY 09.08 any char literal Week W of MONTH Week 2 of September TH SP Position of ordinal text: DDth of MONTH Spelled out positional of ordinal number dd24spth 12th of September Fourteenth

Select 'Employee' EMPLOYEE_ID ' quit as ' JOB_ID ' on ' TO_CHARR(END_DATE, 'fmday the ddth of Month YYYY') Quitting Date from job_history order by end_date; Employee 200 quit as AD_ASST on Thursday the 17 th of June 1993 Note the fmday function trims any spaces that trail shorter days or months. Chars to Dates - Using to_date. to_date(string1, [format], [nls_parameters]); select to_date('25-dec-2010') from dual; 25-DEC-2010 time set to midnight. select to_date('25-dec') from dual; Error input was not long enough. select to_date('25-dec','dd-mon') from dual; 25-DEC-09 year taken from sysdate and time set to midnight. select to_date('25-dec-2010' 18:03:45','DD-MON-YYYY HH24:MI:SS') from dual; Complete conversion. select to_date('25-dec-10','fxdd--mon-yyyy') from dual; The fx operator means it must be an exact match with the format. There is an error here with the year. Select first_name, last_name, hire_date where hire_date > to_date('01/12/2000','mm/dd/yyyy') order by hire_date; Chars to numbers - using to_number. to_number(string1, [format], [nis_parameter]) select to-number('$1,000.55') from dual; Invalid number due to $ select to-number('$1,000.55','$999,999.99') from dual; 1000.55

NVL General Functions. Evaluates whether a column or expression of any date type is null or not. If it is null then an alternative non-null value is returned. nvl(original, ifnull); select nvl(1234) from dual; Invalid number of args error. select nvl(null, 1234) from dual; 1234 Tests if the null keyword is null then returns 1234. select nvl(substr('abc', 4, 'No substring exists') from dual; No substring exists. The substring attempts to extract the fourth character which is null. NVL2 Evaluates whether a column or expression of any data type is null or not. If not null then the second param is returned else the third param is returned. nvl2(original, ifnotnull, ifnull) select nvl2(1234, 1, a string') from dual; Invalid number error due to number and string incompatibility. select nvl2(null, 1234, 5678') from dual; 5678 select nvl2(substr('abc',2),'not bc','no substring') from dual; Not bc The datatype of the ifnotnull and ifnull must be compatible and they cannot be a long. select last_name, salary, commission_pct, nvl2(commission_pct, 'Commission Earner', 'Not a commission earner') Employee_Type where last_name like 'G%'; last_name salary commission_pct Employee_type Gates 2900 null Not a commission earner Gee 2400 0.15 Commission Earner

NULLIF nullif(ifunequal, comparison_term) Tests two terms for equality, if they are equal then it returns a null else it returns the first term. select nullif(1234, 1234) from dual; // null select nullif(1234, 123+1) from dual; // produces 1234 123+1 is not evaluated. select nullif('24-jul-2009','24-jul-09') from dual; // strings of different length COALESCE Returns the first non-null value from a parameter list. If all its params are null then null is returned. Select coalesce(null, null, null, 'a string') from dual; // a string Select coalesce(null, null, null) from dual; // null Select coalesce(substr('abc',4),'not bc','no substring') from dual; Conditional Functions. DECODE // Not bc Implements if-then-else logic by testing the first two terms for equality and returns the third if they are equal and optionally returns another term if they are not. decode(expre1, comp1, iftrue1, icomp2, iftrue2 [iffalse]_ if expr1 = comp1 then return iftrue1 else if expr1 = comp2 then return iftrue2 else return null iffalse; select decode(1234, 123, '123 is a match') from dual; 1234 is compared to 123 and since they are not equal the first result cannot be returned. select decode(1234, 123, '123 is a match','no match') from dual; 1234 is compared to 123 and the iffalse is returned 'No match'.

CASE Two variants. The simple case lists the conditional search item once and equality is tested by each comparison operator. The searched case expression lists a separate condition for each comparison expression. Case search_expr when comparison_expr1 then iftrue1 when comparison_expr2 then iftrue2 else iffalse end; The search, comparison and result params can be column values, expressions or literals but must be the same type. Select case substr(1234,1,3) when '134' then '134 is a match' when '1235' then '1235 is a match' when concat('1', '23') then 'concat('1','23' is a match' else 'no match' end from dual; This searches for 123 the third when produces 123 so '123 is a match' is returned. Joins. Inner Left Outer Right Outer Full Outer Restaurants All matched rows returned. All rows from left, any matches from right, else null. All rows from right, any matches from left, else null. All rows from both with or without matches. Regions ID Name RegionID RegionID Description 1 Home cooking <null> 1 East 2 Grandpas 3 2 North 3 Hoops 1 3 West 4 Burger Bam 1 4 South Left outer join. All rows from left, any matches from right, else null. Right outer join. All rows from right, any matches from left, else null.

Name Region Description Name Region Description Home Cooking <null> Hoops East Grandpas West Burger Bam East Hoops East <null> North Burger Bam East Grandpas West <null> South Inner join. All matched rows returned. Name Region Description Grandpas West Hoops East Burger Bam East Employees Orders Employee_ID Name Prod_id Product Employee_ID 01 Hansen, Ola 234 Printer 01 02 Svenson, Tove 657 Table 03 03 Svenson, Stephen 865 Chair 03 04 Patterson, Karl Inner Join All rows where there is a match. select employees.name, orders.product Name Product.name Hansen, Ola Printer inner join Employees.Employee_id = orders.employee_id Svenson, Stephen Table Svenson, Stephen Chair Left outer join (Returns all rows from the left table (employees) even if there are no matches in the right table (orders). select employees.name, orders.product Name Product left Hansen, Ola Printer left join orders right Svensen, Tove <null> on employee.employee_id = orders.employee_id Svensen, Stephen Table Svensen, Stephen Chair Patterson, Karl <null>

Right outer join (Returns all rows from the right table (orders) even if there are no matches in the left table (employees). select employees.name, orders.product Name Product left Hansen, Ola Printer right join orders right Svensen, Stephen Table on employee.employee_id = orders.employee_id Svensen, Stephen Chair

Oracle SQL Joins. Equi-join Non-equijoin Self-join Outer-join cross join or cartesian Natural Joins. A row associated with one or more rows in another table based on the equality of column value or expressions. A row associated with one or more rows in another table if its column values fall into a range determined by inequality operators. Associate rows with other rows in the same table. Rows with null or differing entries in common join columns are excluded when equi-joins and non equi-joins are performed. An outer join is available to fetch these one-legged or orphaned rows if necessary. Formed when every row from one table is joined to all rows in another. Implemented using three possible join clauses that use the keywords natural, join, using and join on. When the source and target tables share identically named columns it is possible to perform a natural join between them without specifying a join column. Columns with the same names in the source and target tables are automatically associated with each other. Rows with matching columns in both tables are retrieved. Countries table contains three columns, country_id, country_name and region_id. Regions table contain two columns region_id and region_name. select region_name from regions natural join countries where country_name = Canada ; select region_name from regions join countries using <region_id> where country_name = Canada ; select country_name from countries join regions on <country.region_id = regions.region_id> Outer Joins. where region_name = Americas ; // natural join // join using // join on - most widely used. It is occasionally required that rows with non-sharing join column values also be retrieved. Suppose the employees and departments are joined with common department_id values. Employees records with null department_id values are excluded along with values absent from the departments table. An outer join will fetch these rows.

Left Outer Join. Any rows from the table on the left of the join keyword excluded for not fulfilling the join condition are also returned. select e.employee_id, e.department_id, d.department_id, d.department_name from departments d left outer join employee e on (d.department_id = e.department_id) where d.department_name like P% ; Right Outer Join. Any employee records which do not conform to the join condition are included, provided they conform to the where clause condition. select e.last_name, d.department_name from departments d right outer join employee e on (e.department_id = d.department_id) where e.department_name like G% ; Full Outer Join. Returns the combined results of a left and right outer join. select e.last_name, d.department_name from departments d full outer join employee e on (e.department_id = d.department_id) where e.department_id is null; Cross Join or Cartesian. Creates one row of output for every combination of source and target table rows. If the source and target tables have 3 and 4 tables respectively, a cross join results in 12 rows being returned. select * from jobs cross join job_history; Takes 19 rows and 4 columns from the jobs table and the 10 rows and 5 columns from the job_history table and generates one large set of 190 records with 9 columns.