9. Limiting number of records produced by query

“Wooow, we have thousands of users registered, look at these users!” the girls were screaming and jumping out of joy. “I’m really glad that we can query the tables so easily and check what fields are there. But do we need to print all records every time? It makes it slower, is there a way to print out, say, 5 records?” asked Linh.

Indeed there is 😊 There’s a special keyword LIMIT that tells SQL how many records do we want to be printed. For example, this query will print the first 5 records:

SELECT *
FROM users
LIMIT 5

Let’s combine all the things we have learned so far, can you tell what this query is doing?

SELECT *
FROM users
ORDER BY created_at DESC
LIMIT 5

This query could be interpreted like Give me all columns of 5 latest records in the users table, simply 5 latest signups.

Note, that we used the created_at datetime column to sort records by precise timestamps. An alternative would be to sort records by signup_date column. Keep in mind that signup_date doesn’t have information about hour/minute or second of a signup because it’s a column of type date ⚠

Now go and practice these queries in the Playground or jump into your first exercise 👏

Anatoli Makarevich, author of SQL Habit About SQL Habit

Hi, it’s Anatoli, the author of SQL Habit. 👋

SQL Habit is a course (or, as some of the students say, “business simulator”). It’s based on a story of a fictional startup called Bindle. You’ll play a role of their Data Analyst 📊 and solve real-life challenges from Business, Marketing, and Product Management.

SQL Habit course is made of bite-sized lessons (you’re looking at one atm) and exercises. They always have a real-life setting and detailed explanations. You can immediately apply everything you’ve learned at work. 🚀

“well worth the money”

Fluent in SQL in a month

Master Data Analysis with SQL with real life examples from Product Management, Marketing, Finance and more.
-- Type your query here, for example this one -- lists all records from users table: SELECT * FROM users
LIMIT 500
Loading chart... ⏳