|
87 | 87 |
|
88 | 88 | [12. Common table expressions](#12-common-table-expressions)
|
89 | 89 | [13. Recursive common table expressions (CTE)](#13-recursive-common-table-expressions-cte)
|
| 90 | +[14. Views](#14-views) |
90 | 91 |
|
91 | 92 | ---
|
92 | 93 | ###### <div style="text-align:right">[table of contents](#table-of-contents)</div>
|
@@ -1450,4 +1451,52 @@ table suggestions (leader_id, follower_id, depth)
|
1450 | 1451 |
|
1451 | 1452 | ---
|
1452 | 1453 |
|
| 1454 | +###### <div style="text-align:right">[table of contents](#table-of-contents)</div> |
| 1455 | + |
| 1456 | +## 14. Views |
| 1457 | + |
| 1458 | +fixing mistakes in the design of table creation process where you constantly have to perform eg. JOINS for queries when you should have maybe had combined tables. |
| 1459 | +Better way to merge tables together without deleting original tables. |
| 1460 | + |
| 1461 | +A view is a "fake" table that has rows from other tables. |
| 1462 | +These can be exact rows or computed values. |
| 1463 | +can reference a view in any place where we usually reference a table. |
| 1464 | +view doesnt actually create a table or move data around. |
| 1465 | + |
| 1466 | +Views can be created ahead of time, |
| 1467 | +can be refferenced in different queries (whereas CTE's can only be reffered to in the query they are attached to) |
| 1468 | + |
| 1469 | +you want to create a view when there is an operation that's logic you will execute often. |
| 1470 | + |
| 1471 | +view all views -> pgadmin - > schemas -> public views |
| 1472 | + |
| 1473 | +```SQL |
| 1474 | +--creating a view |
| 1475 | +CREATE VIEW tags AS( |
| 1476 | + SELECT id, created_at, user_id, post_id, 'photo_tag' AS type FROM photo_tags |
| 1477 | + UNION ALL |
| 1478 | + SELECT id, created_at, user_id, post_id, 'caption_tag' AS type FROM caption_tags |
| 1479 | +); |
1453 | 1480 |
|
| 1481 | +--reference view from another different query |
| 1482 | +SELECT username, COUNT(*) |
| 1483 | +FROM users |
| 1484 | +JOIN tags ON tags.user_id = users.id |
| 1485 | +GROUP BY username |
| 1486 | +ORDER BY COUNT(*) DESC; |
| 1487 | +``` |
| 1488 | + |
| 1489 | +##### updating view (change the definition) |
| 1490 | +syntax: CREATE OR REPLACE VIEW _ AS |
| 1491 | + |
| 1492 | +```SQL |
| 1493 | + CREATE OR REPLACE VIEW recent_posts AS ( |
| 1494 | + SELECT * FROM posts |
| 1495 | + ORDER BY created_at DESC |
| 1496 | + LIMIT 15 |
| 1497 | + ) |
| 1498 | +``` |
| 1499 | +##### deleting a view |
| 1500 | +```SQL |
| 1501 | + DROP VIEW recent_posts; |
| 1502 | +``` |
0 commit comments