How can I request a random column (or as close to truly random as is possible) in pure SQL?
I want to select any one column randomly from a table.
I have searched lot regarding this on google.
Dependent on your DBMS the catalogue looks a bit different. For mysql you could get a random column like:
select column_name
from information_schema.columns
where table_schema = ?
and table_name = ?
order by rand() limit 1;
and then incorporate that into your query. Other vendors may have a slightly different look of the catalogue, but the idea will be the same.
Why do you want to retrieve a random column?
USE [AdventureWorksDW2012]
GO
DECLARE @SQL VARCHAR(MAX)
SELECT [name]
FROM sys.columns C WHERE C.object_id = OBJECT_ID('DimProduct')
AND C.column_id = (
SELECT ((ABS(CHECKSUM(NEWID()))% COUNT(*)) + 1)
FROM sys.columns C
WHERE C.object_id = OBJECT_ID('DimProduct'))
This may help you, It is done with SQL Server. Here you are randomly selecting a column of table [DimProduct]
Result1:
Result2:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With