{"id":1003,"date":"2023-11-18T23:15:34","date_gmt":"2023-11-18T23:15:34","guid":{"rendered":"https:\/\/s-oneill.com\/sov02\/?p=1003"},"modified":"2023-11-18T23:19:49","modified_gmt":"2023-11-18T23:19:49","slug":"sql-cheatsheet","status":"publish","type":"post","link":"https:\/\/s-oneill.com\/sov02\/sql-cheatsheet\/","title":{"rendered":"SQL Cheatsheet"},"content":{"rendered":"<p><strong>CREATE TABLE<\/strong> table_name (col_1_name col_1_type, column_2_name column_2_type&#8230;);<br \/>\ne.g.<br \/>\n<code>CREATE TABLE items (id INTEGER, name TEXT);<\/code><\/p>\n<p>add <strong>PRIMARY KEY<\/strong> and <strong>AUTOINCREMENT<\/strong> keywords to the id field while creating the table, like so:<\/p>\n<p><code>CREATE TABLE items (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT);<\/code><\/p>\n<p>To automatically increment ids on each insertion, no need to define id when inserting items.<br \/>\nPrimary key means the column is for unique ids<\/p>\n<p><strong>INSERT INTO <\/strong>table_name (column_1_name, column_2_name) VALUES (value_1, value_2);<br \/>\ne.g.<br \/>\n<code><strong>INSERT INTO <\/strong>items (id, name) VALUES (2, \"Book\");<\/code><\/p>\n<p>items table:<br \/>\n\tid \t|\tname<br \/>\n\t2 \t|\tBook<\/p>\n<p><strong>UPDATE<\/strong> table_name SET column_n_name = value_1 WHERE column_n_name = value_2;<br \/>\ne.g.<br \/>\n<code><strong>UPDATE<\/strong> items SET name = \"Novel\" WHERE id = 2;<\/code><\/p>\n<p>items table<br \/>\n\tid \t|\tname<br \/>\n\t2 \t|\tNovel<\/p>\n<p><strong>SELECT<\/strong> column_n_name, column_n_name&#8230; FROM table_name;<br \/>\ne.g.<br \/>\n<code>SELECT id, name FROM items;<\/code><\/p>\n<p>This will return all id and name values from all rows in the items table:<\/p>\n<p>a &#8216;*&#8217; wildcard also represents all columns:<\/p>\n<p><code>SELECT * FROM items;<\/code><br \/>\nreturns all of the rows:<\/p>\n<p>Use the <strong>WHERE<\/strong> statement to narrow the returned values<\/p>\n<p><code>SELECT * FROM items WHERE name = \"Novel\";<\/code><br \/>\nreturns all data from row(s) where the name col value is is &#8220;Novel&#8221;<\/p>\n<p><strong>ORDER BY <\/strong>will sort the results by the column you choose (default <strong>ASC<\/strong>).<br \/>\nTo reverse the order add <strong>DESC<\/strong> after the column name (ascending or descending).<\/p>\n<p><code>SELECT * FROM items WHERE name = \"Novel\" >ORDER BY id DESC;<\/code><br \/>\nYou can also use logical operators like AND and OR to connect more statements.<\/p>\n<p>SELECT * FROM items WHERE name = &#8220;Novel&#8221; AND id = 2;<\/p>\n<p><strong>DELETE<\/strong> FROM table_name WHERE column_n_name = value;<br \/>\ne.g.<br \/>\n<code>DELETE FROM items WHERE id = 2;<\/code><\/p>\n<p><strong>DROP TABLE<\/strong> table_name;<br \/>\ne.g.<br \/>\n<code>DROP TABLE items;<\/code><\/p>\n<p>You can also create a condition to only delete the table if it exists.<br \/>\n<code>DROP TABLE IF EXISTS items;<\/code><\/p>\n<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;<\/p>\n<p><strong>FOREIGN KEYS<\/strong><br \/>\nWe can define relationships between tables.<br \/>\nAn items table may have multiple items that have the same category .<\/p>\n<p>items table<br \/>\n\tid\t|\t name \t|\tcategory<br \/>\n\t1\t|\t Apple\t|\t Fruit<br \/>\n\t2\t|\t Hammer\t|\t Tools<br \/>\n\t3\t|\t Wrench\t|\t Tools<\/p>\n<p>Instead of storing the same category string multiple times,<br \/>\nwe can create another table which will store all of the categories.<\/p>\n<p>categories table<br \/>\n\tid\t|\tcategory<br \/>\n\t1\t|\t Fruit<br \/>\n\t2\t|\t Tools<\/p>\n<p>Now we can just create a reference column inside of the items table, instead of storing strings, we can now store id &#8216;s from the categories table.<\/p>\n<p>items table<br \/>\n\tid\t|\t name \t|\tcategory_id<br \/>\n\t1\t|\t Apple\t|\t 1<br \/>\n\t2\t|\t Hammer\t|\t 2<br \/>\n\t3\t|\t Wrench\t|\t 2<\/p>\n<p>We can connect this category_id column with the id column from the categories database<br \/>\nwith the help of FOREIGN KEYS. <\/p>\n<p><strong>FOREIGN KEY<\/strong> will define the connection. <\/p>\n<p>Here is the SQL for creating these tables:<\/p>\n<p><code>CREATE TABLE categories (<br \/>\n\tid INTEGER PRIMARY KEY AUTOINCREMENT,<br \/>\n\tname TEXT<br \/>\n);<br \/>\nCREATE TABLE items (<br \/>\n\tid INTEGER PRIMARY KEY AUTOINCREMENT,<br \/>\n\tname TEXT,<br \/>\n\tcategory_id INTEGER,<br \/>\n\tFOREIGN KEY(category_id) REFERENCES categories(id)<br \/>\n);<\/code><\/p>\n<p><strong>Joins<\/strong> (Inner, Left, Right and Full Joins)<br \/>\nA JOIN clause combines rows from two or more tables based on related columns.<\/p>\n<p><strong>INNER JOIN <\/strong> selects records that have matching values in multiple tables.<\/p>\n<p>Review: This SELECT will print out the rows from the items table created earlier<\/p>\n<p><code>SELECT id, name, category_id FROM items;<\/code><\/p>\n<p>items table<br \/>\n\tid\t|\t name \t|\tcategory_id<br \/>\n\t1\t|\t Apple\t|\t 1<br \/>\n\t2\t|\t Hammer\t|\t 2<br \/>\n\t3\t|\t Wrench\t|\t 2<\/p>\n<p>But we want to see the category name not the category id.<br \/>\n<strong>INNER JOIN<\/strong> can join two tables together using the ON keyword with a foreign key<br \/>\nfor example:<\/p>\n<p><code>SELECT *<br \/>\nFROM items<br \/>\nINNER JOIN categories ON items.category_id = categories.id;<\/code><\/p>\n<p>&#8230; will join the tables together on the appropriate columns.<\/p>\n<p>items table joined with categories<br \/>\n\tid \t|\tname \t|\tcategory_id \t|\tid \t|\tname<br \/>\n\t1 \t|\tApple\t\t|\t\t 1\t\t|\t 1\t|\t Fruit<br \/>\n\t2\t|\tHammer\t|\t\t 2\t\t|\t 2\t|\tTools<br \/>\n\t3\t|\tWrench\t|\t\t 2\t\t|\t 2\t|\tTools<\/p>\n<p>Instead of printing all of the columns, you can pick which ones to print.<br \/>\nColumns with the same name in both tables have to be prefixed with the table name.<br \/>\nSince this is the case, it&#8217;s better to prefix all of the columns when doing INNER JOIN , just to be sure.<\/p>\n<p><code>SELECT items.id, items.name, categories.name<br \/>\nFROM items<br \/>\nINNER JOIN categories ON items.category_id = categories.id;<\/code><\/p>\n<p>items table joined with categories<br \/>\n\titems.id \t|\t items.name \t|\t categories.name<br \/>\n\t\t1 \t|\t Apple  \t\t|\tFruit<br \/>\n\t\t2 \t|\t Hammer  \t\t|\tTools<br \/>\n\t\t3 \t|\t Wrench  \t\t|\tTools<\/p>\n<p>Now we are listing the category name next to items &#8211;<br \/>\nwithout repeating category name strings in the items table.<\/p>\n<p>Since joins can involve many tables, queries can get long.<br \/>\nYou can use <strong>AS<\/strong> to create <strong>aliases<\/strong> for each table and use those aliases throughout the query.<\/p>\n<p><code>SELECT i.id, i.name, c.name<br \/>\nFROM items AS i<br \/>\nINNER JOIN categories AS c ON i.category_id = c.id;<\/code><\/p>\n<p><strong>LEFT (OUTER) JOIN: <\/strong>Returns all records from the left table, and the matched records from the right table<br \/>\n For the rows for which there is no matching row on the right side, the result-set will contain null. <\/p>\n<p><strong>SELECT *<br \/>\nFROM Orders<br \/>\nLEFT JOIN Customers<br \/>\nON items.category_id = categories.category_id<br \/>\n;<\/strong><\/p>\n<p><strong>RIGHT (OUTER) JOIN:<\/strong> Returns all records from the right table, and the matched records from the left table<br \/>\nFor the rows for which there is no matching row on the left side, the result-set will contain null. <\/p>\n<p><strong>FULL (OUTER) JOIN:<\/strong> Returns all records when there is a match in either left or right table<br \/>\nThe result-set will contain all the rows from both tables. For the rows for which there is no matching, the result-set will contain NULL values.<\/p>\n<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;<\/p>\n<p><strong>COUNT<\/strong><br \/>\nCalculates the number of rows returned by a query.<\/p>\n<p><code>SELECT COUNT(*) FROM items WHERE name = \"Apple\"<\/code><\/p>\n<p>This will return 1 <\/p>\n<p><strong>LIKE<\/strong><br \/>\nThe <strong>LIKE<\/strong> keyword can be used with <strong>WHERE<\/strong> to find substrings in some column.<br \/>\nFor example, if you want all of the rows which have the name that starts with App.<\/p>\n<p><code>SELECT id, name FROM items WHERE name LIKE 'App%';<\/code><\/p>\n<p>items\t table<br \/>\n\tid\t|\t  name<br \/>\n\t1\t|\t  Apple<\/p>\n<p>* see<br \/>\nhttps:\/\/www.geeksforgeeks.org\/sql-join-set-1-inner-left-right-and-full-joins\/<br \/>\nhttps:\/\/www.w3schools.com\/sql\/sql_join.asp<br \/>\nhttps:\/\/en.wikipedia.org\/wiki\/Join_(SQL)<br \/>\nhttps:\/\/www.tutorialspoint.com\/sql\/sql-using-joins.htm<\/p>\n","protected":false},"excerpt":{"rendered":"<p>CREATE TABLE table_name (col_1_name col_1_type, column_2_name column_2_type&#8230;); e.g. CREATE TABLE items (id INTEGER, name TEXT); add PRIMARY KEY and AUTOINCREMENT keywords to the id field while creating the table, like so: CREATE TABLE items (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT); To automatically increment ids on each insertion, no need to define id when inserting [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[1],"tags":[],"class_list":["post-1003","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>SQL Cheatsheet - s-oneill.com<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/s-oneill.com\/sov02\/sql-cheatsheet\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"SQL Cheatsheet - s-oneill.com\" \/>\n<meta property=\"og:description\" content=\"CREATE TABLE table_name (col_1_name col_1_type, column_2_name column_2_type&#8230;); e.g. CREATE TABLE items (id INTEGER, name TEXT); add PRIMARY KEY and AUTOINCREMENT keywords to the id field while creating the table, like so: CREATE TABLE items (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT); To automatically increment ids on each insertion, no need to define id when inserting [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/s-oneill.com\/sov02\/sql-cheatsheet\/\" \/>\n<meta property=\"og:site_name\" content=\"s-oneill.com\" \/>\n<meta property=\"article:published_time\" content=\"2023-11-18T23:15:34+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-11-18T23:19:49+00:00\" \/>\n<meta name=\"author\" content=\"Me(sean)\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Me(sean)\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/s-oneill.com\/sov02\/sql-cheatsheet\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/s-oneill.com\/sov02\/sql-cheatsheet\/\"},\"author\":{\"name\":\"Me(sean)\",\"@id\":\"https:\/\/s-oneill.com\/sov02\/#\/schema\/person\/ab11148c6ea273be80dddd8baec1a545\"},\"headline\":\"SQL Cheatsheet\",\"datePublished\":\"2023-11-18T23:15:34+00:00\",\"dateModified\":\"2023-11-18T23:19:49+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/s-oneill.com\/sov02\/sql-cheatsheet\/\"},\"wordCount\":801,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/s-oneill.com\/sov02\/#\/schema\/person\/a9217b5797251a243dfd504d7ad7d00a\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/s-oneill.com\/sov02\/sql-cheatsheet\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/s-oneill.com\/sov02\/sql-cheatsheet\/\",\"url\":\"https:\/\/s-oneill.com\/sov02\/sql-cheatsheet\/\",\"name\":\"SQL Cheatsheet - s-oneill.com\",\"isPartOf\":{\"@id\":\"https:\/\/s-oneill.com\/sov02\/#website\"},\"datePublished\":\"2023-11-18T23:15:34+00:00\",\"dateModified\":\"2023-11-18T23:19:49+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/s-oneill.com\/sov02\/sql-cheatsheet\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/s-oneill.com\/sov02\/sql-cheatsheet\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/s-oneill.com\/sov02\/sql-cheatsheet\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/s-oneill.com\/sov02\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"SQL Cheatsheet\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/s-oneill.com\/sov02\/#website\",\"url\":\"https:\/\/s-oneill.com\/sov02\/\",\"name\":\"s-oneill.com\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/s-oneill.com\/sov02\/#\/schema\/person\/a9217b5797251a243dfd504d7ad7d00a\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/s-oneill.com\/sov02\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\/\/s-oneill.com\/sov02\/#\/schema\/person\/a9217b5797251a243dfd504d7ad7d00a\",\"name\":\"sean o\",\"logo\":{\"@id\":\"https:\/\/s-oneill.com\/sov02\/#\/schema\/person\/image\/\"},\"description\":\"Web dev over 15 years.\",\"sameAs\":[\"http:\/\/s-oneill.com\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/s-oneill.com\/sov02\/#\/schema\/person\/ab11148c6ea273be80dddd8baec1a545\",\"name\":\"Me(sean)\",\"url\":\"https:\/\/s-oneill.com\/sov02\/author\/user01\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"SQL Cheatsheet - s-oneill.com","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/s-oneill.com\/sov02\/sql-cheatsheet\/","og_locale":"en_US","og_type":"article","og_title":"SQL Cheatsheet - s-oneill.com","og_description":"CREATE TABLE table_name (col_1_name col_1_type, column_2_name column_2_type&#8230;); e.g. CREATE TABLE items (id INTEGER, name TEXT); add PRIMARY KEY and AUTOINCREMENT keywords to the id field while creating the table, like so: CREATE TABLE items (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT); To automatically increment ids on each insertion, no need to define id when inserting [&hellip;]","og_url":"https:\/\/s-oneill.com\/sov02\/sql-cheatsheet\/","og_site_name":"s-oneill.com","article_published_time":"2023-11-18T23:15:34+00:00","article_modified_time":"2023-11-18T23:19:49+00:00","author":"Me(sean)","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Me(sean)","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/s-oneill.com\/sov02\/sql-cheatsheet\/#article","isPartOf":{"@id":"https:\/\/s-oneill.com\/sov02\/sql-cheatsheet\/"},"author":{"name":"Me(sean)","@id":"https:\/\/s-oneill.com\/sov02\/#\/schema\/person\/ab11148c6ea273be80dddd8baec1a545"},"headline":"SQL Cheatsheet","datePublished":"2023-11-18T23:15:34+00:00","dateModified":"2023-11-18T23:19:49+00:00","mainEntityOfPage":{"@id":"https:\/\/s-oneill.com\/sov02\/sql-cheatsheet\/"},"wordCount":801,"commentCount":0,"publisher":{"@id":"https:\/\/s-oneill.com\/sov02\/#\/schema\/person\/a9217b5797251a243dfd504d7ad7d00a"},"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/s-oneill.com\/sov02\/sql-cheatsheet\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/s-oneill.com\/sov02\/sql-cheatsheet\/","url":"https:\/\/s-oneill.com\/sov02\/sql-cheatsheet\/","name":"SQL Cheatsheet - s-oneill.com","isPartOf":{"@id":"https:\/\/s-oneill.com\/sov02\/#website"},"datePublished":"2023-11-18T23:15:34+00:00","dateModified":"2023-11-18T23:19:49+00:00","breadcrumb":{"@id":"https:\/\/s-oneill.com\/sov02\/sql-cheatsheet\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/s-oneill.com\/sov02\/sql-cheatsheet\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/s-oneill.com\/sov02\/sql-cheatsheet\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/s-oneill.com\/sov02\/"},{"@type":"ListItem","position":2,"name":"SQL Cheatsheet"}]},{"@type":"WebSite","@id":"https:\/\/s-oneill.com\/sov02\/#website","url":"https:\/\/s-oneill.com\/sov02\/","name":"s-oneill.com","description":"","publisher":{"@id":"https:\/\/s-oneill.com\/sov02\/#\/schema\/person\/a9217b5797251a243dfd504d7ad7d00a"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/s-oneill.com\/sov02\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/s-oneill.com\/sov02\/#\/schema\/person\/a9217b5797251a243dfd504d7ad7d00a","name":"sean o","logo":{"@id":"https:\/\/s-oneill.com\/sov02\/#\/schema\/person\/image\/"},"description":"Web dev over 15 years.","sameAs":["http:\/\/s-oneill.com"]},{"@type":"Person","@id":"https:\/\/s-oneill.com\/sov02\/#\/schema\/person\/ab11148c6ea273be80dddd8baec1a545","name":"Me(sean)","url":"https:\/\/s-oneill.com\/sov02\/author\/user01\/"}]}},"_links":{"self":[{"href":"https:\/\/s-oneill.com\/sov02\/wp-json\/wp\/v2\/posts\/1003","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/s-oneill.com\/sov02\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/s-oneill.com\/sov02\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/s-oneill.com\/sov02\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/s-oneill.com\/sov02\/wp-json\/wp\/v2\/comments?post=1003"}],"version-history":[{"count":6,"href":"https:\/\/s-oneill.com\/sov02\/wp-json\/wp\/v2\/posts\/1003\/revisions"}],"predecessor-version":[{"id":1009,"href":"https:\/\/s-oneill.com\/sov02\/wp-json\/wp\/v2\/posts\/1003\/revisions\/1009"}],"wp:attachment":[{"href":"https:\/\/s-oneill.com\/sov02\/wp-json\/wp\/v2\/media?parent=1003"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/s-oneill.com\/sov02\/wp-json\/wp\/v2\/categories?post=1003"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/s-oneill.com\/sov02\/wp-json\/wp\/v2\/tags?post=1003"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}