Question: Search Query Trends
"Analyze how search query volumes change over time (daily, weekly, or monthly). Write a query that shows the number of searches over each time period."
Step-by-Step Explanation:
You have a table called search_logs
with:
user_id
keyword
search_time
(timestamp when the search was made)
You need to:
- Analyze how many searches were made over time periods (daily, weekly, or monthly).
- Show the number of searches per time period.
Sample Data (search_logs
):
user_id | keyword | search_time |
---|---|---|
1 | "shoes" | 2024-01-01 10:00:00 |
2 | "jackets" | 2024-01-01 11:00:00 |
3 | "shoes" | 2024-01-02 09:00:00 |
1 | "laptops" | 2024-01-02 13:00:00 |
2 | "shoes" | 2024-01-08 15:00:00 |
Step 1: Extract Time Period from Timestamp
Depending on the analysis you want:
- Daily: Extract only the date (without time).
- Weekly: Extract the week number and year.
- Monthly: Extract the year and month.
In SQL, we use:
DATE(search_time)
→ gives just the date.YEAR(search_time)
andWEEK(search_time)
→ for weekly grouping.DATE_FORMAT(search_time, '%Y-%m')
→ for monthly grouping.
Step 2: Count the Number of Searches
For each time period, count how many searches were made (COUNT(*)
).
Step 3: Group by the Time Period
Use GROUP BY
based on how you extract the time period.
SQL Query Examples:
1. Search Volume Daily:
SELECT
DATE(search_time) AS search_date,
COUNT(*) AS search_count
FROM
search_logs
GROUP BY
search_date
ORDER BY
search_date;
This will show the number of searches for each date.
2. Search Volume Weekly:
SELECT
YEAR(search_time) AS year,
WEEK(search_time) AS week_number,
COUNT(*) AS search_count
FROM
search_logs
GROUP BY
year, week_number
ORDER BY
year, week_number;
This will show number of searches per week.
3. Search Volume Monthly:
SELECT
DATE_FORMAT(search_time, '%Y-%m') AS month,
COUNT(*) AS search_count
FROM
search_logs
GROUP BY
month
ORDER BY
month;
This will show number of searches per month like "2024-01", "2024-02", etc.
Expected Outputs:
For Daily Search Trends:
search_date | search_count |
---|---|
2024-01-01 | 2 |
2024-01-02 | 2 |
2024-01-08 | 1 |
For Weekly Search Trends:
year | week_number | search_count |
---|---|---|
2024 | 1 | 4 |
2024 | 2 | 1 |
For Monthly Search Trends:
month | search_count |
---|---|
2024-01 | 5 |
Important Points:
- Always think about which time frame is most useful (daily/weekly/monthly).
DATE()
,WEEK()
,YEAR()
, andDATE_FORMAT()
are the main functions used.ORDER BY
the time period so you can easily see the trend in the correct order.- Weekly can be tricky because
WEEK()
sometimes depends on the SQL server settings (whether week starts on Sunday or Monday).