Repository navigation
Expand file tree
/
Copy pathpractice_queries.sql
More file actions
215 lines (196 loc) · 12.2 KB
/
Copy pathpractice_queries.sql
File metadata and controls
215 lines (196 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
## 1. SQL Basics
1. SELECT — Retrieve data from one or more tables.
2. SELECT \* — Retrieve all columns.
3. SELECT specific columns — Retrieve selected columns only.
4. DISTINCT — Remove duplicate rows from query results.
5. DISTINCT ON — PostgreSQL-specific selection of one row per distinct group.
6. Column aliases (AS) — Assign temporary names to result columns.
7. Table aliases — Assign short names to tables for readability.
8. SELECT expressions — Perform calculations and transformations within a query.
9. SELECT constants — Return literal values without retrieving table data.
10. Arithmetic operators — Addition, subtraction, multiplication, division, and modulo.
## 2. Filtering and Conditional Operators
11. WHERE — Filter rows based on conditions.
12. AND — Combine conditions requiring all to be true.
13. OR — Combine conditions requiring at least one to be true.
14. NOT — Negate a condition.
15. Comparison operators — `=`, `<>`, `!=`, `>`, `<`, `>=`, `<=`.
16. IN — Match values against a specified list.
17. NOT IN — Exclude values in a specified list.
18. BETWEEN — Filter values within an inclusive range.
19. NOT BETWEEN — Exclude values within a range.
20. IS NULL — Find rows containing NULL values.
21. IS NOT NULL — Find rows with non-NULL values.
22. IS DISTINCT FROM — NULL-safe inequality comparison.
23. IS NOT DISTINCT FROM — NULL-safe equality comparison.
24. Parentheses in conditions — Control the evaluation order of AND and OR.
## 3. Wildcards and Pattern Matching
25. LIKE — Case-sensitive pattern matching.
26. NOT LIKE — Exclude matching text patterns.
27. ILIKE — PostgreSQL case-insensitive pattern matching.
28. NOT ILIKE — Exclude patterns regardless of letter case.
29. % wildcard — Match zero or more characters.
30. \_ wildcard — Match exactly one character.
31. LIKE with ESCAPE — Search for literal wildcard characters.
32. SIMILAR TO — SQL regular-expression-style pattern matching.
33. \~ operator — PostgreSQL case-sensitive regular expression.
34. \~ operator\* — PostgreSQL case-insensitive regular expression.
35. !\~ and !\~\* — Negated regular-expression matching.
36. Starts-with, ends-with, contains — Common LIKE and ILIKE pattern techniques.
## 4. Sorting and Limiting Results
37. ORDER BY — Sort query results.
38. ASC — Sort in ascending order.
39. DESC — Sort in descending order.
40. Multiple-column sorting — Sort using several columns.
41. NULLS FIRST — Place NULL values first.
42. NULLS LAST — Place NULL values last.
43. ORDER BY expressions — Sort by computed values.
44. LIMIT — Restrict the number of returned rows.
45. OFFSET — Skip a specified number of rows.
46. LIMIT with OFFSET — Implement pagination.
47. FETCH FIRST / NEXT — Standard SQL row-limiting syntax.
48. FETCH WITH TIES — Include additional rows tied at the result boundary.
49. TOP equivalent — Use LIMIT or FETCH in PostgreSQL because `SELECT TOP` is SQL Server syntax.
50. Top-N per group — Retrieve the highest or lowest ranked records within groups.
## 5. Aggregate Functions
51. COUNT(\*) — Count all rows, including rows containing NULL values.
52. COUNT(column) — Count non-NULL values in a column.
53. COUNT(DISTINCT column) — Count unique non-NULL values.
54. SUM() — Calculate the total of numeric values.
55. AVG() — Calculate the arithmetic mean of non-NULL numeric values.
56. MIN() — Find the minimum non-NULL value.
57. MAX() — Find the maximum non-NULL value.
58. ROUND() — Round numerical results.
59. COALESCE() — Return the first non-NULL expression.
60. NULLIF() — Return NULL when two expressions are equal.
61. Aggregate functions with DISTINCT — Aggregate unique values.
62. Aggregate FILTER clause — Apply different conditions to individual aggregates.
63. Conditional aggregation — Combine CASE with aggregate functions.
64. Aggregate functions and NULL handling — Understand that COUNT(\*) counts all rows, while COUNT(column), SUM, AVG, MIN, and MAX ignore NULL input values.
65. Aggregates on empty result sets — Understand NULL results versus COUNT returning zero.
## 6. GROUP BY and HAVING
66. GROUP BY — Group rows sharing common values.
67. GROUP BY multiple columns — Group using combinations of column values.
68. GROUP BY with COUNT — Count rows per group.
69. GROUP BY with SUM — Calculate totals per group.
70. GROUP BY with AVG — Calculate averages per group.
71. GROUP BY with MIN and MAX — Calculate grouped minimums and maximums.
72. HAVING — Filter groups after aggregation.
73. WHERE versus HAVING — Filter individual rows versus aggregated groups.
74. GROUP BY with HAVING and ORDER BY — Group, filter, and sort summarized results.
75. GROUP BY with JOIN — Aggregate data across related tables.
76. GROUPING SETS — Generate multiple grouping combinations.
77. ROLLUP — Produce hierarchical subtotals and grand totals.
78. CUBE — Produce subtotals across all grouping combinations.
## 7. SQL Joins
79. INNER JOIN — Return matching rows from both tables.
80. LEFT JOIN / LEFT OUTER JOIN — Return all left-table rows and matching right-table rows.
81. RIGHT JOIN / RIGHT OUTER JOIN — Return all right-table rows and matching left-table rows.
82. FULL JOIN / FULL OUTER JOIN — Return matching and unmatched rows from both tables.
83. CROSS JOIN — Return every combination of rows from two tables.
84. SELF JOIN — Join a table with itself.
85. CROSS JOIN LATERAL — Evaluate a dependent subquery for each preceding row.
86. LEFT JOIN LATERAL — Preserve preceding rows even when a lateral subquery returns no matches.
87. Multiple-table JOIN — Join three or more related tables.
88. JOIN with multiple conditions — Use AND/OR within join conditions.
89. JOIN with WHERE — Filter joined records.
90. JOIN with GROUP BY and HAVING — Aggregate and filter joined data.
91. JOIN with subqueries — Join against derived query results.
92. JOIN with USING — Join tables using identically named columns.
93. NATURAL JOIN — Automatically join columns sharing names.
94. Non-equi JOIN — Join using inequality or range conditions.
95. SEMI JOIN pattern — Return rows having a match, commonly using EXISTS.
96. ANTI JOIN pattern — Return rows without matches, commonly using NOT EXISTS or LEFT JOIN with IS NULL.
97. JOIN versus subquery — Compare alternative ways to retrieve related data.
98. JOIN duplication and NULL handling — Understand one-to-many row multiplication and unmatched records.
## 8. Subqueries
99. Scalar subquery — Return a single value.
100. Single-row subquery — Return one row for comparison.
101. Multiple-row subquery — Return multiple records or values.
102. Subquery in WHERE — Filter rows using another query.
103. Subquery in SELECT — Calculate a value for each output row.
104. Subquery in FROM — Create a derived table.
105. Subquery in HAVING — Filter aggregated results using another query.
106. IN with subquery — Match against a query-generated set.
107. NOT IN with subquery — Exclude query-generated values, with special care around NULLs.
108. EXISTS — Check whether a subquery returns any rows.
109. NOT EXISTS — Check that no matching rows exist.
110. ANY / SOME — Compare against at least one subquery value.
111. ALL — Compare against every subquery value.
112. Correlated subquery — Reference a column from the outer query.
113. Non-correlated subquery — Execute independently of the outer query.
114. Nested subqueries — Place subqueries inside other subqueries.
115. Subquery with aggregate functions — Compare rows against calculated totals, averages, minimums, or maximums.
116. Subquery with UPDATE — Update records based on query results.
117. Subquery with DELETE — Remove records based on query results.
118. LATERAL subquery — Reference earlier FROM items in a dependent subquery.
## 9. Set Operations
119. UNION — Combine query results and eliminate duplicates.
120. UNION ALL — Combine query results while preserving duplicates.
121. INTERSECT — Return distinct rows common to both queries.
122. INTERSECT ALL — Return common rows with duplicate counts preserved according to multiset rules.
123. EXCEPT — Return distinct rows from the first query absent from the second.
124. EXCEPT ALL — Perform multiset difference while accounting for duplicates.
125. MINUS equivalent — Use EXCEPT in PostgreSQL; Oracle's MINUS syntax is not supported.
126. Set operations with WHERE — Combine filtered datasets.
127. Set operations with ORDER BY — Sort combined results.
128. Set operations with subqueries — Combine derived results.
129. Set operation column compatibility — Ensure corresponding columns have compatible datatypes.
130. Combining UNION, INTERSECT, and EXCEPT — Use parentheses to control evaluation order.
## 10. SQL Constraints
131. PRIMARY KEY — Uniquely identify table rows; disallow NULL values.
132. FOREIGN KEY — Enforce relationships between tables.
133. UNIQUE — Prevent duplicate values or value combinations.
134. NOT NULL — Require a column value.
135. CHECK — Validate data against a Boolean condition.
136. DEFAULT — Supply a default value when none is provided.
137. Composite primary key — Define a key using multiple columns.
138. Composite foreign key — Reference multiple columns in another table.
139. Named constraints — Assign explicit names to constraints.
140. Column-level constraints — Define constraints alongside columns.
141. Table-level constraints — Define constraints across one or more columns.
142. ON DELETE CASCADE — Automatically delete dependent referencing rows.
143. ON DELETE SET NULL — Set referencing columns to NULL when the parent row is deleted.
144. ON DELETE RESTRICT / NO ACTION — Prevent invalid parent-row deletion.
145. ON UPDATE CASCADE — Propagate referenced key updates.
146. DEFERRABLE constraints — Delay certain constraint checks within transactions.
147. Constraint validation — Add and validate applicable constraints on existing data.
148. Identity columns — Generate automatically incrementing key values.
## 11. ALTER TABLE
149. ADD COLUMN — Add a new column.
150. DROP COLUMN — Remove a column.
151. RENAME COLUMN — Rename an existing column.
152. RENAME TABLE — Change a table name.
153. ALTER COLUMN TYPE — Change a column's datatype.
154. USING expression — Transform values while changing datatype.
155. SET DEFAULT — Assign a default column value.
156. DROP DEFAULT — Remove a default value.
157. SET NOT NULL — Require values for an existing column.
158. DROP NOT NULL — Allow NULL values.
159. ADD CONSTRAINT — Add a primary, foreign, unique, or check constraint.
160. DROP CONSTRAINT — Remove an existing constraint.
161. RENAME CONSTRAINT — Rename a constraint.
162. ADD IDENTITY / DROP IDENTITY — Manage identity generation.
163. ALTER TABLE with transactions — Demonstrate schema changes with BEGIN and ROLLBACK.
## 12. Data Manipulation: INSERT, UPDATE, DELETE
164. INSERT INTO — Insert new records.
165. INSERT multiple rows — Insert several records in one statement.
166. INSERT SELECT — Insert results from another query.
167. INSERT with DEFAULT values — Populate unspecified columns using defaults.
168. UPDATE — Modify existing records.
169. UPDATE with WHERE — Update only matching records.
170. UPDATE multiple columns — Modify several fields together.
171. UPDATE with AND / OR / IN / BETWEEN — Apply complex update conditions.
172. UPDATE with CASE — Assign different values based on conditions.
173. UPDATE FROM — Update a table using related-table values.
174. UPDATE with subquery — Calculate or filter updates using another query.
175. UPDATE RETURNING — Return rows modified by an update.
176. DELETE FROM — Remove rows from a table.
177. DELETE with WHERE — Remove selected records.
178. DELETE with subquery — Delete based on another query's results.
179. DELETE USING — Delete records using joined-table conditions.
180. RETURNING — Retrieve affected rows from INSERT, UPDATE, or DELETE.
181. INSERT ON CONFLICT DO NOTHING — Skip conflicting inserts.
182. INSERT ON CONFLICT DO UPDATE — Implement upsert operations.
183. TRUNCATE — Quickly remove all records from a table.
184. MERGE — Conditionally insert, update, or delete using a source dataset (PostgreSQL 15+).