{"id":73075,"date":"2017-02-15T12:02:19","date_gmt":"2017-02-15T12:02:19","guid":{"rendered":"https:\/\/www.red-gate.com\/simple-talk\/uncategorized\/oracle-for-absolute-beginners-data-types\/"},"modified":"2021-07-14T13:06:55","modified_gmt":"2021-07-14T13:06:55","slug":"oracle-for-absolute-beginners-data-types","status":"publish","type":"post","link":"https:\/\/www.red-gate.com\/simple-talk\/databases\/oracle-databases\/oracle-for-absolute-beginners-data-types\/","title":{"rendered":"Oracle for Absolute Beginners: Data Types"},"content":{"rendered":"<p>All databases stand on a tripod of datatypes: strings, numbers and dates. And so I&#8217;d imagine that by Day 2 or so of dabbling with Oracle you&#8217;d be starting to get reasonably comfortable with the VARCHAR2, NUMBER and TIMESTAMP data types. And that&#8217;s a good thing, familiarity with those three data types will take you a long way into a career of working with the Oracle database.<\/p>\n<p>However, there are a legion of &#8216;second string&#8217; data types that you&#8217;ll probably want to be passingly familiar with too. It&#8217;s kinda like when you meet someone, and fall in love. Sure you want to know every single thing about the gorgeous person you&#8217;re in love with &#8211; but to\u00a0<em>really<\/em> know them, don&#8217;t you need to know a bit about the family they come from too?<\/p>\n<p>So here are some of the other Oracle data types &#8211; here are some of their quirks, and here are the instances when you might want to use them (I&#8217;ll only be talking about character and number data types, along with a little bit on large objects; I&#8217;ve written <a href=\"https:\/\/allthingsoracle.com\/oracle-for-absolute-beginners-date-timestamp-and-interval\/\" target=\"_blank\">a whole separate article about the various date data types<\/a>).<\/p>\n<h5>Character Data Types<\/h5>\n<h6>CHAR<\/h6>\n<p>The CHAR data type is rather similar to its more popular cousin, VARCHAR2. The one difference between them is that while VARCHAR2 is a\u00a0<em>var<\/em>iable\u00a0<em>char<\/em>aracter data type, CHAR is always a fixed length. And when the string falls short of the set fixed length, CHAR pads it out with blank spaces. \u00a0I&#8217;ll show you what I mean; let&#8217;s knock up a table with a CHAR and a VARCHAR2 column.<\/p>\n<pre>CREATE TABLE test_table\r\n(varchar2_col \u00a0VARCHAR2(10),\r\nchar_col CHAR(10)\r\n);<\/pre>\n<p>If we insert a string of less than 10 characters into both columns and query the table we&#8217;ll notice no immediate difference.<\/p>\n<pre>INSERT INTO test_table (varchar2_col, char_col)\r\nVALUES ('sausage','sausage');<\/pre>\n<pre>SELECT varchar2_col, char_col\r\nFROM test_table;\r\n\r\nvarchar2_col    char_col\r\n------------    ----------\r\nsausage         sausage<\/pre>\n<p>However, if we ask Oracle the\u00a0<em>length<\/em> of each string, we&#8217;ll notice something curious.<\/p>\n<pre>SELECT length(varchar2_col) varchar2_col, length(char_col) char_col\r\nFROM test_table;\r\n\r\nvarchar2_col    char_col\r\n------------    ----------\r\n7               10\r\n<\/pre>\n<p>The reason for this discrepancy becomes obvious if we concatenate a character, let&#8217;s use an x, to the start and end of each field.<\/p>\n<pre>SELECT 'x'||varchar2_col||'x' varchar2_col, 'x'||char_col||'x' char_col\r\nFROM test_table;\r\n\r\n\r\nvarchar2_col    char_col\r\n------------    ----------\r\nxsausagex       xsausage x<\/pre>\n<p>CHAR columns, as I said earlier, are right-padded with blank spaces. This may come in handy one day in your career (I&#8217;ve occasionally needed to generate fixed-length files and have used CHAR in those instances), however, many experts would urge you to avoid CHAR. Because of its inflexible length it can gobble up disk space (compared to VARCHAR2) and there&#8217;s nothing it can do that <a href=\"https:\/\/docs.oracle.com\/cd\/B19306_01\/server.102\/b14200\/functions140.htm\" target=\"_blank\">rpad<\/a>\u00a0(<em>varchar2)<\/em> can&#8217;t do.\u00a0<\/p>\n<p>CHAR, however, isn&#8217;t the most reviled character data type. That dubious honour is reserved for&#8230;<\/p>\n<h6>LONG<\/h6>\n<p>The very first words in <a href=\"https:\/\/docs.oracle.com\/cd\/B28359_01\/server.111\/b28318\/datatype.htm#CNCPT1831\" target=\"_blank\">the Oracle documentation<\/a> on the LONG data type are &#8220;Do not create tables with LONG columns.&#8221; This is because the data type has been deprecated and is only included in each subsequent database version to ensure backward compatibility. However, I must have done something really bad in a past life, cos I&#8217;ve often worked with databases where other developers have decided, in their &#8216;wisdom&#8217;, to use LONG columns.\u00a0<\/p>\n<p>So what&#8217;s so bad about LONGs, you ask.\u00a0<\/p>\n<p>For starters you can only have one LONG column in a table. And if that&#8217;s not bad enough, you then can&#8217;t use that LONG column in your where\u00a0clause; it just isn&#8217;t allowed. Neither is it allowed in your group by clause, or order by, or in a distinct. And that&#8217;s not all &#8211; stored functions cannot return a LONG.<\/p>\n<p>So never use LONGs. And if you ever come across a LONG column in a database you&#8217;re working with, take a minute to curse the fool who used it, and then be aware of its limitations.<\/p>\n<p>For the sake of completeness, I probably should tell you what the features of LONGs are: LONGs hold variable-length character data, very much like VARCHAR2. However, compared to VARCHAR2&#8217;s paltry 32767 character limit, LONG can hold up to 2 gigabytes of information.<\/p>\n<p><em>Do not create tables with LONG columns<\/em>, the Oracle documentation reads; <em>use LOB columns (CLOB, NCLOB) instead<\/em>.<\/p>\n<h6>CLOB<\/h6>\n<p><strong>C<\/strong>haracter <strong>L<\/strong>arge <strong>Ob<\/strong>jects &#8211; CLOBs to their friends &#8211; can hold up to 4gb of data. That&#8217;s a crazy amount of data &#8211; around 260,000 MS Word pages; it makes the 32767 characters VARCHAR2 can hold look as tiny as a two year old girl crying in the rain.\u00a0<\/p>\n<p>I don&#8217;t know about you, but I don&#8217;t actually have many 260,000-page Word documents that I need to save, so my advice is that unless you know that your text will breach the 32767 character limit you should stick with VARCHAR2. \u00a0CLOBs do not suffer from the stupid restrictions that blight LONGs, but they still incur slight performance costs compared to VARCHAR2.\u00a0<\/p>\n<p>Beyond that, you can actually use a number of the SQL constructions that you use with VARCHAR2 with CLOBs. I&#8217;ll show you; let&#8217;s start off by creating a table with 2 CLOB columns (which is something we wouldn&#8217;t have been able to do with LONGs).<\/p>\n<pre>CREATE TABLE clob_test(\r\n clob_col1 \u00a0CLOB,\r\n clob_col2  CLOB\r\n);<\/pre>\n<pre>INSERT INTO clob_test (clob_col1, clob_col2)\r\nVALUES ('sausages','eggs');<\/pre>\n<p>Now let&#8217;s try a few of the everyday operations that we might use with a VARCHAR2 column.<\/p>\n<pre>SELECT clob_col1||clob_col2 \"Concat\", \r\n       UPPER(clob_col1) \"Upper\", \r\n       LENGTH(clob_col1) \"Length\", \r\n       NVL(clob_col1,clob_col2) \"NVL\", \r\n       SUBSTR(clob_col2,1,3) \"Substr\"\r\nFROM clob_test;\r\n\r\nConcat        Upper     Length  NVL       Substr\r\n-----------   -------   ------  --------  ------ \r\nSausageseggs  SAUSAGES  8       Sausages  egg\r\n<\/pre>\n<p>That runs happily, and it seems that there&#8217;s no difference between CLOBs and VARCHAR2s. But if you get complacent and try the following seemingly-innocent query:<\/p>\n<pre>SELECT clob_col1\r\nFROM clob_test\r\nWHERE clob_col1 = clob_col2;<\/pre>\n<p>You&#8217;ll be hit with an ORA-00932 &#8211; inconsistent datatypes &#8211; error. And that&#8217;s because CLOBs\u00a0<em>aren&#8217;t<\/em> just super-sized VARCHAR2s and there are some things you can&#8217;t do easily with them, and that list includes comparisons.\u00a0<\/p>\n<p>To get around this limitation Oracle has given us the dbms_lob package. It contains a number of subprograms that make manipulating LOBs &#8211; CLOBs as well as <strong>B<\/strong>inary <strong>L<\/strong>arge <strong>Ob<\/strong>jects &#8211; a breeze. One of the functions, for example, allows us rewrite our erroring query.<\/p>\n<pre>SELECT clob_col1\r\nFROM clob_test\r\nWHERE dbms_lob.compare(clob_col1,clob_col2) = 0;<\/pre>\n<p>This is because dbms_lob.compare returns 0 where the CLOBs are exact matches. It returns -1 if the first parameter is less than the second, and 1 if the second is less than the first.<\/p>\n<p>Other functions that live in dbms_lob include getlength, append, substr and instr. What they do is probably obvious from their names; you don&#8217;t need me to spoonfeed you. However, here&#8217;s a complete list of <a href=\"https:\/\/docs.oracle.com\/database\/121\/TTPLP\/d_lob.htm#TTPLP66622\" target=\"_blank\">the dbms_lob subprograms<\/a>, and here&#8217;s a table that tells you <a href=\"https:\/\/docs.oracle.com\/cd\/B19306_01\/appdev.102\/b14249\/adlob_sql_semantics.htm#g1016221\" target=\"_blank\">which CLOB operations you can carry out in SQL and which ones need PL\/SQL<\/a>.<\/p>\n<h5>Number Data Types<\/h5>\n<p>Other databases might have their exotic numeric data types &#8211;<em> tinyint, smallint, bigint<\/em> and whatever &#8211; but Oracle is able to get pretty much everything done with just the <code>NUMBER<\/code> data type. \u00a0It stores both fixed\u00a0<em>and<\/em> floating point numbers. And its got such range that it can hold practically any number that you&#8217;ll ever need to record.<\/p>\n<p>So that&#8217;s it, right, there&#8217;s nothing else you need to know, right? Don&#8217;t be too hasty, let me introduce you to&#8230;<\/p>\n<h6>PLS_INTEGER<\/h6>\n<p>OK, I&#8217;m cheating. PLS_INTEGER is\u00a0<strong><em><span style=\"text-decoration: underline;\">not<\/span><\/em><\/strong> a SQL data type; it&#8217;s \u00a0PL\/SQL data type and can only be used in PL\/SQL. Try using it in plain old SQL and you&#8217;ll get an\u00a0<code>ORA-00902: invalid datatype<\/code> error. You cannot use PL\/SQL data types in SQL &#8211; for table columns or whatever. It&#8217;s like trying to speak Chinese to an Eskimo.<\/p>\n<p>However, the reason I&#8217;m mentioning PLS_INTEGER is that when you are writing PL\/SQL, it is preferable to NUMBER in a few instances. \u00a0It, as its name suggests, is a data type for integers; and it is faster than NUMBER in calculations. It also requires less storage.\u00a0<\/p>\n<p>If we&#8217;re being honest, modern processors are pretty fast and modern storage is pretty cheap, so you mightn&#8217;t think that getting a teensy bit faster or that saving a molecule of storage is worth any hassle. Fair point. But when you&#8217;re writing PL\/SQL and working with integers using PLS_INTEGER rather than NUMBER is a good habit to get into.<\/p>\n<h5>Large Object Data Types<\/h5>\n<p>We&#8217;ve already met one member of the LOB family; it&#8217;s time to introduce you to the rest of the gang. Databases, I&#8217;ve said, stand on a tripod of data types &#8211; strings, numbers and dates. However, not all data falls neatly into one of those categories; we&#8217;ve got music and video files, for instance, and photographs, and stuff like that. We obviously need some other way to hold that data. They allow you to store large blocks of unstructured data in binary form (or in character form, in the case of CLOBs).<\/p>\n<p>Ah, speaking of binary data&#8230;<\/p>\n<h6>BLOB<\/h6>\n<p>We&#8217;ve already talked about how you can manipulate BLOBs using the dbms_lob package. That&#8217;s important to remember, since, because it isn&#8217;t comprised of character data, you cannot treat it like a VARCHAR2 the way you can with a CLOB.\u00a0<\/p>\n<p>How about an example? Let&#8217;s say you wanted to load a photo of your pet rabbit, Mr Tickles, to the database. We might start by creating a table.<\/p>\n<pre>CREATE TABLE blob_test (\r\n  id \u00a0     NUMBER,\r\n  text     VARCHAR2(100),\r\n  blob_col BLOB\r\n);<\/pre>\n<p>Now we&#8217;ve got our table, we can upload Mr Tickles&#8217; photo to it using a dbms_lob subprogram. However, before we do that, let me speak to you about&#8230;<\/p>\n<h6>BFILE<\/h6>\n<p>The BFILE data type is a large object data type that allows you store binary data in an operating system file\u00a0<em>outside the database.<\/em> There are a few commonsense rules that go with BFILEs: the file must exist, and Oracle must have the right operating system privileges to read it. Also, BFILEs only provide read-only access to files.<\/p>\n<p>You can create table columns with the BFILE data type, and you can connect it to files using dbms_lob and <a href=\"https:\/\/docs.oracle.com\/cd\/B19306_01\/server.102\/b14200\/statements_5007.htm\" target=\"_blank\">Oracle directories<\/a> (which is a topic outside the scope of this article). You can also use a BFILE as a\u00a0LOB locator to point at the image of Mr Tickles that we want to upload into our BLOB column&#8230;<\/p>\n<pre>DECLARE\r\n  -- BFILENAME is a function that links an OS file to a BFILE. \r\n\u00a0 src_bfile \u00a0BFILE := BFILENAME('IMAGE_DIR','\/MrTickles.jpg');\r\n\u00a0 dest_blob \u00a0BLOB;\r\nBEGIN\r\n  -- Before you can write to a LOB it must be made non-null. Initialising it using EMPTY_BLOB() does this.\r\n\u00a0 INSERT INTO blob_test (id, text, blob_col)\r\n\u00a0 VALUES (1,'Photo of Mr. Tickles', EMPTY_BLOB())\r\n\u00a0 RETURNING blob_col INTO dest_blob;\r\n\r\n  -- LoadFromFile allows you upload a file to a BLOB\r\n\u00a0 dbms_lob.open(src_bfile, dbms_lob.lob_readonly);\r\n\u00a0 dbms_lob.loadfromfile(DEST_LOB =&gt;dest_blob,\r\n\u00a0                       SRC_LOB\u00a0 =&gt; src_bfile,\r\n\u00a0                       AMOUNT   =&gt; \u00a0dbms_lob.getlength(src_bfile));\r\n\u00a0 dbms_lob.close(src_bfile);\r\n\u00a0 COMMIT;\r\nEND;\r\n\/<\/pre>\n<p>OK, that&#8217;s a lot of code, and I know that my inline comments aren&#8217;t the most in-depth explanation possible, but hopefully they&#8217;re enough to demonstrate how BLOBs and BFILEs work.<\/p>\n<p>Indeed the intention of this whole article has been to expose you to some of the data types that while they might live in the shadows of VARCHAR2, NUMBER and TIMESTAMP are important to know. There&#8217;s a good chance that you won&#8217;t need them every day, but when the day comes that you do need them, you&#8217;ll be glad that you stuck with me to the end of this article.\u00a0<\/p>\n","protected":false},"excerpt":{"rendered":"<p>All databases stand on a tripod of datatypes: strings, numbers and dates. And so I&#8217;d imagine that by Day 2 or so of dabbling with Oracle you&#8217;d be starting to get reasonably comfortable with the VARCHAR2, NUMBER and TIMESTAMP data types. And that&#8217;s a good thing, familiarity with those three data types will take you a long way into a&hellip;<\/p>\n","protected":false},"author":221907,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[143533],"tags":[48367,48369,48374,48376,48439,48475,124952],"coauthors":[48557],"class_list":["post-73075","post","type-post","status-publish","format-standard","hentry","category-oracle-databases","tag-bfile","tag-blob","tag-char","tag-clob","tag-long","tag-pls_integer","tag-redgate-deploy"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/73075","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/users\/221907"}],"replies":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/comments?post=73075"}],"version-history":[{"count":1,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/73075\/revisions"}],"predecessor-version":[{"id":88950,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/73075\/revisions\/88950"}],"wp:attachment":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media?parent=73075"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/categories?post=73075"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/tags?post=73075"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/coauthors?post=73075"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}