CodeBlanks Logo Icon CodeBlanks

Post list

Write the VIEW that lists recent posts.

Post list

You can store recent posts as a VIEW. It can be easily queried later.

CREATE VIEW recent_posts AS
SELECT id, title FROM posts ORDER BY id DESC LIMIT 10;

VIEW for the last 10 posts.

The view recent_posts is created. id, title is selected from posts. The result is sorted by id in descending order. Only the first 10 rows are returned.

Post list — details

A VIEW names a query. ORDER BY and LIMIT can be used inside a VIEW.

This way the home page gets the 10 latest posts with SELECT * FROM recent_posts instead of repeating the long query.

Practice Post list

Create the recent_posts VIEW with the last 10 posts.

Starter code

query.sql
-- recent posts view
CREATE VIEW recent_posts

Sample solution

query.sql
CREATE VIEW recent_posts AS
SELECT id, title FROM posts ORDER BY id DESC LIMIT 10;

Expected output

VIEW oluşturuldu

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Add CREATE VIEW

Question
CREATE ____ recent_posts AS
SELECT id, title FROM posts ORDER BY id DESC LIMIT 10;
Answer
CREATE VIEW recent_posts AS
SELECT id, title FROM posts ORDER BY id DESC LIMIT 10;

Explanation: CREATE VIEW stores the query for the 10 latest posts under the name recent_posts.

2 Can a VIEW have LIMIT?

  • No
  • Only in MySQL
  • Yes Correct answer
  • In some cases

Explanation: LIMIT can be used inside a VIEW.

3 Post list: match the terms

Term Meaning
VIEW virtual table
ORDER BY sort
LIMIT limit
recent last

All lessons in Intermediate