Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

202
Views
Check number of query after use limit SQL

I'm new to SQL.

I have a query like

select * from mytable order by 1 desc limit 2

If mytable has only 1 row this query will return that row. How can I make sure my query always return 2 result and if mytable has 1 row it will return NULL

That's my 1st question here, sorry for my English

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You could try using a union trick here:

SELECT col1, col2, col3
FROM
(
    SELECT col1, col2, col3, 1 AS priority FROM mytable
    UNION ALL
    SELECT NULL, NULL, NULL, 2
    UNION ALL
    SELECT NULL, NULL, NULL, 2
) t
ORDER BY
    priority,
    col1
LIMIT 2;

The above strategy is to include via union two "empty" records. However, these empty records would only ever appear in the result set in the event that your table has fewer than 2 records.

over 4 years ago · Santiago Trujillo Report

0

If you have a bunch of columns and don't want to list them, you can use this variation on Tim's answer:

select t.*
from mytable t
union all
select t.*
from (select 1 as n union all select 2 as n) left join
     mytable t
     on 1 = 0;  -- always false
order by col1 desc
limit 2;

The descending sort puts non-NULL values first. This assumes that col1 is not NULL -- so valid rows are first.

Notes:

  • This makes it easy to add more rows (just change the subquery).
  • This makes it easy to handle more columns -- they are inserted automatically.
  • No subquery is needed.
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!