Complete IT Professional http://www.completeitprofessional.com Helping Software Developers Get Ahead In Their Careers Sat, 23 May 2015 23:52:49 +0000 en-US hourly 1 http://wordpress.org/?v=4.2.2 Oracle SUBSTR Function Explained with Exampleshttp://www.completeitprofessional.com/oracle-substr/ http://www.completeitprofessional.com/oracle-substr/#comments Sat, 23 May 2015 23:47:09 +0000 http://www.completeitprofessional.com/?p=3252 ]]> Oracle SUBSTR Function Explained with ExamplesThe Oracle SUBSTR function is used to get a smaller string (the substring) from within a larger string. Let’s take a look at how you can use it and some examples.

Purpose of the Oracle SUBSTR Function

This Oracle SUBSTR function allows you to extract a smaller string from within a larger string. The smaller string is called the substring, which is where the name of the SUBSTR function comes from (SUBSTRing)

Why is this useful?

It’s one of the many string manipulation functions in Oracle, and it’s a common feature of many programming languages. It’s good for splitting data and getting the part you need from a longer string.

 

SUBSTR Syntax

The syntax of the SUBSTR function is:

SUBSTR (string, start_position, [length] )

I’ll explain what each of these parameters mean below.

Also, this function is different from other functions in that it has several versions that can be run, depending on the way that the length is calculated:

  • SUBSTR calculates the length using characters defined by the input character set.
  • SUBSTRB calculates the length using bytes.
  • SUBSTRC calculates the length using Unicode complete characters.
  • SUBSTR2 calculates the lengths using USC2 code points.
  • SUBSTR4 calculates the lengths using USC4 code points.

The INSTR function also has similar variations.

 

SUBSTR Parameters

The parameters of the SUBSTR function are:

  • string (mandatory): This is the base string value that the substring is obtained from.
  • start_position (mandatory): This is the starting position of the substring within the string. It’s where the substring starts from. The first position is always 1.
  • length (optional): This is the number of characters to extract from string, to create the substring. If it is not specified, the function returns the entire string.

As mentioned, the start_position starts at 1. There are a couple of variations that can be used for this parameter:

  • If start_position is 0, it is treated as 1
  • If start_position is positive (greater than 0), the function counts the position from the beginning of the string to find the starting character
  • if start_position is negative (less than 0), the function counts the position from the end of the string, and goes backwards, to find the starting character

Also, for the length parameter, it should be a number greater than or equal to 1. If you specify a value less than 1, the function returns NA.

 

How Can I Use Oracle SUBSTR To Remove the Last Character?

The best way to use Oracle SUBSTR to remove last character is using a combination of SUBSTR and LENGTH.

The LENGTH function can be used to determine the length parameter of the function. Remember, functions can contain other functions as parameters.

This function would be:

SUBSTR ( string, 0, LENGTH( string) - n)

In this case, n can be set to 1 as you want to remove the last character. It can be set to another value if you want more characters removed.

For example, to remove the last character from the name of this site, “Complete IT Professional”, the function would be:

SUBSTR ("Complete IT Professional", 0, LENGTH("Complete IT Professional") - 1)

This would return:

“Complete IT Professiona”

See the Examples section below for more examples.

 

How Can Oracle SUBSTR and INSTR Be Used Together?

The SUBSTR and INSTR functions can be used together to get a specific string up until the occurrence of another character or string. This is good for when you need to extract part of a string in a column, but the length is varied.

You would use the INSTR function as the length parameter:

SUBSTR (string, 1, INSTR(string, substring, 1, 1))

Also, you can use it as part of the start_position parameter if you want to start from the occurrence of a specific character. For example, if names are stored as “lastname, firstname”, you can use this method to extract the firstname from the value.

SUBSTR (string, INSTR(string, substring, 1, 1))

See the Examples section below for more examples.

 

How Can I Use Oracle SUBSTR In Reverse, or SUBSTR From The Right?

To use SUBSTR in reverse, otherwise known as using SUBTSR from the right, simple specify a negative number as the start_position.

To start immediately from the right, use the value of -1.

To start a specific number of characters from the right, use a lower value (e.g. -5 for the fifth character).

This will start counting backwards from the right of the string.

 

Can I Use Oracle SUBSTR with CLOB?

You can use this function with CLOB and NCLOB data types. However, Oracle has an inbuilt package, called DBMS_LOB, which is better at handling these data types, which they recommend using.

DBMS_LOB.SUBSTR performs similar functionality for CLOBs and LOBs.

 

Can I Use Oracle SUBSTR with a LONG?

No, unfortunately you can’t perform this function on a LONG.

According to Oracle, from version 8.0 you should be using the CLOB data type instead.

The only way that I know of to get a SUBSTR from a LONG variable is to write a PL/SQL procedure that takes a ROWID, then converts that to a 32k variable, and returns 4000 characters to SQL, which can then be used for the SUBSTR function.

This is described in more detail here.

 

SUBSTR Data Types

The string parameter can be any of the following data types:

  • CHAR
  • VARCHAR2
  • NCHAR
  • NVARCHAR2
  • CLOB
  • NCLOB

Both start_position and length need to be a NUMBER datatype, or a datatype that can be implicitly converted to a NUMBER and must resolve to an integer. This means it can be a different data type but needs to be a whole number.

The return value of the Oracle SUBSTR function is always the same data type as the one provided for string. So, if STRING is a VARCHAR2, the function returns VARCHAR2.

 

Examples of the SUBSTR Function

Here are some examples of the Oracle SUBSTR function. I find that examples are the best way for me to learn about code, even with the explanation above.

These strings can be shown along with their positions:

123456789101112131415161718192021222324
CompleteITProfessional

 

Example 1:

This is an example using both parameters for the SUBSTR.

SELECT 'Complete IT Professional',
 SUBSTR('Complete IT Professional', 1, 10) AS SUB
 FROM DUAL;

Result:

‘COMPLETEITPROFESSIONAL’SUB
Complete IT ProfessionalComplete I

This shows the first 10 characters from the string.

 

Example 2:

This example only uses the start_position parameter, and not the length.

SELECT 'Complete IT Professional',
 SUBSTR('Complete IT Professional', 5) AS SUB
 FROM DUAL;

Result:

‘COMPLETEITPROFESSIONAL’SUB
Complete IT Professionallete IT Professional

This shows the string starting at position 5.

 

Example 3:

This example shows the last character of the string.

SELECT 'Complete IT Professional',
 SUBSTR('Complete IT Professional', -1, 5) AS SUB
 FROM DUAL;

Result:

‘COMPLETEITPROFESSIONAL’SUB
Complete IT Professionall

As the start_position is -1, it starts at the first character before the end of the string. Because the length is greater than 1, it returns the whole substring.

 

Example 4:

This example shows the last 5 characters of the string.

SELECT 'Complete IT Professional',
 SUBSTR('Complete IT Professional', -5, 5) AS SUB
 FROM DUAL;

Result:

‘COMPLETEITPROFESSIONAL’SUB
Complete IT Professionalional

Because start position is -5, it starts at the 5th character from the right of the string.

 

Example 5:

This example shows how both SUBSTR and INSTR can be used together.

SELECT 'Complete IT Professional',
 SUBSTR('Complete IT Professional',
 INSTR('Complete IT Professional', ' ', 1, 1)) AS SUB
 FROM DUAL;

Result:

‘COMPLETEITPROFESSIONAL’SUB
Complete IT Professional IT Professional

This shows the value of the string starting from the first space character.

 

Example 6:

This example uses the INSTR as a length parameter.

SELECT 'Complete IT Professional',
 SUBSTR('Complete IT Professional', 1,
 INSTR('Complete IT Professional', ' ', 1, 1)) AS SUB
 FROM DUAL;

Result:

‘COMPLETEITPROFESSIONAL’SUB
Complete IT ProfessionalComplete

This shows the string up until the first space character. It’s good for finding the first word in a string.

 

Example 7:

This example shows how to find the middle of a string using a space character and INSTR.

SELECT 'Complete IT Professional',
 SUBSTR('Complete IT Professional',
 INSTR('Complete IT Professional', ' ', 1, 1)+1,
 INSTR('Complete IT Professional', ' ', 1, 2)-INSTR('Complete IT Professional', ' ', 1, 1)-1) AS SUB
 FROM DUAL;

Result:

‘COMPLETEITPROFESSIONAL’SUB
Complete IT ProfessionalIT

It’s a bit more complicated, but the INSTR is used to find the first space, and then find the second space, and return the string in between using SUBSTR.

 

Example 8:

This example shows how to remove the last character using SUBSTR.

SELECT 'Complete IT Professional',
 SUBSTR('Complete IT Professional', 0,
 LENGTH('Complete IT Professional') - 1) AS SUB
 FROM DUAL;

Result:

‘COMPLETEITPROFESSIONAL’SUB
Complete IT ProfessionalComplete IT Professiona

The last character has been removed from the string.

 

Example 9:

This example shows how you can remove more than the last character (in this case, remove the last 5 characters).

SELECT 'Complete IT Professional',
 SUBSTR('Complete IT Professional', 0,
 LENGTH('Complete IT Professional') - 5) AS SUB
 FROM DUAL;

Result:

‘COMPLETEITPROFESSIONAL’SUB
Complete IT ProfessionalComplete IT Profess

This string has had the last 5 characters removed from it.

 

Similar Functions

Some functions which are similar to the SUBSTR function are:

  • REGEXP_SUBSTR – Similar to the SUBSTR function, but allows for regular expressions.
  • INSTR – Allows you to search for a string within another string.
  • LENGTH – Returns the length of the provided string.
  • REPLACE – Replaces one string with another string in the provided value.

 

Lastly, if you enjoy the information and career advice I’ve been providing, sign up to my newsletter below to stay up-to-date on my articles. You’ll also receive a fantastic bonus. Thanks!

Image courtesy of digitalart / FreeDigitalPhotos.net

]]>
http://www.completeitprofessional.com/oracle-substr/feed/ 0
Oracle NVL2 Function Explained with Exampleshttp://www.completeitprofessional.com/oracle-nvl2/ http://www.completeitprofessional.com/oracle-nvl2/#comments Thu, 21 May 2015 11:00:33 +0000 http://www.completeitprofessional.com/?p=3712 ]]> Oracle NVL2 FunctionThe Oracle NVL2 function is an extension of the NVL function and can be used to handle NULL values. Let’s take a  look at how it can be used as well as some examples.

Purpose of the Oracle NVL2 Function

The NVL2 function is similar to the NVL function. NVL2 allows you to specify a value to check, and then specify a value to use if it is null, as well as a value to use if it is not null.

It’s similar to NVL because NVL allows you to check a value and return something else if it is null. NVL2 has three parameters, while NVL has two.

Let’s look at how the function is made up.

 

Syntax

The syntax of the Oracle NVL2 function is:

NVL2( value_to_check, value_if_not_null, value_if_null )

Let’s see what these parameters mean.

 

Parameters

The parameters of the NVL2 function are:

  • value_to_check (mandatory): This is the value to check to see if it is NULL or not.
  • value_if_not_null (mandatory): If value_to_check is not null, then NVL2 returns this value.
  • value_if_null (mandatory): If value_to_check is null, then NVL2 returns this value.

Some notes about this function:

  • These parameters are called different names by Oracle in their NVL2 function definition. The value_to_check is called expr1, the value_if_not_null is called expr2, and the value_if_null is called expr3.
  • The value_to_check parameter can have any data type.
  • The value_if_not_null and value_if_null can have any data type except LONG.
  • The data type of value_to_check determines the output.
  • If value_if_not_null  is a character type, then value_if_null is converted to the data type of value_if_not_null before comparing, unless value_if_null is a NULL constant.
  • If value_if_not_null  is numeric, then Oracle determines the type with the higher precedence.

 

Oracle NVL2, NVL, CASE, DECODE, or COALESCE?

Why would you use NVL2 instead of NVL, CASE, DECODE, or COALESCE?

Well, there seems to be a lot of functions that you can use to get the same result.

  • NVL – Checks one value and returns it, if it is null, return another value
  • NVL2 – Checks one value, if it is null, return a different value, if it is not null, return another different value
  • CASE – Allows for IF-THEN-ELSE statements in SQL
  • DECODE – Allows for IF-THEN-ELSE statements in SQL.
  • COALESCE – Returns the first non-null expression in your list

So, it depends on what you need the function for.

In my article on the Oracle DECODE function, I recommend that you use CASE instead of DECODE for several reasons.

If you need just a simple NULL comparison to show a different value, use NVL.

NVL2 is an Oracle-only function, so this is something you may want to keep in mind.

COALESCE is a standard SQL function, and also has a bit more functionality.

So, your choice will depend on what you need the function for and how much you need it to do.

For NVL2 vs CASE, I would use NVL2 only if I was checking for NULL. If it was something more complicated, I would use CASE.

For NVL2 vs DECODE, I would also use NVL2 only if I was checking for NULL, as with CASE. I would also use CASE instead of DECODE if possible.

 

Examples of the Oracle NVL2 Function

Here are some examples of the Oracle NVL2 function to help explain how to use the NVL2 function in Oracle SQL. I find that examples are the best way for me to learn about code, even with the explanation above.

Example 1

This example shows the basic usage of the NVL2 function.

SELECT first_name,
NVL2(first_name, first_name, 'No name provided') AS First_Name_Check
FROM customers;

Result:

FIRST_NAMEFIRST_NAME_CHECK
JohnJohn
SallySally
SteveSteve
MarkMark
AdamAdam
JoshJosh
PeterPeter
(null)No name provided

All of the records have the first_name showing, except for the last record, where it has been replaced with the specified value.

 

Example 2

This example shows a similar example, but we’ve specified NULL as the third parameter, to see what happens.

SELECT first_name,
NVL2(first_name, first_name, NULL) AS First_Name_Check
FROM customers;

Result:

FIRST_NAMEFIRST_NAME_CHECK
JohnJohn
SallySally
SteveSteve
MarkMark
AdamAdam
JoshJosh
PeterPeter
(null)(null)

This output shows NULL being used to replace the NULL value. No error is shown, it just doesn’t change the data.

 

Example 3

This example uses numeric data types to show the NVL2 function.

SELECT first_name, employees,
NVL2(employees, employees, 0) AS Employee_Check
FROM customers;

Result:

FIRST_NAMEEMPLOYEESEMPLOYEE_CHECK
John44
Sally1010
Steve1515
Mark2323
Adam5555
Josh11
Peter(null)0
(null)(null)0

The employee_check column shows the employees, or 0 if none are found. It works in a similar way to the character examples.

 

Example 4

This example uses NVL2 with DATE values.

SELECT first_name, start_date,
NVL2(start_date, start_date, '01-JAN-2000') AS Date_Check
FROM customers;

Result:

FIRST_NAMESTART_DATEDATE_CHECK
John12/APR/201012/APR/2010
Sally04/JUL/201104/JUL/2011
Steve21/MAR/200921/MAR/2009
Mark01/FEB/200101/FEB/2001
Adam (null)01/JAN/2000
Josh10/FEB/201210/FEB/2012
Peter16/OCT/201216/OCT/2012
  (null)16/OCT/201216/OCT/2012

It shows the date of 1 Jan 2000 if a NULL value is found.

 

 

Example 5

This example uses a mix of data types. The value_to_check is a number, and the other two parameters are strings.

SELECT first_name, employees,
NVL2(employees, 'Has some employees', 'Zero') AS Employee_Check
FROM customers;

Result:

FIRST_NAMEEMPLOYEESEMPLOYEE_CHECK
John4Has some employees
Sally10Has some employees
Steve15Has some employees
Mark23Has some employees
Adam55Has some employees
Josh1Has some employees
Peter (null)Zero
 (null) (null)Zero

The output is shown as expected. Employee_check shows two different text values, depending on the value of the employees column.

 

Similar Functions

Some functions which are similar to the NVL2 function are:

  • NVL – Checks one value and returns it, if it is null, return another value
  • CASE – Allows for IF-THEN-ELSE statements in SQL
  • DECODE – Allows for IF-THEN-ELSE statements in SQL.
  • COALESCE – Returns the first non-null expression in your list

 

Lastly, if you enjoy the information and career advice I’ve been providing, sign up to my newsletter below to stay up-to-date on my articles. You’ll also receive a fantastic bonus. Thanks!

]]>
http://www.completeitprofessional.com/oracle-nvl2/feed/ 0
Book Review: Clean Code: A Handbook of Agile Software Craftsmanshiphttp://www.completeitprofessional.com/book-review-clean-code-a-handbook-of-agile-software-craftsmanship/ http://www.completeitprofessional.com/book-review-clean-code-a-handbook-of-agile-software-craftsmanship/#comments Mon, 18 May 2015 11:00:21 +0000 http://www.completeitprofessional.com/?p=3677 ]]> Book Review Clean CodeI recently read the book “Clean Code: A Handbook of Agile Software Craftsmanship” by Robert C Martin. In this article, I write my review of this book and what I thought of it.

Why I Read This Book

I’ve been reading a lot of books lately on my commute to work, and one of the books I recently read was this one.

Why did I decide to read this book?

Well, it started with me reading John Sonmez’s list of books every software developer must read. On this list was Clean Code, and he says “I can neatly divide my programming career into pre-Code Complete, pre-Clean Code and after.”

It’s also written by Robert Martin, aka Uncle Bob, who is one of the most well-known software developers in the industry.

So, I thought it was a good idea to read it.

Also, I haven’t read a software development book for a while, so I thought I’d start with this one.

I had this book an eBook format as I much prefer to read it electronically.

 

First Impressions

My first impressions from reading this book were that it seemed pretty comprehensive and straight to the point.

Just reading the contents page shows how much material has gone into the book. It doesn’t just cover how to structure functions or effective commenting, it covers much more than that. I knew that by reading this book I should get quite a bit of value form it.

I also noticed from reading it that the author doesn’t mess around. There is no fluff like I’ve seen in other books I’ve read.

He starts with explaining the structure of the book, and the benefits of reading all of the sections.

He then goes into detail about the benefits of clean code and what it actually is.

After that, he discusses the strategies and definitions of clean code and how you can transform your code. He uses examples from code he has written, publicly available code, and other examples.

The examples are easy to follow if you’ve done Java programming, which I have. While the examples are in Java, he mentions that the concepts should apply to any programming language, and I think it does.

So, what did I think as I was reading the book, and after I read it?

 

Thinking About The Code I’ve Written In The Past

The main thought that occurred to me for a good part of the book was, “Wow, I’ve actually written some pretty bad cod ein my time!”

As I was reading through his tips and strategies for improving your code, I realised that my recent devleopment projects adhered to about 60%-70% of them. There were many that I did not follow. This was because:

  • I knew what I was doing may not have been the best, but did not know there was a better way
  • I did not take the time to improve it
  • I thought what I was doing was the right way

For example, Robert really highlights the importance of choosing valuable names for your functions, variables, and classes. I knew the basics, such as give them meaningful names and don’t use single-letter variables.

However, taking the time to name your variables right is one of the best things you can do for your code, as it helps you in the future, as well as any other developer that looks at your code.

It’s also different to what I was taught in university. This is understanding, thought. In uni they taught us the fundamentals of writing code and computer science, such as how object oriented design works, how to write programs in Java and to get them to compile. All of the information on best practices that is mentioned in the book is based off many years of experience, which really shows.

 

My Current Employer

Another thing I thought when I read the book was that the developers that I currently work with would really benefit from reading this book.

I work for a consulting company and there are a lot of developers that work with us. I might recommend this book to them. They would most likely benefit from this book, no matter what language they develop in.

Then, I wondered about the systems at my current workplace and how hard it is to get things changed. I mean, I understand the process and the release cycles, but I wonder if the “unclean” code is a factor in this? And how much it could be improved if the code was cleaned up?

 

The End Result – “Clean Code” Review

The book taught me a lot of ways I can improve my code. I don’t write a lot of code in my current role, but if I ever go back, there will be an improvement in how I write code.

It also gave me motivation to do some programming of my own. Perhaps start a side project. Just to see if I can put these tips into action and see the benefits of writing quality code. It would make a great enhancement to my Github profile and for any future jobs I want to go for.

So, what would I rate this book?

It’s the first book review I’ve done on this site, and I thought it was a great book. The code samples were good, the concepts made sense, and even the references between the code samples and supporting material were clear.

I give it five stars. I’ve also left an Amazon review on the book as well.

If you’re interested in reading the book, you can get it at Amazon:

Clean Code: A Handbook of Agile Software Craftsmanship

Note: this is an affiliate link, which means I get a small commission from the sale at no extra cost to you. And while it’s my first review and I did give it five stars, I think it’s because it’s such a good book. Not every book will get five stars of course!

Readers, what do you think? Have you read this book? If so, what did you think, and how did it change the way you code? If not, do you have any desire to read it?

Lastly, if you enjoy the information and career advice I’ve been providing, sign up to my newsletter below to stay up-to-date on my articles. You’ll also receive a fantastic bonus. Thanks!

]]>
http://www.completeitprofessional.com/book-review-clean-code-a-handbook-of-agile-software-craftsmanship/feed/ 2
Oracle LISTAGG Function with Exampleshttp://www.completeitprofessional.com/oracle-listagg/ http://www.completeitprofessional.com/oracle-listagg/#comments Thu, 14 May 2015 11:00:07 +0000 http://www.completeitprofessional.com/?p=3520 ]]> Oracle LISTAGG Function with ExamplesThis article explains the Oracle LISTAGG functions, which is one of the more difficult functions to understand.

Purpose of the Oracle LISTAGG Function

The purpose of the Oracle LISTAGG function is to allow you to perform aggregation of strings from data in columns.

What is string aggregation? Well, it’s a technique similar to concatenation, but it allows you to aggregate data in a GROUP BY, combining strings that have matches in a value in another column.

It’s a new function in Oracle 11g R2, so you may not have heard of it if you’re using an older version. Actually, you might not have heard of it even if you’re using 11g R2!

This function might be easier to explain with an example.

Let’s use our sample data set that we’ve using in our other Oracle SQL function articles.

SELECT country, last_name
FROM customers;
COUNTRYLAST_NAME
USASmith
USAJones
CanadaBrown
UKAllan
USACooper
(null)Thompson
FranceManson
(null)(null)

Using a LISTAGG function, we could have an output like this:

COUNTRYLISTAGG_OUTPUT
CanadaBrown
FranceManson
UKAllan
USACooper, Jones, Smith
(null)Thompson

As you can see, the last_name values have been concatenated together and split by a comma, which are grouped by each different value of country.

Let’s learn how we can use this function to get this result.

 

LISTAGG Syntax

The LISTAGG syntax is:

LISTAGG( measure_expr [, delimiter]) WITHIN GROUP (order_by_clause) [OVER query_partition_clause]

Let’s have a look at the parameters of this function in more detail.

 

LISTAGG Parameters

There are several mandatory and optional parameters in the LISTAGG function. The parameters of the LISTAGG function are:

  • measure_expr (mandatory): This is the column (or expression) that you wish to concatenate the values of. In the example above, I used last_name.
  • delimiter (optional): This is the delimiter, or the character in between each value of measure_expr. If this is not specified, no value is used.
  • order_by_clause (mandatory): This is the order of the concatenated values in measure_expr are listed.
  • query_partition_clause (optional): This allows you to use LISTAGG as an analytic function, which we will see in the examples section below.

 

Usage of the LISTAGG Function

There are a few ways you can use this function.

If you use it without any grouping, LISTAGG operates on all rows and returns a single row.

If you use it with grouping, LISTAGG operates on and returns a row for each group defined by the GROUP BY clause.

If you use it as an analytic function, LISTAGG partitions the query result set into groups, based on one or more expressions in the query_partition_clause.

We can see how this works in the examples below.

 

Can You Run Oracle LISTAGG With DISTINCT Results?

Yes, you can run a query using LISTAGG and eliminate duplicates from the output of the LISTAGG function.

The way to do this is to SELECT from a subquery which already removes the duplicates, and do your LISTAGG on that.

SELECT LISTAGG(column1, ',') WITHIN GROUP (ORDER BY column2) as listagg_output
FROM (
  SELECT DISTINCT column1, column2
  FROM test_table
);

There is a more advanced version, which has been documented on Stack Overflow here, which can be used for more columns.

SELECT col1, LISTAGG(col2, ',') WITHIN GROUP (ORDER BY col2)
FROM (
  SELECT  col1,
  col2,
  row_number() OVER(PARTITION BY col1, col2 ORDER BY col1) as rn
  FROM test_table
  ORDER BY col1 ,col2
)
WHERE rn = 1
GROUP BY col1;

Just substitute your tables and columns into this query as needed.

 

What Is The Oracle LISTAGG LIMIT?

The limit of the output of the Oracle LISTAGG function is 4000 bytes. Any more than this and you’ll receive an Oracle error.

You can build a custom function to get the output of LISTAGG from multiple rows and combine them into a CLOB value if that’s what you really need, but that’s outside the scope of this article.

 

Is There An Oracle LISTAGG Alternative?

Yes, there are a couple of alternatives

The first is the WM_CONCAT built-in function. This is not supported by Oracle any more and is not documented, so I suggest avoiding it.

Alternatively, you can create a generic user-defined aggregate function, that does the work for you, in PL/SQL. This has been detailed in an AskTom article here.

You can also write a specific user-defined function for your purpose. If you’re only doing it for one query or one section of your application, you can write a specific function which gets you the result you need, and isn’t used by other areas.

 

Does Oracle LISTAGG Work on Multiple Columns?

Do you want to be able to use multiple columns inside your LISTAGG function and output those as values?

Well, you can do that using LISTAGG.

You’ll just need to concatenate them inside the LISTAGG function. You can use either the CONCAT function or the doubple pipe character (||). As I mentioned in the article on CONCAT, both of these methods have the same performance.

 

Examples of the Oracle LISTAGG Function

Here are some examples of the LISTAGG function. I find that examples are the best way for me to learn about code, even with the explanation above.

Before we see some examples, let’s look at the sample data that we’ll use. This will make it easier to explain the examples.

SELECT * FROM customers;

 

FIRST_NAMELAST_NAMECOUNTRYFULL_ADDRESSEMPLOYEESSTART_DATE
JohnSmithUSA10 Long Road412/04/2010
SallyJonesUSA50 Market Street1004/07/2011
SteveBrownCanada201 Flinders Lane1521/03/2009
MarkAllanUK8 Smith Street2301/02/2001
AdamCooperUSA14 Wellington Road55(null)
JoshThompson(null)80 Victoria Street110/02/2012
PeterMansonFrance5 Johnson St(null)16/10/2012
(null)(null)(null)155 Long Road(null)16/10/2012

Example 1

This example uses LISTAGG to aggregate all values in the table

SELECT LISTAGG(last_name, ',') WITHIN GROUP (ORDER BY last_name) as LISTAGG_OUTPUT
FROM customers;

Result:

LISTAGG_OUTPUT
Allan,Brown,Cooper,Jones,Manson,Smith,Thompson

It shows all values of last_name in the table, separated by a single comma character.

 

Example 2

This example shows you how to use LISTAGG on a subset of records using the WHERE clause.

SELECT LISTAGG(last_name, ',') WITHIN GROUP (ORDER BY last_name) as LISTAGG_OUTPUT
FROM customers
WHERE country = 'USA';
LISTAGG_OUTPUT
Cooper,Jones,Smith

As you can see, it shows a single row, but only those last_names where the country is USA.

 

Example 3

This example uses LISTAGG to aggregate the last_name values for each country.

Because LISTAGG is an aggregate function, any other columns listed here need to have a GROUP BY. It can also use the PARTITION BY, but we’ll cover that later.

SELECT country, LISTAGG(last_name, ',') WITHIN GROUP (ORDER BY last_name) as LISTAGG_OUTPUT
FROM customers
GROUP BY country;

 

COUNTRYLISTAGG_OUTPUT
CanadaBrown
FranceManson
UKAllan
USACooper,Jones,Smith
(null)Thompson

Each country is listed, along with the last_name only for the records that match the country.

 

Example 4

This example shows what happens if we don’t specify the ORDER BY.

SELECT country, LISTAGG(last_name, ',') WITHIN GROUP (last_name) as LISTAGG_OUTPUT
FROM customers
GROUP BY country;

Result:

ORA-30491: missing ORDER BY clause
30491. 00000 -  "missing ORDER BY clause"

You’ll get this error if you leave out the words ORDER BY, or the entire clause that’s inside the brackets.

 

Example 5

This example shows what happens using the default delimiter, using the example above for each country.

SELECT country, LISTAGG(last_name) WITHIN GROUP (ORDER BY last_name) as LISTAGG_OUTPUT
FROM customers
GROUP BY country;

Result:

COUNTRYLISTAGG_OUTPUT
CanadaBrown
FranceManson
UKAllan
USACooperJonesSmith
(null)Thompson

The result is the same, but the data is not separated by a comma. The default delimiter is nothing, so there is nothing in between each value.

 

Example 6

This is the same query as above, but using two characters as a delimiter.

SELECT country, LISTAGG(last_name, ', ') WITHIN GROUP (ORDER BY last_name) as LISTAGG_OUTPUT
FROM customers
GROUP BY country;
COUNTRYLISTAGG_OUTPUT
CanadaBrown
FranceManson
UKAllan
USACooper, Jones, Smith
(null)Thompson

This result is a little more readable, as we have a comma and a space in between the values.

 

Example 7

This example shows how the PARTITION BY is used. I’ve added a few extra columns to make more sense of it.

SELECT first_name, last_name, country,
LISTAGG(last_name, ',') WITHIN GROUP (ORDER BY last_name) OVER (PARTITION BY country) as LISTAGG_OUTPUT
FROM customers;
FIRST_NAMELAST_NAMECOUNTRYLISTAGG_OUTPUT
SteveBrownCanadaBrown
PeterMansonFranceManson
MarkAllanUKAllan
AdamCooperUSACooper,Jones,Smith
SallyJonesUSACooper,Jones,Smith
JohnSmithUSACooper,Jones,Smith
JoshThompson(null)Thompson
(null)(null)(null)Thompson

Each row from the customers table is shown. For each row, we have the LISTAGG function, which shows an aggregation of last_name values.

Notice how we did not use a GROUP BY. The GROUP BY is not needed if you use the OVER PARTITION BY clause.

The PARTITION BY clause tells you how the values inside the LISTAGG are split. You can see that the last_name values that are shown are those for the country, and in the case of records with a country of USA, they are repeated.

 

Example 8

This example is the same as above, but the PARTITION BY clause is on the last_name field.

SELECT first_name, last_name, country,
LISTAGG(last_name, ',') WITHIN GROUP (ORDER BY last_name) OVER (PARTITION BY last_name) as LISTAGG_OUTPUT
FROM customers
FIRST_NAMELAST_NAMECOUNTRYLISTAGG_OUTPUT
MarkAllanUKAllan
SteveBrownCanadaBrown
AdamCooperUSACooper
SallyJonesUSAJones
PeterMansonFranceManson
JohnSmithUSASmith
JoshThompson(null)Thompson
(null)(null)(null)(null)

As you can see, the LISTAGG function doesn’t really do much. This is because it’s partitioned on the same value that is being aggregated.

 

Example 9

What if we didn’t want a partition and wanted to show the other data as well?

SELECT first_name, last_name, country,
LISTAGG(last_name, ',') WITHIN GROUP (ORDER BY last_name) as LISTAGG_OUTPUT
FROM customers

Result:

ORA-00937: not a single-group group function
00937. 00000 -  "not a single-group group function"

Oracle treats this as using an aggregate function, and as a result, you need to use a GROUP BY.

 

Similar Functions

There aren’t really any functions which are similar to the LISTAGG function. However, one that I mentioned was:

  • CONCAT – Allows string values to be joined or concatenated together.

 

 

Lastly, if you enjoy the information and career advice I’ve been providing, sign up to my newsletter below to stay up-to-date on my articles. You’ll also receive a fantastic bonus. Thanks!

Image courtesy of David Castillo Dominici / FreeDigitalPhotos.net

]]>
http://www.completeitprofessional.com/oracle-listagg/feed/ 0
3 Interview Questions Most People Are Not Prepared Forhttp://www.completeitprofessional.com/3-interview-questions-most-people-are-not-prepared-for/ http://www.completeitprofessional.com/3-interview-questions-most-people-are-not-prepared-for/#comments Mon, 11 May 2015 11:00:23 +0000 http://www.completeitprofessional.com/?p=3505 ]]> 3 Interview Questions Most People Are Not Prepared ForEveryone knows about the common and much feared interview question that probes you for your greatest weakness, but what are some other questions that you might have to answer that can also make you sweat?

Questions that investigate secrets or seek out negative reactions are definitely sneaky, but not unheard of.  Hiring managers and interviewers aren’t above utilizing fear and inducing stress as a common tactic during the job search to see how well you perform under pressure.

If you want to come off as a rockstar in your interview, then preparation is the name of the game.  Beyond that first basic question on your weaknesses, prepare some answers for these tough interview questions and don’t let anything come at you out of left field.

 

Tell Me Something Few People Know About You

This one is supposed to intimidate you, but don’t let it! Here’s why preparation is awesome (and so are you for doing it): You can have something picked out that is not some deep, dark, secret that is likely to get you disqualified for new grad jobs. Instead, focus on some unusual talent, a special skill, or even how you differ in ways of thinking that might impact your work positively. Avoid the urge to spill your guts on something that might make the rest of the interview very, very awkward. Because that’s just not cool– and whomever’s interviewing you will probably think so too.

 

What Did You Like Least About Your Most Recent Position/Job?

This is a trick question because if you mention something in your previous job that you might repeat in your new job, the interviewer will wonder if you will be a bad fit or if you’ll just make the same mistakes again. So, instead focus on some tasks outside your potential area of responsibilities for the new position and be brief about what you disliked about it. If you did perform well, despite this conflict, say so. If not, say it was a learning experience and explain in detail to the employer what you learned from this experience.

 

Tell Me a Story About a Time You Failed and How You Overcame It

I’m going to have to be honest with you here, bud. The employer is not interested in whom you blame for your failures, only how you experienced the event or situation and what it taught you. Remember to stay positive and show how the failure led to a success later, either by learning how to overcome the situation or by sidestepping it in the future all together.

Hopefully these three tricky questions will help you kick some butt in your next interview. Remember, preparation is really the bottom line for going above and beyond. If you’re still having trouble or just want to brush up on more interview-fu skills, make sure you check out our tutorial with advanced tactics such as behavioural and scheduling hacks.

Find out more about what employers expect from a fresh graduate job candidate by signing up at FirstJob.com.

SL LR1This is a guest post by Sean Little. Sean Little is the VP of Marketing for FirstJob.com. FirstJob matches current students and recent college graduates with internships and quality career opportunities. Sean also runs FirstJob’s campus ambassador program at campuses across the country, helping students learn marketing topics while connecting them with top brands and job opportunities. When not busy trying to help recent grads find their dream job, Sean can be found out in San Francisco partaking in live music.

]]>
http://www.completeitprofessional.com/3-interview-questions-most-people-are-not-prepared-for/feed/ 0
How to Convert Data Types in Oracle SQLhttp://www.completeitprofessional.com/convert-data-types-in-oracle-sql/ http://www.completeitprofessional.com/convert-data-types-in-oracle-sql/#comments Tue, 05 May 2015 11:00:09 +0000 http://www.completeitprofessional.com/?p=3480 ]]> How to Convert Data Types in Oracle SQLWhen using Oracle SQL, there are many ways to convert data types. Three of the most common data types are string (VARCHAR2), number, and date. Let’s take a look at how you can convert to these types.

Converting to a Number in Oracle SQL

To convert a value to a number data type, there are two ways you can do it. You can use the CAST function or the TO_NUMBER function.

This is one of the most common ways to convert data types in Oracle SQL.

The main difference between CAST and TO_NUMBER is that CAST is ANSI compliant, and TO_NUMBER (along with the other TO_* functions) are Oracle-specific. CAST also works on a wider range of data types, where as there are only a few data types for the TO_* functions.

Let’s start with TO_NUMBER.

TO_NUMBER lets you convert a string (VARCHAR2, CHAR, etc) to a NUMBER type.

TO_NUMBER(value)

The TO_NUMBER function is quite simple. It has one parameter – the value to convert. It accepts one of the string types, and returns a NUMBER data type. For example:

TO_NUMBER('150')

This function would return a number value of 150.

There are also the TO_BINARY_DOUBLE and TO_BINARY_FLOAT functions, which work in a similar way to convert values to a BINARY DOUBLE and BINARY FLOAT data type respectively.

The other way to convert values into a NUMBER data type is to use the CAST function.

CAST (expression AS type_name)

In this function, the expression is the value you want to convert, and the type_name is the data type you’re converting to. You can specify several types here, but NUMBER is the only numeric type you can use.

For example:

CAST('200' AS NUMBER)

This function would return a number value of 200.

 

Converting to a String in Oracle SQL

As with the NUMBER data type, there are two ways to convert a value to a string data type.

The main string data types in Oracle are:

  • CHAR
  • NCHAR
  • VARCHAR2
  • NVARCHAR2
  • TEXT

The TO_CHAR function takes a value and converts it to a TEXT data type. It works in a similar way to TO_NUMBER, but has a few parameters.

TO_CHAR(expression, [format,] [options])

The expression is the value to convert to a TEXT data type, which can be a type of date, number, or NTEXT. The format is how the input data is identified or formatted, and options specify languages or currency information.

In most cases, you’ll just need the first parameter, which is the only required parameter. For example:

TO_CHAR('20-JAN-2015')

This will show the date in a TEXT data type.

TO_CHAR(1342)

This will show the number in a TEXT data type.

The other way of converting to string data types is to use CAST. It works in a similar way, but can convert to a few more data types:

  • CHAR
  • VARCHAR2
  • NCHAR
  • NVARCHAR2

The CAST function has the same parameters as mentioned earlier.

CAST (expression AS type_name)

In this function, the expression is the value you want to convert, and the type_name is the data type you’re converting to. You can specify several types here, which are from the list above.

For example:

CAST(1094 AS CHAR)

This will convert the value 1094 to a CHAR value.

CAST('01-FEB-2015' AS VARCHAR2)

This will convert the date value to a VARCHAR2 data type.

 

Converting to a Date in Oracle SQL

Just like with the number and string types, there are two ways to convert to a date type.

However, in Oracle, there are two main data types for storing dates:

  • DATE – stores the day, month, and year
  • TIMESTAMP – stores the day, month, year, hour, minute, second, and fraction of a second

It depends on what type you want to convert to as to what function to use.

To convert to just a DATE, you can use the TO_DATE function. It takes a few parameters:

TO_DATE(string, [format,] [nls_parameters])

The string is the value to convert, and is the only required parameter. The format is the format of the date stored as a string, and nls_parameters specify language or regional settings.

For example:

TO_DATE('18-APR-2015')

This will convert the value in a string to a DATE type.

Using parameters, you can specify different kinds of dates.

TO_DATE('01/02/2015', 'dd/mm/yyyy')

This will specify the date as being in the format you mentioned, and convert it to a date.

If you want to convert to a date and time, or a TIMESTAMP, you would use the TO_TIMESTAMP function. It works in a similar way.

TO_TIMESTAMP(string, [format,] [nls_parameters])

An example of this is here:

TO_TIMESTAMP('10-MAR-2015 13:06:10')

This will convert the string value to a TIMESTAMP value.

The final way of converting to a date type is to use CAST. Once again, you use CAST and specify the data type to convert to.

CAST (expression AS type_name)

In this function, the expression is the value you want to convert, and the type_name is the data type you’re converting to. You can specify several types here, such as DATE or TIMESTAMP.

For example:

CAST('18-APR-2015' as DATE)

This will convert the string value to a DATE. You can perform a similar function using a TIMESTAMP.

 

Convert Data Types in Oracle SQL

So, there are a few ways to convert between data types. CAST is more versatile as it can handle more data types, but TO_* functions are easier to use as they have less parameters.

The functions again are:

  • TO_NUMBER
  • TO_CHAR
  • TO_DATE
  • CAST
]]>
http://www.completeitprofessional.com/convert-data-types-in-oracle-sql/feed/ 0
Is LinkedIn Premium Job Seeker Worth It?http://www.completeitprofessional.com/linkedin-premium-job-seeker/ http://www.completeitprofessional.com/linkedin-premium-job-seeker/#comments Mon, 04 May 2015 11:00:10 +0000 http://www.completeitprofessional.com/?p=3471 ]]> LinkedIn Premium for Job SeekersIf you’re on LinkedIn, you may have heard of LinkedIn Premium. Is it worth getting, even if you’re a job seeker? Let’s have a look at ti in this article.

What Is LinkedIn Premium?

LinkedIn Premium is a collection of extra features offered by LinkedIn which are not available to standard, or “Basic” level users. These features allow you to make the most out of the LinkedIn platform and connect with people for a variety of reasons.

To access the LinkedIn premium information page, log in to LinkedIn. Hover over your profile picture icon on the top right, and select “Try Premium”.

capture01

The LinkedIn premium page will appear. Now, the look of this page will depend on when you view the page, as it looks different to last time I opened it and LinkedIn may change the design again at a later date.

Capture02

You’ll see your name and a question about the free trial of Premium (which may or may not be there in the future).

Now, here’s the main part. This Premium page is broken up into four sections. There’s one section for each type of user, or each “reason” for using LinkedIn Premium.

  • Land your dream job
  • Grow and nurture your network
  • Unlock sales opportunities
  • Find and hire talent

What’s the difference between each of these, if they are all for LinkedIn Premium? Well, they each offer different features tailored to a specific kind of user, and each have different prices.

The one that you are probably interested in is the first one – “land your dream job”. This is the one that is targeted towards job seekers.

The types of Premium membership are for:

  • “Land your dream job” is targeted towards job seekers, and is also called “LinkedIn Premium Job Seeker“.
  • “Grow and nurture your network” is targeted towards business owners, and is also called “LinkedIn Premium Business Plus“.
  • “Unlock sales opportunities” is targeted towards salespeople, and is also called “LinkedIn Premium Sales Navigator Professional“.
  • “Find and hire talent” is targeted towards recruiters, and is also called “LinkedIn Premium Recruiter Lite“.

Clicking on each of the boxes will show more details about that plan.

We’re only going to focus on the “LinkedIn Premium Job Seeker” section, as we don’t really care about the other types.

capture03

 

Why Should Job Seekers Get LinkedIn Premium?

Basically, the reason to get LinkedIn Premium is to help you get a job. LinkedIn Premium helps job seekers do this using their Job Seeker version of LinkedIn Premium in many ways.

  • Direct messaging to recruiters
  • Who’s viewed your profile
  • Featured applicant
  • Applicant insights

The ability to directly message recruiters is helpful. LinkedIn Basic only allows you to send messages to people in your network or groups you have joined, and not messages to “cold contacts” (or people you don’t know).

This feature allows you to message recruiters, or even people who have viewed your profile. You’re allowed 3 “InMails” per day (an InMail is LinkedIn’s internal message to another contact).

The “Who’s Viewed Your Profile” feature allows you to see everyone who’s viewed your profile in the last 90 days, where the Basic membership only allows you to see the last 5 people. If you’ve set up your profile to include the right information, then you’d want to see who’s viewed it.

The “Featured Applicant” feature makes sure you stand out in the list of candidates when others look for a job and when you apply for a job. This makes it easier for recruiters to see you and can improve your chances of getting a job.

The “Applicant Insights” feature allows you to see how you compare to other people who have applied for the same job, based on their LinkedIn profile. This one excites me as someone who comes from a database background (I’d like to know how I compare to others if I went for a job).

All of these features allow you to be more efficient and effective at getting a job.

 

Is LinkedIn Premium Worth It For Job Seekers?

That’s what all of this comes down to.

As a job seeker, is it worth it for you to get LinkedIn Premium?

For this question, I’m only talking about the “LinkedIn Premium Job Seeker” version. None of the others are that relevant for job seekers. While their features are good, they are probably too much for the average job seeker.

My answer is yes, I think LinkedIn Premium is worth it for job seekers.

Why do I say this?

Because the time taken to get a job can be greatly reduced by getting a LinkedIn Premium account, allowing you to start earning money faster, and even getting a better job than without it. I’ve included LinkedIn in my list of the best job searching sites for IT professionals, and this is even at the basic level.

Many people may decide against a Premium account, as they might think:

  • “I don’t want to pay for extra features”
  • “I don’t need a Premium account to get a job”
  • “I don’t even use LinkedIn”

However, I think that a change in perspective can really help. Paying the monthly fee for the Job Seeker version of Premium, which is the cheapest of the four options, can accelerate the time taken to get a job. If you start a job sooner, you’ll start earning money soon, which means you’ll more than pay for the LinkedIn Premium membership.

 

What’s the Cost for Job Seeker LinkedIn Premium?

Also, at the time of writing, LinkedIn offers a free 30 day trial, before their subscription starts, which is another incentive to try it out. After the trial ends, the service will cost $29.99 per month. Note that it is showing AUD $29.99 for me, because I’m based in Australia. I’m not sure what the prices would be in other regions, so your page may show something different, but I assume they would all be pretty similar due to the exchange rates.

So, the cost to you would be:

  • Free for 30 days
  • Approximately $29 per month after that

This plan doesn’t offer an annual charge method like the other plans do. This is because Job Seekers may only be using it for a short period such as a few months, where as the other Premium plans would ideally be used for at least a few years.

 

What Are The Downsides of LinkedIn Premium for Job Seekers?

Well, the major downside you might be thinking is the cost. However, the features should give you enough benefits to outweigh this cost and get you the job you’re after.

The other downside is that you actually have to use these features to get the benefit of the membership. Sure, this might not be a downside, but it’s hard to find a downside from such a good service.

If you’re paying for the membership, you’ll need to use the features. You’ll get the most from your membership if you send messages to recruiters, apply for jobs using the Applicant Insights feature, and see who’s viewed your profile. It’s not a “set and forget” membership that will allow you to get a better job magically. You should be using LinkedIn as an IT professional anyway.

 

Conclusion

LinkedIn Premium offers four different versions of its premium service, and the one that is most useful to you is the Job Seeker version. It allows direct messaging to recruiters, see who’s viewed your profile, display as a featured applicant, and to get insights when applying for a job.

I think it’s worth getting, as the cost of the membership is outweighed by the benefits. You also get a free trial.

Career Action Tip: Read the LinkedIn Premium Job Seeker page to find out more about the Job Seeker version of LinkedIn Premium, and if you’re interested, sign up for it.

Lastly, if you enjoy the information and career advice I’ve been providing, sign up to my newsletter below to stay up-to-date on my articles. You’ll also receive a fantastic bonus. Thanks!

 

]]>
http://www.completeitprofessional.com/linkedin-premium-job-seeker/feed/ 0
Oracle CAST Function Explained with Exampleshttp://www.completeitprofessional.com/oracle-cast/ http://www.completeitprofessional.com/oracle-cast/#comments Thu, 30 Apr 2015 11:00:29 +0000 http://www.completeitprofessional.com/?p=3462 ]]> Oracle CAST FunctionThe Oracle CAST function is quite powerful, but it can be hard to use. Learn how to use it and what it can do in this article.

Purpose of the Oracle CAST Function

The purpose of the Oracle CAST function is to convert one data type to another. It allows more functionality than the TO_NUMBER, TO_CHAR and TO_DATE functions, as it allows you to specify the actual data types you want to convert to, rather than just use the defaults of those functions.

 

Syntax

The syntax for the Oracle CAST function is:

CAST( {expr | MULTISET (subquery) } AS type_name )

This structure is a little different as it does not separate the parameters by a comma, as many other functions do. Instead, it has the word “AS”.

There are two main ways you can run this query. You can run it using a single result data type, which would be:

CAST( expr AS type_name )

Or, you can run it using a subquery, which would be:

CAST( MULTISET (subquery) AS type_name )

 

Parameters

The parameters of the CAST function are:

  • expr (mandatory choice): This is the value or expression that is to be converted to another data type. See below for the valid data types.
  • MULTISET (optional): This keyword indicates that the subquery results will return multiple rows, and are then CAST into a collection value. If this is omitted, and the subquery returns multiple rows, it will only return a single row.
  • subquery (mandatory choice): This is the subquery that can be run to be converted into a collection data type.
  • type_name (mandatory): This is the Oracle data type that the expr or subquery will be converted to. See below for the valid data types.

 

Valid Data Types for Oracle Cast

The Oracle CAST function can only convert to and from certain data types. This table from Oracle shows which types are compatible.

from BINARY_FLOAT, BINARY_DOUBLEfrom CHAR, VARCHAR2from NUMBERfrom DATETIME / INTERVALfrom RAWfrom ROWID, UROWIDfrom NCHAR, NVARCHAR2
to BINARY_FLOAT, BINARY_DOUBLEXXXX
to CHAR, VARCHAR2XXXXXX
to NUMBERXXXX
to DATE, TIMESTAMP, INTERVALXX
to RAWXX
to ROWID, UROWIDXX
to NCHAR, NVARCHAR2XXXXXX

A few things to note from this table:

  • The Datetime/Interval column includes DATE, TIMESTAMP, TIMESTAMP WITH TIMEZONE, INTERVAL DAY TO SECOND and INTERVAL YEAR TO MONTH.
  • You cannot cast a UROWID to a ROWID if the UROWID contains the value of a ROWID of an index-organized table.
  • CAST does not support any of the LOB data types. If you try to CAST a CLOB into a character data type, for example, the LOB value is converted to a character value and then converted to the target data type. If the resulting value is larger than the target type, then you’ll get an error.

 

Examples of the Oracle CAST Function

Here are some examples of the Oracle CAST function. I find that examples are the best way for me to learn about code, even with the explanation above.

First of all, let’s set up the CUSTOMERS table.

CREATE TABLE customers (
 first_name varchar2(100),
 last_name varchar2(100),
 country varchar2(20),
 full_address CLOB,
 employees number,
 start_date date
 );
INSERT INTO customers (first_name, last_name, country, full_address, employees, start_date) VALUES ('John', 'Smith', 'USA', '10 Long Road', 4, '12-APR-2010');
 INSERT INTO customers (first_name, last_name, country, full_address, employees, start_date) VALUES ('Sally', 'Jones', 'USA', '50 Market Street', 10, '04-JUL-2011');
 INSERT INTO customers (first_name, last_name, country, full_address, employees, start_date) VALUES ('Steve', 'Brown', 'Canada', '201 Flinders Lane', 15, '21-MAR-2009');
 INSERT INTO customers (first_name, last_name, country, full_address, employees, start_date) VALUES ('Mark', 'Allan', 'UK', '8 Smith Street', 23, '1-FEB-2001');
 INSERT INTO customers (first_name, last_name, country, full_address, employees, start_date) VALUES ('Adam', 'Cooper', 'USA', '14 Wellington Road', 55, NULL);
 INSERT INTO customers (first_name, last_name, country, full_address, employees, start_date) VALUES ('Josh', 'Thompson', NULL, '80 Victoria Street', 1, '10-FEB-2012');
 INSERT INTO customers (first_name, last_name, country, full_address, employees, start_date) VALUES ('Peter', 'Manson', 'France', '5 Johnson St', NULL, '16-OCT-2012');
 INSERT INTO customers (first_name, last_name, country, full_address, employees, start_date) VALUES (NULL, '', NULL, '155 Long Road', NULL, '16-OCT-2012');
SELECT * FROM customers;

Result:

FIRST_NAMELAST_NAMECOUNTRYFULL_AddressEMPLOYEESSTART_DATE
JohnSmithUSA10 Long Road412/APR/10
SallyJonesUSA50 Market Street104/JUL/11
SteveBrownCanada201 Flinders Lane1521/MAR/09
MarkAllanUK8 Smith Street231/FEB/01
AdamCooperUSA14 Wellington Road55(null)
JoshThompson (null)80 Victoria Street110/FEN/12
PeterMansonFrance5 Johnson St (null)16/OCT/12
 (null) (null) (null)155 Long Road (null)16/OCT/12

We can see the data in the customers table that will be used for a few examples below.

 

Example 1 – Oracle CAST String to DATE

This example shows how to CAST from a string value that contains a date, to a date data type.

SELECT '30-APRIL-2015',
CAST('30-APRIL-2015' AS DATE) AS OUTPUT_VALUE
FROM dual;

Result:

’30-Apr-15′OUTPUT_VALUE
30-Apr-1530/APR/15

Notice how the date in the output value is displayed in the date format for Oracle.

 

Example 2 – Oracle CAST NUMBER to String

This example shows how to cast a number to a CHAR data type.

SELECT 41.522,
CAST(41.522 AS CHAR(10)) AS OUTPUT_VALUE
FROM dual;

Result:

41.522OUTPUT_VALUE
41.52241.522

It can be hard to see in this example but the alignment is different in the SQL Developer tool, which is done for different data types.

 

Example 3 – Oracle CAST VARCHAR to Number

This example shows how to convert a VARCHAR to a NUMBER.

SELECT '  2093 ',
CAST('  2093 ' AS NUMBER) AS OUTPUT_VALUE
FROM dual;

Result:

‘2093’OUTPUT_VALUE
   20932093

I’ve put spaces around the first number value, which have been removed when it has converted to a NUMBER data type.

 

Example 4 – Oracle CAST DATE to TIMESTAMP

This example shows how to cast a DATE value to a TIMESTAMP value. For this example, I’ve used the CUSTOMERS table shown above.

SELECT start_date,
CAST(start_date AS TIMESTAMP) AS OUTPUT_VALUE
FROM customers;

Result:

START_DATEOUTPUT_VALUE
12/APR/1012/APR/10 12:00:00.000000000 AM
04/JUL/1104/JUL/11 12:00:00.000000000 AM
21/MAR/0921/MAR/09 12:00:00.000000000 AM
01/FEB/0101/FEB/01 12:00:00.000000000 AM
(null)(null)
10/FEB/1210/FEB/12 12:00:00.000000000 AM
16/OCT/1216/OCT/12 12:00:00.000000000 AM
16/OCT/1216/OCT/12 12:00:00.000000000 AM

Each of the DATE value has been converted to a TIMESTAMP which includes hours, minutes, seconds, and fractional seconds.

 

Example 5 – Oracle Cast NUMBER to VARCHAR2

This example shows how to convert a NUMBER value to a VARCHAR2 data type.

SELECT 9834,
CAST(9834 AS VARCHAR2(30)) AS OUTPUT_VALUE
FROM dual;

Result:

9834OUTPUT_VALUE
98349834

This is similar to Example 2. It can be hard to see in this example but the alignment is different in the SQL Developer tool, which is done for different data types.

 

Example 6 – CAST with Multiset Subquery

This example is a simple example of how to use a multiset subquery with cast.

First, we look at the customers table to find employees in the USA.

SELECT first_name
FROM customers
WHERE country = 'USA';

Result:

FIRST_NAME
John
Sally
Adam

Then, we create a new TYPE to store VARCHAR2 values.

CREATE TYPE usa_employee_first_names AS TABLE OF VARCHAR2(100);

Then, we write our SQL to return a value of that type.

SELECT
CAST(MULTISET(SELECT first_name
  FROM customers
  WHERE country = 'USA')
  AS usa_employee_first_names) AS OUTPUT_VALUE
FROM dual;

 

Result:

OUTPUT_VALUE
SYSTEM.USA_EMPLOYEE_FIRST_NAMES(‘John’,’Sally’,’Adam’)

As you can see, it returns one value. This value is of type “usa_employee_first_names” and includes several values. It can then be used for other purposes, such as inserting into a table.

 

Similar Functions

Some functions in Oracle which are similar to the CAST function are:

  • TO_NUMBER – This function converts a character value to a NUMBER data type.
  • TO_CHAR – This function converts a number or date value to a CHAR data type.
  • TO_DATE – This function converts a character value to a DATE-related data type.

Lastly, if you enjoy the information and career advice I’ve been providing, sign up to my newsletter below to stay up-to-date on my articles. You’ll also receive a fantastic bonus. Thanks!

Image courtesy of digitalart / FreeDigitalPhotos.net

]]>
http://www.completeitprofessional.com/oracle-cast/feed/ 0
How To Find The Path To Your Ideal Job In The IT Industryhttp://www.completeitprofessional.com/how-to-find-the-path-to-your-ideal-job/ http://www.completeitprofessional.com/how-to-find-the-path-to-your-ideal-job/#comments Mon, 27 Apr 2015 11:00:50 +0000 http://www.completeitprofessional.com/?p=3445 ]]> How To Find The Path To Your Ideal Job In The IT IndustryOne of the most popular questions that I’ve gotten on Complete IT Professional over the years is how do I become a <role>, where <role> is any kind of role in the IT industry. I’ve written a few articles on various roles, but this article will explain a method you can use for any role.

Getting in to the role that you want in your career can be challenging. You’ll need to know what the role is, then the steps needed to get there, and then do the work. Where do you get started? How do you get the role that you want in the IT industry?

Let’s take a look at the steps.

 

Decide On Your Ideal Role

The first step to getting the role that you want is to actually work out what it is that you want to do. This is easier said than done.

Do you know the job title of the role that you want to do? For example, you may want to become a Senior Software Engineer at a technology company. Or, you may want to become a Database Administrator in the finance industry.

If you know the job title, it helps, because we’ll use that in the next step.

If you’re not sure of the job title, do you know anyone who is in the position you’d like to be in? For example, a co-worker, or someone from a book you’ve read?

Write this down somewhere. You’ll use it in the next step.

 

Search LinkedIn For That Job Title

Once you have your job title, it’s time to pay a visit to LinkedIn.

If you don’t have a profile already, I highly recommend setting one up. It’s great for your career.

Assuming you have one already, log in to LinkedIn.

Why are we visiting LinkedIn? Well, we’re going to use it to do research on this job title.

For this example, let’s go with the title of Senior Software Engineer. Put that title into the search box at the top of the page.

 

LinkedIn search

The results will appear. At the time of writing, there is a list of job opportunities. This is probably on purpose, but LinkedIn may change this in the future.

LinkedIn search results

We only want to see people. Click on the People link on the left, and the page will show people who have that title.

LinkedIn search results for software engineer

 

Now, the thing to note here is that the list of people will be dependent on your connections. So, it will show people who are closely connected to you at the top of the list. It’s also dependent on their profile setup and keywords they have used, as LinkedIn tries to show you the most relevant people based on your search.

So, we have a list of people with that title. Now what?

 

Look At The Job History Of People With That Title

The next step is to have a look at the job history of people who are currently working in that role.

Why do we do this?

Well, the best way of finding out how to become a certain role is to find people who have done it before, or are doing it now, and see how they got there. LinkedIn is a great way to find this, as people usually list their employment history in their profile.

So, find a profile from the list what has the title you want and click on the name.

Now, I’ve blocked out some of the details of this profile to maintain privacy of the person in question, but you should be able to get the general picture.

software engineer sample profile

This summary section will show an overview of the person, which usually includes their qualifications and experience. However, for most profiles, it’s too broad to use for this research.

Scroll down below that and have a look at the section titled Experience.

software engineer experience

You can see, in this example, that the person currently works as a Senior Software Engineer, because the date says “August 2010 – Present”. They have been in this role for almost 5 years at this company. You can also see what kind of work is involved and usually a little bit about the company.

However, to find out what you need, keep scrolling down.

There should be more entries in this Experience section for this person. LinkedIn profiles, unlike resumes, don’t have a limit on experiences, so you should see all of their roles here.

Sure enough, scrolling to the bottom will see this person’s first role.

software engineer role

This will show how they got started in this industry.

What do you need to do with this information?

 

Write Down Their Job History

Make a list of their roles and dates.

This helps with working out how to get where you want to be, and how long it takes.

So, go through this person’s profile and make a list of:

  • Their job role
  • Their tenure (how long they spent in the role)

Both of these are easily visible in the profile.

But, that’s not all you’ll need. You also need the Education part.

 

Include Their Education

Experience is one thing. Another factor to consider is the education.

Keep scrolling down in the profile you’re looking at, until you see the Education section.

This is important, as it shows you how the person got started in their first role.

education on linkedin example

As you can see, this person has a Bachelor in Computer Studies from a university, then went on to get a Masters in Engineering. They also did some independent coursework, and got a PRINCE2 foundation (which is in the Project Management field).

Once again, take note of these points from the Education, Certifications and Courses section:

  • The achievement (e.g. bachelor’s, master’s, certification)
  • The date achieved

This will show what extra things you need to get into this role.

 

Repeat for More People

Alright, so you’ve got the information from one profile. Now what?

One result is not a definitive guide to getting the role you want.

You should go back to the search results, choose someone else from the list, and repeat the same task.

How many times should you do this? Well, as many as you can until you understand what needs to be done to become this role. As an indication, I would probably get information from 10 different profiles if I was doing this myself.

If you have a large list of people, or are looking for a particular kind of role, you can use filters.

There are filters on the left that let you filter by your relationship, location, company, industry, and more.

I would suggest filtering by country, as different countries may have different requirements. You may also want to filter by company or industry, if you’re looking for those in particular.

The research for each person should take about 10 minutes. Before long, you’ll have a pretty good list of different profiles.

 

Combine and Look for Trends

Once you have a list of people in the role that you want, as well as their history, you should now combine the data.

By this, I don’t mean add them all into a long list. I mean, create some kind of summary that shows the most popular route to getting in to that role.

For example, let’s say you have information on 10 people.

Let’s start with Education. 7 of the 10 got a Bachelor’s degree, 1 has a master’s, and the other 2 didn’t have anything. You could then write down that the education requirement is to get a Bachelor’s degree.

The next step is their first role. Let’s say 6 of them started as a junior software developer, 1 in help desk, 1 as a software engineer, and 1 as a web designer. You should pick the majority here, and note that the first role is a junior software developer.

How long did they stay a junior software developer? Find the most common answer here as well. Let’s say it’s 3.5 years – so write that down. Don’t forget to include the next jobs, as some people move to a different company in the same role, which comes up as two entries on their LinkedIn profile.

Keep going until you get a complete picture of the path to the role you want.

For example, it could look like this:

Senior Software Engineer

  • Bachelor’s Degree in Computer Science
  • 3 years Junior Software Developer
  • 5 years Software Developer
  • 2.5 years Software Engineer
  • 5 years Senior Software Engineer

From this information, you can see the education needed, the job roles on the way to that role, and the time spent in each role. In this example, it shows you need a Bachelor’s degree and 10.5 years experience to become a Senior Software Engineer.

 

Well, I hope this guide has been helpful if you’re trying to work out where your career is going and how to find the path to your ideal job. If you have a long term career plan (link), it’s one step you should be doing. If you don’t have a long term career plan, make one!

Readers, what is your ideal role? What would it take for you to get there? How did you go with this process? Reply in the comments section below.

Career Action Tip: Perform this process for the job role that you want in your IT career.

Lastly, if you enjoy the information and career advice I’ve been providing,sign up to my newsletter belowto stay up-to-date on my articles. You’ll also receive a fantastic bonus. Thanks!

Image courtesy of jscreationzs / FreeDigitalPhotos.net

]]>
http://www.completeitprofessional.com/how-to-find-the-path-to-your-ideal-job/feed/ 0
Oracle RPAD Function with Exampleshttp://www.completeitprofessional.com/oracle-rpad/ http://www.completeitprofessional.com/oracle-rpad/#comments Thu, 23 Apr 2015 11:00:24 +0000 http://www.completeitprofessional.com/?p=3437 ]]> Oracle RPAD Function with ExamplesThe Oracle RPAD function can be useful, especially when using it with the LPAD function. Let’s learn more about the RPAD function and see some examples in this article.

Purpose of the Oracle RPAD Function

The purpose of the Oracle RPAD function is to take a text value, and “pad” it on the right, by adding extra characters to the right of the value to meet a specified length.

It can be useful for ensuring that all values are the same length. Just like the LPAD function, it’s often used in hierarchical queries.

 

Syntax

The syntax of the RPAD function is:

RPAD( expr, length [, pad_expr] )

Let’s have a look at what each of these parameters mean.

 

Parameters

The parameters of the Oracle RAD function are:

  • expr (mandatory): This is the text value or text expression that you want to pad.
  • length (mandatory): This is the total length value that the expr will be padded to.
  • pad_expr (optional): This is the character or set of characters to use for padding the expr value. The default value is a single space.

 

Some things to note about the RPAD function:

  • The length specifies the display length, and not the number of characters in the string. This is mostly the same, but for some multibyte character sets, it can be different. If you’re using VARCHAR2 values then it should match.
  • If the length value is shorter than the length of expr, then the expr is trimmed to be length characters.
  • If pad_expr is not specified, a single space is used.
  • The return data type is TEXT.

 

Can You Use Both Oracle RPAD and LPAD Functions At Once?

Yes, you can use RPAD and LPAD in the same query. This is quite common, as sometimes you want to pad characters to both sides of a string.

See the examples section below for more information on how you can do this and what the results are.

 

Can You Use Oracle RPAD with a NULL String?

No, RPAD will not work with NULL values. If the expression you’re providing contains a NULL value, or if you’re using a column that may contain a NULL value, you’ll need to use the NVL function first (or a function like COALESCE or DECODE to change it to a non-NULL value).

So, instead of this function:

RPAD(columnname, 15, ' ')

You’ll need to use something like:

RPAD(NVL(columnname, ' '), 15, ' ')

See the examples below for more information.

If you don’t use a NVL function or something similar, your return value will be NULL. This may or may not be the desired outcome.

 

Examples of the RPAD Function

Here are some examples of the RPAD function. I find that examples are the best way for me to learn about code, even with the explanation above.

Example 1

This example uses RPAD with the default padding value.

SELECT first_name, RPAD(last_name, 15) AS padded_value
FROM customers;

Result:

FIRST_NAMEPADDED_VALUE
JohnSmith
SallyJones
SteveBrown
MarkAllan
AdamCooper
JoshThompson
PeterManson
(null)(null)

 

The names have all been padded with spaces on the right to be the same length.

 

Example 2

This example uses a * as the padding value.

SELECT first_name, RPAD(last_name, 15, '*') AS padded_value
FROM customers;

Result:

FIRST_NAMEPADDED_VALUE
JohnSmith**********
SallyJones**********
SteveBrown**********
MarkAllan**********
AdamCooper*********
JoshThompson*******
PeterManson*********
(null)(null)

The values have had a * character padded to the right instead of a space.

 

Example 3

This example uses a length that is less than some of the values.

SELECT first_name, RPAD(last_name, 3, ' ') AS padded_value
FROM customers;

Result:

FIRST_NAMEPADDED_VALUE
JohnSmith
SallyJones
SteveBrown
MarkAllan
AdamCoope
JoshThomp
PeterManso
(null)(null)

Some of the values are trimmed to match the length value of 5.

 

Example 4

This example uses RPAD on a number column.

SELECT employees, RPAD(employees, 4, ' ') AS padded_value
FROM customers;

Result:

EMPLOYEESPADDED_VALUE
44
1010
1515
2323
5555
11
(null)(null)
(null)(null)

The values are padded in the same way as a string value.

 

Example 5

This example uses LPAD and RPAD in the one statement, with different characters to show you how they are added.

SELECT last_name, RPAD(LPAD(last_name, 10, '#'), 15, '*') AS padded_value
FROM customers;

Result:

LAST_NAMEPADDED_VALUE
Smith#####Smith*****
Jones#####Jones*****
Brown#####Brown*****
Allan#####Allan*****
Cooper####Cooper*****
Thompson##Thompson*****
Manson####Manson*****
(null)(null)

The value is padded with # on the left, which varies to match the 10 character length, and then a set of * to bring the 10 characters up to 15 characters.

 

Example 6

This example uses the NVL function with a NULL value.

SELECT country, RPAD(NVL(country, ' '), 10, '_') AS padded_value
FROM customers;

Result:

COUNTRYPADDED_VALUE
USAUSA_______
USAUSA_______
CanadaCanada____
UKUK________
USAUSA_______
(null) _________
FranceFrance____
(null) _________

The values which are not null are padded, and the null value is represented as a space character.

 

Example 7

This example uses a NULL value as the padding expression, just to see what happens.

SELECT country, RPAD(country, 8, NULL) AS padded_value
FROM customers;

Result:

COUNTRYPADDED_VALUE
USA(null)
USA(null)
Canada(null)
UK(null)
USA(null)
(null)(null)
France(null)
(null)(null)

All of the values are changed to NULL, which is probably not what you wanted.

 

Example 8

This example shows how to use LPAD with multiple characters as your pad_expr.

SELECT country, RPAD(country, 15, '-*') AS padded_value
FROM customers;

Result:

COUNTRYPADDED_VALUE
USAUSA-*-*-*-*-*-*
USAUSA-*-*-*-*-*-*
CanadaCanada-*-*-*-*-
UKUK-*-*-*-*-*-*-
USAUSA-*-*-*-*-*-*
(null)(null)
FranceFrance-*-*-*-*-
(null)(null)

The country values are padded with a combination of – and *. If there is not an exact match between padding characters and places remaining (such as with Canada or UK), then only part of the padding expression is used.

 

Example 9

This example uses a dynamic length, which is based on the length of each value.

SELECT country, RPAD(country, LENGTH(country)*2, '*') AS padded_value
FROM customers;

Result:

COUNTRYPADDED_VALUE
USAUSA***
USAUSA***
CanadaCanada******
UKUK**
USAUSA***
(null)(null)
FranceFrance******
(null)(null)

The values are padded to different lengths, as determined by the LENGTH function. Each name has a different number of * characters after it.

 

Similar Functions

Some functions which are similar to the RPAD function are:

  • LPAD – This function is similar to RPAD, but will add characters to the left of the string.
  • CONCAT – This function will combine or concatenate two values together.

Lastly, if you enjoy the information and career advice I’ve been providing, sign up to my newsletter below to stay up-to-date on my articles. You’ll also receive a fantastic bonus. Thanks!

Image courtesy of digitalart / FreeDigitalPhotos.net

]]>
http://www.completeitprofessional.com/oracle-rpad/feed/ 0