{"id":73213,"date":"2014-02-13T11:54:42","date_gmt":"2014-02-13T11:54:42","guid":{"rendered":"https:\/\/www.red-gate.com\/simple-talk\/uncategorized\/oracle-for-absolute-beginners-part-3-update-insert-delete\/"},"modified":"2021-07-14T13:07:35","modified_gmt":"2021-07-14T13:07:35","slug":"oracle-for-absolute-beginners-part-3-update-insert-delete","status":"publish","type":"post","link":"https:\/\/www.red-gate.com\/simple-talk\/databases\/oracle-databases\/oracle-for-absolute-beginners-part-3-update-insert-delete\/","title":{"rendered":"Oracle for Absolute Beginners: Part 3 \u2013 Update, Insert, Delete"},"content":{"rendered":"<p><a title=\"Oracle for Absolute Beginners: Part 1 \u2013 Databases\" href=\"https:\/\/allthingsoracle.com\/oracle-for-absolute-beginners-part-1-databases\/\">Part 1<\/a>, <a title=\"Oracle for Absolute Beginners: Part 2 \u2013 SQL\" href=\"https:\/\/allthingsoracle.com\/oracle-for-absolute-beginners-part-2-sql\/\">Part 2<\/a>.<\/p>\n<p>A wise man* once said: <i>So no-one told you life was gonna be this way. Your job\u2019s a joke, you\u2019re broke, your love life\u2019s DOA. It\u2019s like you\u2019re always stuck in second gear. And when it hasn\u2019t been your day, you week, your month, or even your year.<\/i><\/p>\n<p>[*That wise man <em>wasn\u2019t<\/em> me; but stick with me, I promise to bring this back around to Oracle SQL imminently. ]<\/p>\n<p>So \u2013 since it hasn\u2019t been your day, your week, your month, or even your year \u2013 you decide to go to Central Perk with your friends Ross, Rachel, Monica, Phoebe, Chandler and Joey.\u00a0 Oh, and that new friend you made that\u2019s also named Ross Geller.\u00a0 The music is loud, the atmosphere is great, and a good time is had by everyone.<\/p>\n<p>You wake up the next morning with a bit of a sore head and try to recall everything that went on the night before: you\u2019d discovered that Chandler\u2019s middle name is Muriel, and that Ross\u2019 is Eustace. Rachel gave you her new phone number. Phoebe gave you her new address. Oh, and you had a big fight with new Ross and decided you no longer want to be friends with him.<\/p>\n<p>You roll out of bed and groggily wipe your eyes: all this new information needs recording; you\u2019d better fire up your database.<\/p>\n<h5>UPDATE<\/h5>\n<p>Since we thoroughly looked into SELECT statements in the previous part, we can now turn our attention to UPDATE statements. In SQL we use update statements to change existing records \u2013 not to <i>create<\/i> new records or to delete them \u2013 just to change them.<\/p>\n<p>The syntax for update statements is as follows:<\/p>\n<pre>UPDATE &lt;table name &gt;\r\nSET &lt;column name&gt;= &lt;value&gt;\r\nWHERE &lt;condition(s)&gt;;<\/pre>\n<p>To see an update statement in action, log into your Oracle environment and run a query to select Chandler\u2019s middle name (middle names are stored in the MIDDLE_NAME column) from the FRIEND_NAME table. You should get a null.<\/p>\n<p>Now run the following update statement:<\/p>\n<pre>UPDATE friend_name\r\nSET middle_name = 'Muriel'\r\nWHERE UPPER(first_name) = 'CHANDLER';<\/pre>\n<p>Done that?\u00a0 Now try running your select statement querying his middle name again.<\/p>\n<p>We also need to update Ross Geller\u2019s middle name to Eustace.\u00a0 Knowing our data as intimately as you do by now, can you tell me what\u2019s wrong with running the following update statement?<\/p>\n<pre>UPDATE friend_name\r\nSET middle_name = 'Eustace'\r\nWHERE UPPER(first_name) = 'ROSS'\r\nAND UPPER(last_name) = 'GELLER';<\/pre>\n<p>Figured what\u2019s wrong with it yet? It\u2019s not the syntax; that\u2019s as right as rain. No, the issue \u2013 in this specific case \u2013 is that our WHERE clause identifies <i>two<\/i> people, since we\u2019ve got two friends named Ross Geller.\u00a0 Parachute that where clause into a select query and you\u2019ll see that it returns more than one record. However, we only want to update one record, since we only have one friend named Ross <i>Eustace<\/i> Geller.<\/p>\n<p>Forgive me for sneaking in a lesson about primary keys when we\u2019re talking about update statements, but this is why it is doubly important to use primary key columns in your where clauses when updating (or deleting) records \u2013 cos if we do not uniquely identify the records we want to change (or delete), the consequences can be critical.<\/p>\n<p>So, now that we\u2019ve reinforced that point, I should probably rewrite our update statement as:<\/p>\n<pre>UPDATE friend_name\r\nSET middle_name = 'Eustace'\r\nWHERE friend_id = 1;<\/pre>\n<p>Let\u2019s try a couple more updates.\u00a0 It turns out Monica goes by the last name Bing and really hates being called Geller-Bing.\u00a0 She also mysteriously reveals that her middle name is \u2026 E. Just E.<\/p>\n<p>We could, of course, write two update statements \u2013 one for her surname and the second for her middle name.\u00a0 However, with SQL it is possible to update more than one column in a single update statement as long as the columns are in the same table. We simply need to separate the columns in the SET clause with a comma. Let me demonstrate:<\/p>\n<pre>UPDATE friend_name\r\nSET middle_name = 'E',\r\nLast_name = 'Bing'\r\nWHERE friend_id = 4;<\/pre>\n<p>This method works just as well for three, four or however many columns; do bear in mind, however, that SQL will use the same WHERE clause to identify the record(s) to update.<\/p>\n<h5>INSERT<\/h5>\n<p>Rachel has a new phone number.<\/p>\n<p>I don\u2019t know how well you remember our database structure, but to record this information we will need to add the new number to the PHONE_NUMBER table (this will call for an INSERT statement), and then add a record (another INSERT) to the FRIEND_PHONE linking this new number with Rachel.<\/p>\n<p>Let\u2019s add the phone number.\u00a0 She says her new number is 5550789.\u00a0 Assuming the country and area codes are unchanged and the phone id is 9, our insert statement would be as follows:<\/p>\n<pre>INSERT INTO phone_number  (phone_id, country_code, area_code, phone_number)\r\nVALUES (9, 1, 212, 5550789);<\/pre>\n<p>The syntax for a basic insert statement is as follows:<\/p>\n<pre>INSERT INTO &lt;table_name&gt; (&lt;comma-separated column list&gt;)\r\nVALUES ( &lt;comma-separated value list&gt;);<\/pre>\n<p>Got that? Good. Then maybe you should have a go.\u00a0 Last night, Phoebe mentioned that she\u2019d moved apartments (again!) and has a new address.\u00a0 It is Apartment 10, House 12, Morton Street, New York City, New York, NY 10014.<\/p>\n<p>Create an insert statement to put a new record (with an address_id of 4) into the ADDRESS table. You\u2019ll want to remember that you\u2019ll need to enclose VARCHAR2 strings in single quotes.<\/p>\n<h5>DATES<\/h5>\n<p>And now, just to keep you on your toes, I\u2019m going to interrupt our conversation about insert statements to keep a promise I made you to tell you more about dates. (Don\u2019t panic, we\u2019ll return to inserts once this detour is over.)<\/p>\n<p>The problem with dates, if you recall, is how to use them in SQL; if you enclose them in single quotes they\u2019ll be taken as VARCHAR2 strings and if you don\u2019t they might be mistaken for numbers. The trick is to take a character string and tell SQL to convert it to a date; to do that we\u2019ll need to use the TO_DATE function.<\/p>\n<p>The syntax is as follows:<\/p>\n<pre>TO_DATE(&lt;string&gt;,&lt;format mask&gt;)<\/pre>\n<p>The &lt;string&gt; is the character string that we want converted to a date, and\u00a0 the \u00a0&lt;format mask&gt; is the pattern it matches.<\/p>\n<p>So if I wanted to use a date \u2013 say 25 March, 1999 \u2013 in a where clause or an insert statement, I might write the following:<\/p>\n<p>TO_DATE(&#8217;25\/03\/1999&#8242;,&#8217;DD\/MM\/YYYY&#8217;)<\/p>\n<p>Alternatively, if I were American, I might write<\/p>\n<p>TO_DATE(&#8217;03\/25\/1999&#8242;,&#8217;MM\/DD\/YYYY&#8217;)<\/p>\n<p>Or I could say<\/p>\n<p>TO_DATE(&#8216;1999-03-25&#8242;,&#8217;YYYY-MM-DD&#8217;)<\/p>\n<p>You get the idea. As long as the format mask tells SQL what pattern we\u2019re using, Oracle doesn\u2019t really limit us.<\/p>\n<p>Let me show you how we might use the to_date function in a select statement. If I wanted a list of all my friends who\u2019d been living at the same address since 25 March, 1999, I might say:<\/p>\n<pre>SELECT FRIEND_ID\r\nFROM FRIEND_ADDRESS\r\nWHERE MOVED_IN &gt;= TO_DATE('25\/03\/1999','DD\/MM\/YYYY');<\/pre>\n<h5>INSERT Cont\u2019d<\/h5>\n<p>Let\u2019s get back to Rachel. We were recording the fact that she has a new phone number. We\u2019ve inserted the phone number into the PHONE_NUMBER table with a phone_id of\u00a0 9; now we need to insert a row into FRIEND_PHONE, using what we\u2019ve learned about dates.<\/p>\n<pre>INSERT INTO FRIEND_PHONE (friend_id, phone_id, start_date)\r\nVALUES (5, 9, TO_DATE('01\/01\/2014','DD\/MM\/YYYY'));<\/pre>\n<p>We also need to insert a row into FRIEND_ADDRESS to record the fact that Phoebe has a new address. Her friend_id is 6 and the address_id is 4. Using any date of your choosing in the MOVED_IN column, write the insert statement.<\/p>\n<h5>DELETE<\/h5>\n<p>The syntax for delete statements is:<\/p>\n<pre>DELETE FROM &lt;table name&gt;\r\nWHERE &lt;condition&gt;;<\/pre>\n<p>Since you\u2019ve had a big bust-up with the other Ross Geller, you\u2019ve decided to delete his name from your address book.\u00a0 Using the syntax above \u2013 and remembering to use the primary key identifier instead of the name &#8211; \u00a0the statement we need is:<\/p>\n<pre>DELETE FROM friend_name\r\nWHERE friend_id = 7;<\/pre>\n<p>Copy the statement, paste it in your SQL window, click the <b>Run<\/b> button, and\u2026<\/p>\n<h5>ERRORS<\/h5>\n<p>Did you get the following error?<\/p>\n<pre>ORA-02292: integrity constraint (ALLTHINGSORACLE.FRIEND_PHONE_FRIEND_FK) violated - child record found<\/pre>\n<p>I\u2019m sorry; I set you up. The truth is, we cannot honestly speak about coding without talking about errors. Every programmer \u2013 no matter how good she is \u2013 runs up against errors, often quite frequently. So it is important that you learn to understand \u2013 and not fear \u2013 them.<\/p>\n<p>Oracle errors usually begin with an ORA-, followed by a numeric code and a description. If you find the description to be inadequate, try googling the error code, there are numerous sites where you can plug in the error number and receive advice on what to do next.<\/p>\n<p>Our error \u2013 ORA-02292 \u2013 tells us that an integrity constraint has been violated because a child record has been found. What this means is that we cannot delete Ross from our FRIEND_NAME table when there are records that depend on him (child records) in another table.<\/p>\n<h5>DELETE Cont\u2019d<\/h5>\n<p>Before we can delete Ross Geller from FRIEND_NAME, we must delete the child record from FRIEND_PHONE.\u00a0 Using his friend_id (7), why don\u2019t you write and run a delete statement to do that using the syntax we learned earlier?\u00a0 And once you\u2019ve done that, you can try deleting him from FRIEND_NAME again.<\/p>\n<h5>CONCLUSION<\/h5>\n<p>And that\u2019s it. We\u2019ve covered the basics; we know how to select, update, insert and delete. Plus, we know how to manipulate the various data types and how to stare down error messages.<\/p>\n<p>When I was a child there was a cartoon series on TV named Voltron: Defender of the Universe in which there were 4 robot lions who, individually, were pretty good fighters. But when things got tough they would come together to form one giant robot who was pretty much undefeatable.<\/p>\n<p>Think of what we\u2019ve learned so far \u2013 select, update, insert, delete \u2013 as our four robot lions. In the next article we\u2019re gonna join them together and build our humongous unbeatable robot of advanced selects, joins, sub-queries, functions and procedures.<\/p>\n<p>I. Cannot. Wait.<\/p>\n<h5>PRACTICE<\/h5>\n<p>Here are a few teasers to keep you busy until next time.<\/p>\n<ul>\n<li>Since we\u2019ve added a new phone number for Rachel (friend_id 5) we need to update our records to indicate that she\u2019s no longer using her old phone number. Update FRIEND_PHONE to do this.<\/li>\n<li>Since Phoebe (friend_id 6) has moved to a new address, we need to update our records to indicate that she no longer lives at her old address. Update FRIEND_ADDRESS to do this.<\/li>\n<li>Try inserting the details of your real-world friends into the FRIEND_NAME table. Remember that each record must have a unique friend_id.<\/li>\n<li>Insert some phone numbers into the PHONE_NUMBER table, and then insert records into FRIEND_PHONE associating them with your friends, ensuring that you put dates in the START_DATE column.<\/li>\n<li>Delete some of the records you have just added.<\/li>\n<\/ul>\n<h3>Next Article:\u00a0<a href=\"https:\/\/allthingsoracle.com\/oracle-for-absolute-beginners-part-4-multi-table-queries\/?utm_source=allthingsoracle&amp;utm_medium=publink&amp;utm_content=articleseries\">Oracle for Absolute Beginners: Part 4 \u2013 Multi-table queries<\/a><\/h3>\n","protected":false},"excerpt":{"rendered":"<p>Part 1, Part 2. A wise man* once said: So no-one told you life was gonna be this way. Your job\u2019s a joke, you\u2019re broke, your love life\u2019s DOA. It\u2019s like you\u2019re always stuck in second gear. And when it hasn\u2019t been your day, you week, your month, or even your year. [*That wise man wasn\u2019t me; but stick wit&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":[48366],"coauthors":[],"class_list":["post-73213","post","type-post","status-publish","format-standard","hentry","category-oracle-databases","tag-beginners-guide"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/73213","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=73213"}],"version-history":[{"count":1,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/73213\/revisions"}],"predecessor-version":[{"id":91697,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/73213\/revisions\/91697"}],"wp:attachment":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media?parent=73213"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/categories?post=73213"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/tags?post=73213"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/coauthors?post=73213"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}