Interview Questions/SQL/Article Views - Authors Who Viewed Their Own Articles

Article Views - Authors Who Viewed Their Own Articles

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Description

You are given a Views table that logs which viewer read which article on a given date. There is no primary key, so duplicate rows can exist. Write a SQL query to find all authors who have viewed at least one of their own articles - i.e., rows where author_id = viewer_id. Return the result as id, sorted in ascending order.

Database Schema

Views

Column NameExample Value
article_id1
author_id3
viewer_id5
view_date2019-08-01

Example

Views

article_idauthor_idviewer_idview_date
1352019-08-01
1362019-08-02
2772019-08-01
2762019-08-02
4712019-07-22
3442019-07-21
3442019-07-21

Output

id
4
7

Explanation:

Author 7 viewed their own article (article_id=2). Author 4 viewed their own article (article_id=3) - the duplicate row is ignored by DISTINCT. Author 3 never viewed their own articles.

Approach hint

Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

SQL Editor
Loading...

Views

article_idauthor_idviewer_idview_date
1352019-08-01
1362019-08-02
2772019-08-01
2762019-08-02
4712019-07-22
3442019-07-21
3442019-07-21

Output

id
4
7