├── README.md
├── markdown_basics
└── cheatsheet.md
├── modifying_data_with_sql
└── cheatsheet.md
├── querying_relational_databases
└── cheatsheet.md
├── reporting_with_sql
└── cheatsheet.md
└── sql_basics
└── cheatsheet.md
/README.md:
--------------------------------------------------------------------------------
1 | # Cheat Sheets
2 |
3 | A collection of cheat sheets for Treehouse Courses
4 |
5 |
6 | ## Databases
7 |
8 | * [SQL Basics](sql_basics/cheatsheet.md)
9 | * [Modifying Data With SQL](modifying_data_with_sql/cheatsheet.md)
10 | * [Reporting with SQL](reporting_with_sql/cheatsheet.md)
11 | * [Querying Relational Databases](querying_relational_databases/cheatsheet.md)
12 | * [Markdown Basics](markdown_basics/cheatsheet.md)
--------------------------------------------------------------------------------
/markdown_basics/cheatsheet.md:
--------------------------------------------------------------------------------
1 | # Markdown Basics
2 |
3 | ## Headlines, Paragraphs, and Basic Formatting
4 |
5 | ### Headlines
6 |
7 | Type a single hash (AKA pound symbol) and a space to create the largest or first-level heading. A second-level heading uses two hashes next to each other followed by a space and text. The rest of the headline levels just add another hash.
8 |
9 | #### Heading Level 4
10 | ##### Heading Level 5
11 | ###### Heading Level 6
12 |
13 | ### Paragraphs and Line Breaks
14 |
15 | We create paragraphs by typing the way we would in any other program. Just hit return twice to start another paragraph.
16 |
17 | Where you see empty space between blocks of text in your Markdown document, you will see empty space separating those blocks of text in your formatted HTML document.
18 |
19 | #### Line Breaks
20 |
21 | You don’t always want that space that appears between one line of text and another: for example, lines of poetry or song lyrics don't have spaces between them. To add just a line break without a space, type two spaces at the end of a line, then press return once.
22 |
23 | I love you without knowing how, or when, or
24 | from where
25 | I love you directly without problems or pride:
26 | I love you like this because I don't know any
27 | other way to love
28 |
29 | Neruda, Pablo. "Sonnet 17" The Poetry of Pablo Neruda, edited by Ilan Stavans, translated by Mark Eisner, Farrar, Straus and Giroux, 2005, p. 514.
30 |
31 | ### Emphasis and Bolding
32 |
33 | #### Italics
34 |
35 | Emphasis can be added with either the asterisk or the underscore characters.
36 |
37 | This *works*, and this _works_ too
38 |
39 | #### Bolding
40 |
41 | Bolding is easy too. Just add an extra asterisk or underscore.
42 |
43 | This **works**, and this __works__ too
44 |
45 | #### Bolding and Emphasis Together
46 |
47 | You can even bold and italicize text like ***this*** or ___this___
48 |
49 | ### Blockquotes
50 |
51 | A blockquote sets text apart from the rest of the document. It indicates that the text is quoted from another source.
52 |
53 | You format a blockquote using the greater than symbol. If you want a blockquote to span multiple paragraphs, add the greater than symbol to the line between paragraphs too.
54 |
55 | > Markdown is intended to be as easy-to-read and easy-to-write as is feasible.
56 | >
57 | > Readability, however, is emphasized above all else. A Markdown-formatted document should be publishable as-is, as plain text, without looking like it’s been marked up with tags or formatting instructions. — [John Gruber](https://daringfireball.net/projects/markdown/ "The Creator of Markdown")
58 |
59 | ### Horizontal Rule
60 |
61 | OK, that’s a good start. We can separate this from our next section with a horizontal rule, which is just a line used to separate sections of a document.
62 |
63 | You can use three or more underscores, asterisks, or hyphens. I prefer hyphens.
64 |
65 | ___
66 |
67 | ***
68 |
69 | ---
70 |
71 | ## Lists
72 |
73 | You can write both numbered and bulleted lists with Markdown.
74 |
75 | ### Numbered Lists
76 |
77 | You create numbered lists like you do in other writing programs. Type the number, a period, a space, and the item label.
78 |
79 | 1. Item One
80 | 2. Item Two
81 |
82 | To nest an item, indent it with a tab or at least two spaces beneath the item above it.
83 |
84 | 1. Item One
85 | 1. Nested Level Two
86 | 2. Nested Level Two
87 | 1. Nested Level Three
88 | 2. Nested Level Three
89 |
90 | #### Bulleted Lists
91 |
92 | Bulleted lists work like numbered lists, but you use the asterisk character, a space, and no period.
93 |
94 | * Item One
95 | * Item Two
96 |
97 | You can nest bulleted items too. We just indent our item below another item like we did with our numbered list.
98 |
99 | * Item One
100 | * Nested Item One
101 | * Nested Item Two
102 |
103 | ##### Asterisk Gotchas
104 |
105 | Because the asterisk is used for bolding, italicizing, and creating bulleted lists, it's easy to make mistakes. Check your spacing, and use a preview to ensure you are formatting text the way you intend.
106 |
107 | *Italicized Item*
108 | *Not Formatted
109 | * Bulleted Item
110 |
111 | What if you do want a bulleted item that is bold and italicized? Type an asterisk and a space. This will create the bulleted item. Then use two asterisks for the bolding and a third for the italicizing on both sides of the text.
112 |
113 | * ***Bold Italicized Bulleted Item***
114 |
115 | #### Mixed Lists
116 |
117 | You can mix the two list styles too. Just use the numbers or asterisks where you want them.
118 |
119 | 1. Item One
120 | * Nested Item
121 | * Nested Item
122 | 2. Item Two
123 | * Nested Item
124 | * Nested Item
125 | 1. Deep Nested Item One
126 | 2. Deep Nested Item Two
127 | * Super Deep Nested Item
128 | * Super Deep Nested Item
129 |
130 | ---
131 |
132 | ## Code
133 |
134 | We format code using the backtick character. The backtick is on the same key as the tilde on a U.S. English keyboard, which is usually to the left of the number 1 and above the tab key.
135 |
136 | You can use a single backtick to create inline code. For example, you may type something like this:
137 |
138 | To install the latest version of NPM, you can type, `npm install npm@latest -g`
139 |
140 | For multiple lines of code, you'll usually create a code block. Instead of one backtick, use three backticks above and below the code block. Some sites and editors also support syntax highlighting by language. Add it by typing the name of the coding language immediately after the top three backticks.
141 |
142 | ```JavaScript
143 | let exampleFunction = () => {
144 | let foo = 'foo';
145 | let bar = 'bar';
146 |
147 | return foo + bar;
148 | }
149 | ```
150 |
151 | ---
152 |
153 | ## Links
154 |
155 | Markdown provides a syntax for links that’s easy to remember. First, type the text you want to appear on the page in square brackets, then add the link in parenthesis. If I want to link to Treehouse, I would type
156 |
157 | [Treehouse](https://teamtreehouse.com/)
158 |
159 | You also have the option to provide a title, which appears when you hover the mouse cursor over the link. Just type a space after the url and close the label in quotes. Both the url and the title should be inside the parenthesis.
160 |
161 | [Treehouse](https://teamtreehouse.com/ "Treehouse link with a title")
162 |
163 | What if you want to link to a reference at the bottom of a section or page like a footnote? Start with the text in square brackets, but don’t add the parenthesis. Instead, add a number to reference in another set of square brackets.
164 |
165 | [Treehouse][1]
166 |
167 | Now at another place in the document, add the reference number in square brackets and follow it with a colon, a space, and the link url. You can add an optional title with a space and quotes to this type of link too. Reference links don’t require parenthesis.
168 |
169 | [1]: https://teamtreehouse.com "Treehouse Reference Link"
170 |
171 | ---
172 |
173 | ## Images
174 |
175 | Type a label for the image in square brackets. On the Web we call this alt text, because it will be displayed as an alternate if the image cannot be shown for any reason. I have an image of kittens, so I’ll write, “Kittens” in square brackets and follow that with the url for the image in parenthesis.
176 |
177 | That creates a link for the kitten image, but I want to display the image. All I have to do is add an exclamation mark in front of the square brackets.
178 |
179 | 
180 |
181 | What if I want the image to link to something too? Just add square brackets around your whole image code. At the end of the new square brackets, put the link url in parenthesis.
182 |
183 | [](https://placekitten.com)
184 |
185 | Images can have titles like links too. You add them the same way. After the image url, add a space and put the title in quotes.
186 |
187 | [](https://placekitten.com)
188 |
189 | ---
190 |
191 | ## Conclusion
192 |
193 | That's it for this document. You now have a handy Markdown reference. Feel free to explore more information about Markdown and its many flavors, but this is a great start. The more you use Markdown the more natural it will feel.
194 |
195 | Thanks for learning Markdown with [Treehouse](https://teamtreehouse.com "Treehouse")
196 |
--------------------------------------------------------------------------------
/modifying_data_with_sql/cheatsheet.md:
--------------------------------------------------------------------------------
1 | # Modifying Data With SQL Cheatsheet
2 |
3 | ## Adding a Row to a Table
4 |
5 |
6 | Inserting a single row:
7 |
8 | ```
9 | INSERT INTO
VALUES (, , ...);
10 | ```
11 |
12 | This will insert values in the order of the columns prescribed in the schema.
13 |
14 | Examples:
15 |
16 | ```
17 | INSERT INTO users VALUES (1, "chalkers", "Andrew", "Chalkley");
18 | INSERT INTO users VALUES (2, "ScRiPtKiDdIe", "Kenneth", "Love");
19 |
20 | INSERT INTO movies VALUES (3, "Starman", "Science Fiction", 1984);
21 | INSERT INTO movies VALUES (4, "Moulin Rouge!", "Musical", 2001);
22 | ```
23 |
24 | Inserting a single row with values in any order:
25 |
26 | ```
27 | INSERT INTO (, ) VALUES (, );
28 | INSERT INTO (, ) VALUES (, );
29 | ```
30 |
31 | Examples:
32 |
33 | ```
34 | INSERT INTO users (username, first_name, last_name) VALUES ("chalkers", "Andrew", "Chalkley");
35 | INSERT INTO users (first_name, last_name, username) VALUES ("Kenneth", "Love", "ScRiPtKiDdIe");
36 |
37 | INSERT INTO movies (title, genre, year_released) VALUES ("Starman", "Science Fiction", 1984);
38 | INSERT INTO movies (title, year_released, genre) VALUES ("Moulin Rouge!", 2001, "Musical");
39 | ```
40 |
41 |
42 | ## Adding Multiple Rows to a Table
43 |
44 | Inserting multiple rows in a single statement:
45 |
46 | ```
47 | INSERT INTO (, , ...)
48 | VALUES
49 | (, , ...),
50 | (, , ...),
51 | (, , ...);
52 | ```
53 |
54 | Examples:
55 |
56 | ```
57 | INSERT INTO users (username, first_name, last_name)
58 | VALUES
59 | ("chalkers", "Andrew", "Chalkley"),
60 | ("ScRiPtKiDdIe", "Kenneth", "Love");
61 |
62 | INSERT INTO movies (title, genre, year_released)
63 | VALUES
64 | ("Starman", "Science Fiction", 1984),
65 | ("Moulin Rouge!", "Musical", 2001);
66 | ```
67 |
68 | ## Updating All Rows in a Table
69 |
70 | An update statement for all rows:
71 |
72 | ```
73 | UPDATE SET = ;
74 | ```
75 |
76 | The `=` sign is different from an equality operator from a `WHERE` condition. It's an _assignment operator_ because you're assigning a new value to something.
77 |
78 | Examples:
79 |
80 | ```
81 | UPDATE users SET password = "thisisabadidea";
82 | UPDATE products SET price = 2.99;
83 | ```
84 |
85 | Update multiple columns in all rows:
86 |
87 | ```
88 | UPDATE SET = , = ;
89 | ```
90 |
91 | Examples:
92 |
93 | ```
94 | UPDATE users SET first_name = "Anony", last_name = "Moose";
95 | UPDATE products SET stock_count = 0, price = 0;
96 | ```
97 |
98 | ## Updating Specific Rows
99 |
100 | An update statement for specific rows:
101 |
102 | ```
103 | UPDATE SET = WHERE ;
104 | ```
105 | Examples:
106 |
107 | ```
108 | UPDATE users SET password = "thisisabadidea" WHERE id = 3;
109 | UPDATE blog_posts SET view_count = 1923 WHERE title = "SQL is Awesome";
110 | ```
111 |
112 | Update multiple columns for specific rows:
113 |
114 | ```
115 | UPDATE SET = , = WHERE ;
116 | ```
117 |
118 | Examples:
119 |
120 | ```
121 | UPDATE users SET entry_url = "/home", last_login = "2016-01-05" WHERE id = 329;
122 | UPDATE products SET status = "SOLD OUT", availability = "In 1 Week" WHERE stock_count = 0;
123 | ```
124 |
125 | ## Removing Data from All Rows in a Table
126 |
127 | To delete all rows from a table:
128 |
129 | ```
130 | DELETE FROM ;
131 | ```
132 |
133 | Examples:
134 |
135 | ```
136 | DELETE FROM logs;
137 | DELETE FROM users;
138 | DELETE FROM products;
139 | ```
140 |
141 |
142 | ## Removing Specific Rows
143 |
144 | To delete specific rows from a table:
145 |
146 | ```
147 | DELETE FROM WHERE ;
148 | ```
149 |
150 | Examples:
151 |
152 | ```
153 | DELETE FROM users WHERE email = "andrew@teamtreehouse.com";
154 | DELETE FROM movies WHERE genre = "Musical";
155 | DELETE FROM products WHERE stock_count = 0;
156 | ```
157 |
158 |
159 | ## Transactions
160 |
161 |
162 | Switch autocommit off and begin a transaction:
163 |
164 | ```
165 | BEGIN TRANSACTION;
166 | ```
167 |
168 | Or simply:
169 |
170 | ```
171 | BEGIN;
172 | ```
173 |
174 | To save all results of the statements after the start of the transaction to disk:
175 |
176 | ```
177 | COMMIT;
178 | ```
179 |
180 | To reset the state of the database to before the beginning of the transaction:
181 |
182 | ```
183 | ROLLBACK;
184 | ````
185 |
--------------------------------------------------------------------------------
/querying_relational_databases/cheatsheet.md:
--------------------------------------------------------------------------------
1 | # Querying Relational Databases Cheatsheet
2 |
3 | ## SQL JOINs
4 |
5 | JOINs merge related data from multiple tables together in to result set.
6 |
7 | The two most common types of joins are:
8 |
9 | * INNER JOIN
10 | * OUTER JOIN
11 |
12 |
13 | ### INNER JOINs
14 |
15 | INNER JOINs return rows that match from both tables.
16 |
17 | ```
18 | SELECT FROM
19 | INNER JOIN ON . = .;
20 |
21 |
22 | SELECT FROM AS
23 | INNER JOIN AS ON . = .;
24 |
25 | ```
26 |
27 | Examples:
28 |
29 | ```
30 | SELECT product_name, category FROM products
31 | INNER JOIN product_categories ON products.category_id = product_categories.id;
32 | SELECT products.product_name, product_categories.category FROM products
33 | INNER JOIN product_categories ON products.category_id = product_categories.id;
34 | SELECT p.product_name, c.category FROM products AS p
35 | INNER JOIN product_categories AS c ON p.category_id = c.id;
36 | ```
37 |
38 | INNER JOINing multiple tables:
39 |
40 | ```
41 | SELECT FROM
42 | INNER JOIN ON . = .
43 | INNER JOIN ON . = .;
44 | ```
45 |
46 | Examples:
47 |
48 | ```
49 | SELECT users.full_name, sales.amount, products.name FROM sales
50 | INNER JOIN users ON sales.user_id = users.id
51 | INNER JOIN products ON sales.product_id = products.id;
52 | ```
53 |
54 | ### OUTER JOINs
55 |
56 | There are 3 types of OUTER JOINs:
57 |
58 | * LEFT OUTER JOIN - JOINs all matching data and all non-matching rows from the _left_ table in the query
59 | * RIGHT OUTER JOIN - JOINs all matching data and all non-matching rows from the _right_ table in the query
60 | * FULL OUTER JOIN - JOINs all matching data and then all non-matching rows from both tables.
61 |
62 | ```
63 | SELECT FROM
64 | LEFT OUTER JOIN ON . = .;
65 |
66 |
67 | SELECT FROM AS
68 | LEFT OUTER JOIN AS
69 | ON . = .;
70 |
71 | ```
72 |
73 | #### Example
74 |
75 | If you wanted to get the product count for every category,
76 | even categories without products, an `OUTER JOIN` is the best solution.
77 | The following two examples will yield the same results, however one is a `LEFT OUTER JOIN` and one is a `RIGHT OUTER JOIN`.
78 |
79 | ```
80 | SELECT categories.name, COUNT(products.id) AS "Product Count" FROM categories
81 | LEFT OUTER JOIN products ON categories.id = products.category_id;
82 |
83 | SELECT categories.name, COUNT(products.id) AS "Products Count" FROM products
84 | RIGHT OUTER JOIN categories ON categories.id = products.category_id;
85 | ```
86 |
87 | ## Set Operations
88 |
89 |
90 | Set operations merge data in to one set based on column definitions and the data contained within each column.
91 |
92 | The four set operations are:
93 |
94 | * UNION
95 | * UNION ALL
96 | * INTERSECT
97 | * EXCEPT
98 |
99 | The number of columns need to match. If number of columns don't match it'll result in an error.
100 |
101 | ```
102 |
103 | SELECT FROM SELECT FROM ;
104 | SELECT , FROM SELECT , FROM ;
105 | ```
106 |
107 | ### UNION Examples
108 |
109 | Unions return all distinct values from both data sets with no duplicates.
110 |
111 | Get a list of unique restaurants from both north and south malls.
112 |
113 | ```
114 | SELECT store FROM mall_south WHERE type = "restaurant"
115 | UNION
116 | SELECT store FROM mall_north WHERE type = "restaurant";
117 | ```
118 |
119 | Get a list of unique classes taught in two schools. Order them by their class name.
120 |
121 | ```
122 | SELECT evening_class FROM school_1 UNION SELECT evening_class FROM school_2
123 | ORDER BY evening_class ASC;
124 | ```
125 |
126 | ### UNION ALL
127 |
128 | Union all returns all values from both data sets – with duplicates.
129 |
130 | Get a list of all names for boys and girls and order them by name.
131 |
132 | ```
133 | SELECT boy_name AS name FROM boy_baby_names
134 | UNION ALL
135 | SELECT girl_name AS name FROM girl_baby_names
136 | ORDER by name;
137 | ```
138 |
139 | ### INTERSECT
140 |
141 | Returns only values that are in both data sets.
142 |
143 | Get list of classes offered in both schools.
144 |
145 | ```
146 | SELECT evening_class FROM school_1 INTERSECT SELECT evening_class FROM school_2
147 | ORDER BY evening_class ASC;
148 | ```
149 | Get list of restaurants at both mall locations.
150 |
151 | ```
152 | SELECT store FROM mall_south WHERE type = "restaurant"
153 | INTERSECT
154 | SELECT store FROM mall_north WHERE type = "restaurant";
155 | ```
156 |
157 | ### EXCEPT
158 |
159 | Returns data from the first data set that's not in the second.
160 |
161 | Get a list of local stores in a mall.
162 |
163 | ```
164 | SELECT store FROM mall
165 | EXCEPT
166 | SELECT store FROM all_stores WHERE type = "national"
167 | ```
168 |
169 |
170 | ## Subqueries
171 |
172 | Subqueries are queries within queries. A subquery can also be called an _inner_ query with the "parent" query being called the _outer_ query.
173 |
174 | There are two main ways to use a subquery:
175 |
176 | 1. In an `IN` condition
177 | 2. As a derived or temporary table
178 |
179 | A subquery in an `IN` condition must only have one column.
180 |
181 | ```
182 | SELECT FROM WHERE . IN ();
183 | SELECT FROM
184 | WHERE . IN (SELECT FROM WHERE );
185 | ```
186 |
187 | Examples:
188 |
189 | Get a list of user's names and emails for users who have spent over 100 dollars in a single transaction.
190 |
191 | ```
192 | SELECT name, email FROM users
193 | WHERE id IN (SELECT DISTINCT(user_id) FROM sales WHERE saleAmount > 100);
194 |
195 | // OR
196 |
197 | SELECT name, email FROM users
198 | INNER JOIN (SELECT DISTINCT(user_id) FROM sales WHERE saleAmount > 100) AS best_customers
199 | ON users.id = best_customers.user_id;
200 | ```
201 |
202 | Get a list of user's names and emails for users who have spent over 1000 dollars in total.
203 |
204 | ```
205 | SELECT name, email FROM users WHERE id IN (SELECT user_id FROM sales WHERE SUM(saleAmount) > 1000 GROUP BY user_id);
206 |
207 | // OR
208 |
209 | SELECT name, email, total FROM users
210 | INNER JOIN (SELECT user_id, SUM(saleAmount) AS total FROM sales WHERE total > 1000 GROUP BY user_id) AS ultimate_customers
211 | ON users.id = ultimate_customers.user_id;
212 | ```
213 |
--------------------------------------------------------------------------------
/reporting_with_sql/cheatsheet.md:
--------------------------------------------------------------------------------
1 | # Reporting with SQL Cheatsheet
2 |
3 | ## Ordering Columns
4 |
5 | Ordering by a single column criteria:
6 |
7 | ```
8 | SELECT * FROM ORDER BY [ASC|DESC];
9 |
10 | ```
11 |
12 | `ASC` is used to order results in ascending order.
13 |
14 | `DESC` is used to order results in descending order.
15 |
16 | Examples:
17 |
18 | ```
19 | SELECT * FROM books ORDER BY title ASC;
20 | SELECT * FROM products WHERE name = "Sonic T-Shirt" ORDER BY stock_count DESC;
21 | SELECT * FROM users ORDER BY signed_up_on DESC;
22 | SELECT * FROM countries ORDER BY population DESC;
23 | ```
24 |
25 | Ordering by multiple column criteria:
26 |
27 | ```
28 | SELECT * FROM ORDER BY [ASC|DESC],
29 | [ASC|DESC],
30 | ...,
31 | [ASC|DESC];
32 | ```
33 |
34 | Ordering is prioritized left to right.
35 |
36 | Examples:
37 |
38 | ```
39 | SELECT * FROM books ORDER BY genre ASC,
40 | title ASC;
41 |
42 | SELECT * FROM books ORDER BY genre ASC,
43 | year_published DESC;
44 |
45 | SELECT * FROM users WHERE email LIKE "%@gmail.com"
46 | ORDER BY last_name ASC,
47 | first_name ASC;
48 | ```
49 |
50 | ## Limiting Results
51 |
52 | ### SQLite, PostgreSQL and MySQL
53 |
54 | To limit the number of results returned, use the `LIMIT` keyword.
55 |
56 | ```
57 | SELECT FROM LIMIT <# of rows>;
58 | ```
59 |
60 | ### MS SQL
61 |
62 | To limit the number of results returned, use the `TOP` keyword.
63 |
64 | ```
65 | SELECT TOP <# of rows> FROM ;
66 | ```
67 |
68 | ### Oracle
69 | To limit the number of results returned, use the `ROWNUM` keyword in a `WHERE` clause.
70 |
71 | ```
72 | SELECT FROM WHERE ROWNUM <= <# of rows>;
73 | ```
74 |
75 |
76 | ## Paging Through Results
77 |
78 | ### SQLite, PostgreSQL and MySQL
79 |
80 | To page through results you can either use the `OFFSET` keyword in conjunction with the `LIMIT` keyword or just with LIMIT alone.
81 |
82 | ```
83 | SELECT FROM LIMIT <# of rows> OFFSET ;
84 | SELECT FROM LIMIT , <# of rows>;
85 | ```
86 |
87 | ### MS SQL and Oracle
88 |
89 | To page through results you can either use the `OFFSET` keyword in conjunction with the `FETCH` keyword. Cannot be used with `TOP`.
90 |
91 | ```
92 | SELECT FROM OFFSET ROWS FETCH NEXT <# of rows> ROWS ONLY;
93 | ```
94 |
95 | ## Syntax definitions
96 |
97 | * **Keywords**: Commands issued to a database. The data presented in queries is unaltered.
98 |
99 | * **Operators**: Performs comparisons and simple manipulation
100 |
101 | * **Functions**: Presents data differently through more complex manipulation
102 |
103 | * **Arguments** or **Parameters**: Values passed in to functions.
104 |
105 | A function looks like:
106 |
107 | ```
108 | ()
109 | ```
110 |
111 | Examples:
112 |
113 | ```
114 | SELECT UPPER("Andrew Chalkley");
115 | SELECT UPPER(name) FROM passport_holders;
116 | ```
117 |
118 | ## Concatenating Strings
119 |
120 | ### SQLite, PostgreSQL and Oracle
121 |
122 | Use the concatenation operator `||`.
123 |
124 | ```
125 | SELECT || || FROM ;
126 | ```
127 |
128 | ### MS SQL
129 |
130 | Use the concatenation operator `+`.
131 |
132 | ```
133 | SELECT + + FROM ;
134 | ```
135 |
136 |
137 | ### MySQL, PostgreSQL and MS SQL
138 |
139 | Use the `CONCAT()` function.
140 |
141 | ```
142 | SELECT CONCAT(, , ) FROM ;
143 | ```
144 |
145 | ## Finding Length of Strings
146 |
147 | To obtain the length of a value or column use the `LENGTH()` function.
148 |
149 | ```
150 | SELECT LENGTH() FROM ;
151 | ```
152 |
153 | ## Changing the Case of Strings
154 |
155 | Use the `UPPER()` function to uppercase text.
156 |
157 | ```
158 | SELECT UPPER() FROM ;
159 | ```
160 |
161 | Use the `LOWER()` function to lowercase text.
162 |
163 | ```
164 | SELECT LOWER() FROM ;
165 | ```
166 |
167 | ## Create Excerpts with Substring
168 |
169 | To create smaller strings from larger piece of text you can use the `SUBSTR()` funciton or the substring function.
170 |
171 |
172 | ```
173 | SELECT SUBSTR(, , ) FROM ;
174 | ```
175 | * **\** : Specifies where to start in the string
176 |
177 | - if is 0 (zero), then it is treated as 1.
178 |
179 | - if is positive, then the function counts from the beginning of string to find the first character.
180 |
181 | - if is negative, then the function counts backward from the end of string.
182 |
183 | * **\** : length of the desired substring
184 |
185 | ```
186 | SELECT SUBSTR('abcdefg', 3,4);
187 | ```
188 | OUTPUT: cdef
189 |
190 | ```
191 | SELECT SUBSTR('abcdefg', -5,4);
192 | ```
193 | OUTPUT: cdef
194 |
195 | ## Replacing Portions of Text
196 |
197 | To replace piece of strings of text in a larger body of text you can use the `REPLACE()` function.
198 |
199 | ```
200 | SELECT REPLACE(, , ) FROM ;
201 | ```
202 |
203 | ## Counting Results
204 |
205 | To count rows you can use the `COUNT()` function.
206 |
207 | ```
208 | SELECT COUNT(*) FROM ;
209 | ```
210 |
211 | To count unique entries use the `DISTINCT` keyword too:
212 |
213 | ```
214 | SELECT COUNT(DISTINCT ) FROM ;
215 | ```
216 |
217 | To count aggregated rows with common values use the `GROUP BY` keywords:
218 |
219 | ```
220 | SELECT COUNT() FROM GROUP BY ;
221 | ```
222 |
223 | ## Obtaining Totals
224 |
225 | To total up numeric columns use the `SUM()` function.
226 |
227 | ```
228 | SELECT SUM(;
229 | SELECT SUM( FROM
230 | GROUP BY
231 | HAVING ;
232 | ```
233 |
234 | ## Calculating Averages
235 |
236 | To get the average value of a numeric column use the `AVG()` function.
237 |
238 | ```
239 | SELECT AVG() FROM ;
240 | SELECT AVG() FROM GROUP BY ;
241 | ```
242 |
243 | ## Finding the Maximum and Minimum Values
244 |
245 | To get the maximum value of a numeric column use the `MAX()` function.
246 |
247 | ```
248 | SELECT MAX() FROM ;
249 | SELECT MAX() FROM GROUP BY ;
250 | ```
251 |
252 | To get the minimum value of a numeric column use the `MIN()` function.
253 |
254 | ```
255 | SELECT MIN() FROM ;
256 | SELECT MIN() FROM GROUP BY ;
257 | ```
258 |
259 | ## Mathematical Operators
260 |
261 | * `*` Multiply
262 | * `/` Divide
263 | * `+` Add
264 | * `-` Subtract
265 |
266 | ```
267 | SELECT FROM ;
268 | ```
269 |
270 | ## Up-to-the-Minute Dates and Times
271 |
272 | ### SQLite
273 |
274 | To get the current date use: `DATE("now")`
275 |
276 | To get the current time use: `TIME("now")`
277 |
278 | To get the current date time: `DATETIME("NOW")`
279 |
280 | ### MS SQL
281 |
282 | To get the current date use: `CONVERT(date, GETDATE())`
283 |
284 | To get the current time use: `CONVERT(time, GETDATE())`
285 |
286 | To get the current date time: `GETDATE()`
287 |
288 | ### MySQL
289 |
290 |
291 | To get the current date use: `CURDATE()`
292 |
293 | To get the current time use: `CURTIME()`
294 |
295 | To get the current date time: `NOW()`
296 |
297 | ### Oracle and PostgreSQL
298 |
299 | To get the current date use: `CURRENT_DATE`
300 |
301 | To get the current time use: `CURRENT_TIME`
302 |
303 | To get the current date time: `CURRENT_TIMESTAMP`
304 |
305 | ## Calculating Dates
306 |
307 | See documentation sites:
308 |
309 | * [SQLite](https://www.sqlite.org/lang_datefunc.html)
310 | * [MS SQL](https://msdn.microsoft.com/en-us/library/ms186724.aspx#ModifyDateandTimeValues)
311 | * [PostgreSQL](http://www.postgresql.org/docs/9.1/static/functions-datetime.html)
312 | * [MySQL](https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html)
313 | * [Oracle](https://docs.oracle.com/cd/E17952_01/refman-5.0-en/date-calculations.html)
314 |
315 | ## Formatting Dates
316 |
317 | See documentation sites:
318 |
319 | * [SQLite](https://www.sqlite.org/lang_datefunc.html)
320 | * [MS SQL](https://msdn.microsoft.com/en-us/library/ms186724.aspx#SetorGetSessionFormatFunctions)
321 | * [PostgreSQL](http://www.postgresql.org/docs/9.1/static/functions-datetime.html)
322 | * [MySQL](https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html)
323 | * [Oracle](https://docs.oracle.com/cd/B28359_01/server.111/b28286/sql_elements004.htm)
324 |
--------------------------------------------------------------------------------
/sql_basics/cheatsheet.md:
--------------------------------------------------------------------------------
1 | # SQL Basics Cheatsheet
2 |
3 | ## Find All Columns and Rows in a Table
4 |
5 |
6 | ```
7 | SELECT * FROM ;
8 |
9 | ```
10 |
11 | The asterisk or star symbol (`*`) means all columns.
12 |
13 | The semi-colon (`;`) terminates the statement like a period in sentence or question mark in a question.
14 |
15 | Examples:
16 |
17 | ```
18 | SELECT * FROM books;
19 | SELECT * FROM products;
20 | SELECT * FROM users;
21 | SELECT * FROM countries;
22 | ```
23 |
24 | ## Retrieving Specific Columns of Information
25 |
26 |
27 | Retrieving a single column:
28 |
29 | ```
30 | SELECT FROM ;
31 | ```
32 |
33 | Examples:
34 |
35 | ```
36 | SELECT email FROM users;
37 | SELECT first_name FROM users;
38 | SELECT name FROM products;
39 | SELECT zip_code FROM addresses;
40 | ```
41 |
42 | Retrieving multiple columns:
43 |
44 | ```
45 | SELECT , , ... FROM ;
46 | ```
47 |
48 | Examples:
49 |
50 | ```
51 | SELECT first_name, last_name FROM customers;
52 | SELECT name, description, price FROM products;
53 | SELECT title, author, isbn, year_released FROM books;
54 | SELECT name, species, legs FROM pets;
55 | ```
56 |
57 | ## Aliasing Column Names
58 |
59 | ```
60 | SELECT AS FROM ;
61 | SELECT FROM ;
62 |
63 | ```
64 |
65 | Examples:
66 |
67 | ```
68 | SELECT username AS Username, first_name AS "First Name" FROM users;
69 | SELECT title AS Title, year AS "Year Released" FROM movies;
70 | SELECT name AS Name, description AS Description, price AS "Current Price" FROM products;
71 | SELECT name Name, description Description, price "Current Price" FROM products;
72 | ```
73 |
74 | ## Finding the Data You Want
75 |
76 | ```
77 | SELECT FROM WHERE ;
78 | ```
79 |
80 | ### Equality Operator
81 |
82 | Find all rows that a given value matches a column's value.
83 |
84 | ```
85 | SELECT FROM WHERE = ;
86 | ```
87 |
88 | Examples:
89 |
90 | ```
91 | SELECT * FROM contacts WHERE first_name = "Andrew";
92 | SELECT first_name, email FROM users WHERE last_name = "Chalkley";
93 | SELECT name AS "Product Name" FROM products WHERE stock_count = 0;
94 | SELECT title "Book Title" FROM books WHERE year_published = 1999;
95 | ```
96 |
97 | ### Inequality Operator
98 |
99 |
100 | Find all rows that a given value doesn't match a column's value.
101 |
102 | ```
103 | SELECT FROM WHERE != ;
104 | SELECT FROM WHERE <> ;
105 | ```
106 |
107 | The not equal to or inequality operator can be written in two ways `!=` and `<>`. The latter is *less* common.
108 |
109 | Examples:
110 |
111 | ```
112 | SELECT * FROM contacts WHERE first_name != "Kenneth";
113 | SELECT first_name, email FROM users WHERE last_name != "L:one";
114 | SELECT name AS "Product Name" FROM products WHERE stock_count != 0;
115 | SELECT title "Book Title" FROM books WHERE year_published != 2015;
116 | ```
117 |
118 | ### Relational Operators
119 |
120 | There are several relational operators you can use:
121 |
122 | * `<` less than
123 | * `<=` less than or equal to
124 | * `>` greater than
125 | * `>=` greater than or equal to
126 |
127 | These are primarily used to compare *numeric* and *date/time* types.
128 |
129 | ```
130 | SELECT FROM WHERE < ;
131 | SELECT FROM WHERE <= ;
132 | SELECT FROM WHERE > ;
133 | SELECT FROM WHERE >= ;
134 | ```
135 |
136 | Examples:
137 |
138 | ```
139 | SELECT first_name, last_name FROM users WHERE date_of_birth < '1998-12-01';
140 | SELECT title AS "Book Title", author AS Author FROM books WHERE year_released <= 2015;
141 | SELECT name, description FROM products WHERE price > 9.99;
142 | SELECT title FROM movies WHERE release_year >= 2000;
143 | ```
144 |
145 | ### More Than One Condition
146 |
147 | You can compare multiple values in a `WHERE` condition. If you want to test that *both* conditions are true use the `AND` keyword, or *either* conditions are true use the `OR` keyword.
148 |
149 | ```
150 | SELECT FROM WHERE AND ...;
151 | SELECT FROM WHERE OR ...;
152 | ```
153 |
154 | Examples:
155 |
156 | ```
157 | SELECT username FROM users WHERE last_name = "Chalkley" AND first_name = "Andrew";
158 | SELECT * FROM products WHERE category = "Games Consoles" AND price < 400;
159 | SELECT * FROM movies WHERE title = "The Matrix" OR title = "The Matrix Reloaded" OR title = "The Matrix Revolutions";
160 | SELECT country FROM countries WHERE population < 1000000 OR population > 100000000;
161 | ```
162 |
163 | ### Searching in a Set of Values
164 |
165 | ```
166 | SELECT FROM WHERE IN (