Select limit percent - mysql

I want
example 10% of records in table
not 10 records
This query run in SQL Server
select top 10 percent * from tablename
Why this query in MySQL do not run?
select top 10 percent * from tablename

You could do it with a subquery, this is pretty basic since you want everything in one table:
SELECT *
FROM (
SELECT tablename.*, #counter := #counter +1 AS counter
FROM (select #counter:=0) AS initvar, tablename
ORDER BY value DESC
) AS X
where counter <= (10/100 * #counter);
ORDER BY value DESC

For MySQL use order by or limit
select * from tablename order by percent desc limit 10
TOP clause works on MSSQL server not sql.

Related

How to select random 2 percent rows in mysql?

How to get a random 2% sample from a table in MySQL?
I tried the following queries
SELECT orderID
FROM orders
ORDER BY rand()
LIMIT 1 OFFSET (SELECT convert(0.02 * count(*), unsigned) FROM orders)
;
SELECT orderID
FROM orders
ORDER BY rand()
LIMIT (SELECT convert(0.02 * count(*), unsigned) FROM orders)
;
Both of them give errors. Could someone explain error and alternate methods.
Database: Northwind
MySQL version: 8.0
I would use ROW_NUMBER here:
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (ORDER BY RAND()) rn, COUNT(*) OVER () cnt
FROM orders
)
SELECT *
FROM cte
WHERE rn < 0.02 * cnt; -- select first 2% of a random sample
If approximately 2% is sufficient, then you can just use:
SELECT orderID
FROM orders
WHERE rand() <= 0.02;
Because no sorting is required, this is probably the fastest method.
Do note that the result is not exactly 2% but on a large table it will be close enough.
You can use MySQL Stored Procedure to create a function inside our MySQL.
https://www.mysqltutorial.org/getting-started-with-mysql-stored-procedures.aspx/
CREATE PROCEDURE GetRand2PercentSample()
BEGIN
DECLARE nLimit INT DEFAULT 0;
SELECT COUNT(*) * 0.2
INTO nLimit
FROM orders;
SELECT * FROM orders ORDER BY RAND() LIMIT nLimit;
END
// to call the function
call GetRand2PercentSample()

SQL limit result to top 50%

I tried two methods but failed in mysql.
/*see top 50% students, but this sql can't work*/
select * from student_table order by chinese_score desc limit count(*) * 0.5 ;
/*also can't work*/
set #num= floor((select count(*) from test.student_score)*0.5);
select * from student_table order by chinese_score desc limit #num ;
How to solve in mysql?
In Mysql this can be done in a single query using user defined variables.
You can store a value in a user-defined variable in one statement and
refer to it later in another statement. This enables you to pass
values from one statement to another.
SELECT * FROM (
SELECT student_table.*, #counter := #counter +1 AS counter
FROM (SELECT #counter:=0) AS initvar, student_table
ORDER BY student_table.chinese_score DESC
) AS result
WHERE counter < (#counter/2) ORDER BY chinese_score DESC;

How Can I set result set row count using sql query

I wanted to set the number rows returned per query say 5. How can I set this in the sql query.
Can any one please help me
Highly dependent on what RDBMS you are using.
For Oracle
SELECT * FROM the_table WHERE ROWNUM < 6
(since 12c there is another option, too).
For Postgresql
SELECT * FROM the_table LIMIT 5
According to the MySQL manual you can do this by adding LIMIT statement to your query:
SELECT * FROM tbl_name
LIMIT offset, row_numbers
or
SELECT * FROM tbl_name
LIMIT row_numbers OFFSET offset
offset option is very useful in case of pagination.
SELECT TOP 5 *
FROM dbo.MyTable
As someone suggest zou can use:
select top X from table_name
where X is the numer of rows that you want
or you can use row_number
With cte AS
( SELECT *,
ROW_NUMBER() OVER (order by table_column) as RowNumber
FROM table_name)
select *
from cte
Where RowNumber <= 5
or even:
With cte AS
( SELECT *,
ROW_NUMBER() OVER (order by table_column) as RowNumber
FROM table_name)
select *
from cte
Where RowNumber between 5 and 10

Mysql get top half of table then bottom half of table

I need to get the top half of my table in my first query and in the next query I need the bottom half.
I tried doing this for the top but it wont work
SELECT * FROM t_domains WHERE type_domain='radio' ORDER BY
date_created DESC LIMIT 0, (COUNT(*) / 2)
I need it as two queries for my function to work.
Anybody have any pointers or tips?
I would suggest doing 2 query's:
select count(*) from t_domains
to get the total count, and then get the data you want by using limit and offset:
select * from t_domains limit count/2
for the top and
select * from t_domains offset count/2
for the lower half......
This approach gives you also a way to limit the query's in another situation: what if the table contains 1 million records?
for first half
mysql-> SET #n := 0
mysql-> SELECT *,nnn FROM (
SELECT *, #n := #n + 1 AS nnn FROM t_domains ORDER BY date_created
) AS t
WHERE nnn <= ( SELECT COUNT(date_created) / 2 FROM t_domains ) AND type_domain = 'radio'
for second half, change here WHERE nnn <= this "<" on this ">"
As explained in MySQL's official documentation, LIMIT's two arguments must both be CONSTANTS except for prepared statements and stored programs. It does not seem very easy to simply store the count and later use it in a LIMIT clause.
As of version 8.0, MySQL has provided a ROW_NUMBER() function, which provides a much simpler solution than other answers have pointed out.
set #count=(select count(*)/2 from t_domains);
select * from (
select *, ROW_NUMBER() over (order by date_created desc) as row_num
from t_domains
) as t
where row_num <= #count
;
You may also check RANK(), which considers rows with equal values to have the same "ranking".
This always works.
Store the count
SELECT COUNT(*) FROM t_domains WHERE type_domain='radio'
Then use the stored count.
SELECT * FROM t_domains WHERE type_domain='radio' ORDER BY
date_created DESC LIMIT 0, {$stored_count/2}

DELETE with a percentage on total count

Let's say I want to delete 10% of rows, is there a query to do this?
Something like:
DELETE FROM tbl WHERE conditions LIMIT (SELECT COUNT(*) FROM tbl WHERE conditions) * 0.1
If you only need roughly 10% of rows, in no particular order, this should do the trick:
DELETE FROM tbl WHERE RAND() <= 0.1
However, I don't recommend using it on very large data sets due to the overhead of generating random numbers.
I would simply return the total amount of filtered rows, calculate through php and use that value as a limit in my DELETE query.
$query = mysql_query("SELECT COUNT(*) FROM tbl WHERE conditions");
$int = reset(mysql_fetch_array($query));
$int = round($int * 0.1);
mysql_query("DELETE FROM tbl WHERE conditions LIMIT {$int}");
I'm not sure if DELETE allows an advanced query such as this one:
DELETE FROM ( SELECT h2.id
FROM ( SELECT COUNT(*) AS total
FROM tbl
WHERE conditions) AS h
JOIN ( SELECT *, #rownum := #rownum + 1 AS rownum
FROM tbl, (SELECT #rownum := 0) AS vars
WHERE conditions) AS h2
ON '1'
WHERE rownum < total * 0.1) AS h3