Can Kurucu
Can Kurucu

Reputation: 75

Using "LIMIT OFFSET" with array_to_json in PostgreSQL

I've a problem when using limit offset in postgresql. Although I specify limit offset values, it lists all data.

SELECT 
        array_to_json(
            array_agg(
                json_build_object(
                    'nickName', u.username,
                    'date', to_char(p.create_date, 'DD/MM/YYYY'),
                    'time', to_char(p.create_date, 'HH24:MM'),
                    'questionId', p.post_id,
                    'questionContent', p.content,
                    'status', CASE WHEN p.status = 0 THEN 'Waiting for approval' WHEN p.status = 1 THEN 'Approved' WHEN p.status = 0 THEN 'Reject' END,
                    'rejectReason', p.reject_reason,
                    'answerUrl', p.seo_url
                )
            )
        )
  INTO _posts
FROM posts p
  INNER JOIN users u ON u.user_id = p.user_id 
WHERE p.user_id = _user_id
LIMIT 5 OFFSET _page * 5;

Please review my code and tell me where the problem is.

Upvotes: 1

Views: 1242

Answers (1)

Lucas
Lucas

Reputation: 630

Without rewriting the whole query for you, json_agg may be more appropriate here.

SELECT json_agg(x) AS json_feed
FROM (
    SELECT
        column AS "columnName", ...
    FROM your_table
    LIMIT 5
) AS x

Upvotes: 2

Related Questions