EN
PostgreSQL - select first N rows
0 points
In this article, we would like to show you how to find and select the first row from a table in PostgreSQL.
Quick solution:
xxxxxxxxxx
1
SELECT "column1", "column2", "columnN"
2
FROM "table_name"
3
LIMIT N;
To show how to select the first N rows from a table, we will use the following table:

Note:
At the end of this article you can find database preparation SQL queries.
In this example, we will select all the information (columns) about the first 3
users from the users
table.
Query:
xxxxxxxxxx
1
SELECT *
2
FROM "users"
3
LIMIT 3;
Output:

In this example, we will find the first 3 users id
, name
and email
column information.
Query:
xxxxxxxxxx
1
SELECT "id", "name", "email"
2
FROM "users"
3
LIMIT 3;
Output:

In this example, we will select the first row in some order.
xxxxxxxxxx
1
SELECT *
2
FROM "users"
3
ORDER BY "name"
4
LIMIT 3;
Output:

create_tables.sql
file:
xxxxxxxxxx
1
CREATE TABLE "users" (
2
"id" SERIAL PRIMARY KEY,
3
"name" VARCHAR(100) NOT NULL,
4
"email" VARCHAR(100) NOT NULL,
5
"country" VARCHAR(15) NOT NULL
6
);
insert_data.sql
file:
xxxxxxxxxx
1
INSERT INTO "users"
2
("name", "email", "country")
3
VALUES
4
('Tom', 'tom@email.com', 'Poland'),
5
('Chris', 'chris@email.com', 'Spain'),
6
('Jack', 'jack@email.com', 'Spain'),
7
('Kim', 'kim@email.com', 'Vietnam'),
8
('Marco', 'marco@email.com', 'Italy'),
9
('Kate', 'kate@email.com', 'Spain'),
10
('Nam', 'nam@email.com', 'Vietnam');