INSERT with Subquery in SQL

Level 5212 keystrokes

INSERT with SELECT inserts the results of a query into a table.

SQL code

-- Insert into daily_stats, filling these four columns
1INSERT INTO daily_stats (
2 date,
3 page_views,
4 unique_visitors,
5 total_sales
6)
-- The rows come from a SELECT instead of VALUES; columns are matched by position
7SELECT
-- Today's date goes into date
8 CURDATE(),
-- Number of log rows = page views (the alias views is only a label)
9 COUNT(*) AS views,
-- Each user is counted once
10 COUNT(DISTINCT user_id) AS visitors,
-- Total amount of the day
11 SUM(amount) AS sales
12FROM
13 page_logs
-- Only today's logs; with no GROUP BY, exactly one row is inserted
14WHERE
15 log_date = CURDATE();

Output

Query OK, 1 row affected
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this SQL code and how often they appear.

  • _× 7
  • ,× 6
  • (× 6
  • )× 6
  • ;× 1
  • *× 1
  • =× 1

More SQL examples at level 5

← SQL typing practice