Skip to content

Commit 273b9aa

Browse files
committed
Views / Materialized views
1 parent f0b3468 commit 273b9aa

File tree

1 file changed

+45
-1
lines changed

1 file changed

+45
-1
lines changed

01.SQL.md

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,8 @@
9191

9292
[14. Views](#14-views)
9393

94+
[15. Materialized Views](#15-materialized-views)
95+
9496
---
9597
###### <div style="text-align:right">[table of contents](#table-of-contents)</div>
9698
## 1. Basics
@@ -324,14 +326,18 @@ No performance benefits between types
324326
Can provide string in almost any format and postgres will do conversion
325327
can specify something to be date by explicitly giving a data type with '::DATE'
326328

329+
###### date_trunc('week')
330+
pulls out from date property and rounds down to nearest week
331+
327332
```SQL
328333
SELECT('NOV 20 1980'::DATE);
329334
```
330335
* 1980-11-20 -> 1980-11-20
331336
* NOV-20-1980 -> 1980-11-20
332337
* 20-Nov-1980 -> 1980-11-20
333338
* 1980-November-20 -> 1980-11-20
334-
* November 20, 1980 -> 1980-11-20
339+
* November 20, 1980 -> 1980-11-20\
340+
335341

336342
##### Time
337343

@@ -1502,3 +1508,41 @@ syntax: CREATE OR REPLACE VIEW _ AS
15021508
```SQL
15031509
DROP VIEW recent_posts;
15041510
```
1511+
---
1512+
## 15. Materialized views
1513+
Query that gets executed only at very specific times, but the results are saved and
1514+
can be referenced without rerunning the query.
1515+
1516+
We make use of a materialized view when we have a very expensive query.
1517+
We can run a materialized view just one time and hang on to the results and refer back to it
1518+
without having to rerun the very expensive query.
1519+
'WITH DATA' is when we create the materialized view, tell postgreSQL to run query once and hold onto the results.
1520+
after running the materialized view, you can refer to it without running the query again.
1521+
1522+
1523+
```SQL
1524+
CREATE MATERIALIZED VIEW as weekly_likes AS (
1525+
--query to materialize
1526+
SELECT
1527+
data_trunk('week', COALESCE(posts.created_at, comments.created_at)) AS week
1528+
COUNT(posts.id) AS num_likes_for_posts,
1529+
COUNT(comments.id) AS num_likes_for_comments
1530+
FROM likes
1531+
LEFT JOIN posts ON posts.id = likes.post_id
1532+
LEFT JOIN comments ON comments.id = likes.comment_id
1533+
GROUP BY week
1534+
ORDER BY week
1535+
) WITH DATA; --'with data' is when we create the materialized view, tell postgreSQL to run query once and hold onto the results.
1536+
1537+
```
1538+
1539+
```SQL
1540+
SELECT * FROM weekly_likes;
1541+
```
1542+
1543+
##### Update data held by materialized view
1544+
modifying any data in materialized view (SQL statement), will require us to refresh the materialized view to keep the data in-sync
1545+
1546+
```SQL
1547+
REFRESH MATERIALIZED VIEW weekly_likes;
1548+
```

0 commit comments

Comments
 (0)