Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Query to select limit in specific condition

In my table, I have the ’email’ column. I want to select 1000 data where max 100 emails are ‘gmail’. Is there any way to write one query to get data?

What I am doing is, to create two queries and then merge them.

SELECT email from my_table where email not like '%@gmail.%' limit 900;
SELECT email from my_table where email like '%@gmail.%' limit 100;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A simple union all should be it. However, to make sure that you’re getting exactly 1000 rows (in case there are more than 1000 rows but less than 100 are @gmail) you can do this:

with u as 
(SELECT email from my_table where email like '%@gmail.%' limit 100)
select * from u
union all
(SELECT email from my_table 
where email not like '%@gmail.%' 
limit 1000 - (select count(*) from u));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading