473,396 Members | 1,748 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

SQL Union Problems When Trying to Retrieve Random Records

I have a situation where i am trying to run two query's and retrieve
one record from each query, then using Union combine them into one
recordset. The First Query is strait forward and should just return
the matching record however the second query needs to find a random
record and return it. The union is causing me some trouble. It seems
that any method i try to find a random record just causes an error.

Here is an example of a query that's causing the problem.
--------------------------------------------------------------------------------------------------------

declare @variable1 smallint
declare @variable2 int

set @variable1 = 10002
set @variable2 = 1001211720

select col1, col2, col3, col4, col5, col6
from table1
where col1 = @variable1 and col2 = @variable2

union

select col1, col2, col3, col4, col5, col6
from table2
where col2 = @variable2
order by newID()

--------------------------------------------------------------------------------------------------------
I have also tried the following which does not provide an error but i
cannot find a way only to return one record from the second query
--------------------------------------------------------------------------------------------------------

declare @variable1 smallint
declare @variable2 int

set @variable1 = 10002
set @variable2 = 1001211720

select newID() as colID, col1, col2, col3, col4, col5, col6
from table1
where col1 = @variable1 and col2 = @variable2

union

select newID() as colID, col1, col2, col3, col4, col5, col6
from table2
where col2 = @variable2
order by colID

If anyone has any ideas, fixes, or thoughts i would appreciate them...
thanks in advance...
FYI i am fairly inexperienced in SQL so please feel free to let me know
if you need more of an explination.

Jun 6 '06 #1
9 2891
Jeremy,

look up SELECT TOP 1 in Books Online

Jun 6 '06 #2
Am 6 Jun 2006 08:02:01 -0700 schrieb Jeremy:
....
I have also tried the following which does not provide an error but i
cannot find a way only to return one record from the second query


Without looking at the rest of your query only a hint for getting only one
record (works only for SQL2000 and higher):

select col1, col2, ... from table where ...
union
select * from
(select top 1 col1, col2, col3, ... from table where .... order by col1,
....) as X

.... and you get only the first record from the second part.

bye, Helmut
Jun 6 '06 #3
i found that this does not get a random value... it only returns the
first record... how would i use this and return a random value.
thanks
jeremy
Alexander Kuznetsov wrote:
Jeremy,

look up SELECT TOP 1 in Books Online


Jun 6 '06 #4
JM********@gmail.com (JM********@gmail.com) writes:
i found that this does not get a random value... it only returns the
first record... how would i use this and return a random value.


select col1, col2, col3, col4, col5, col6
from table1
where col1 = @variable1 and col2 = @variable2
union
select col1, col2, col3, col4, col5, col6
from (SELECT TOP 1 col1, col2, col3, col4, col5, col6
from table2
where col2 = @variable2
order by newID()) AS d

You need a derived table into which you can put the TOP 1 and ORDER BY.

--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Jun 6 '06 #5
>
select col1, col2, col3, col4, col5, col6
from (SELECT TOP 1 col1, col2, col3, col4, col5, col6
from table2
where col2 = @variable2
order by newID()) AS d


Erland,

My server has crashed and I cannot verify it right now, but I have a
feeling that newID() will be calculated for every row, which may be
inefficient. I was thinking of a more efficient way to get a random
row. Suppose there is an identity column, then you could
do something like this to get a random identity:

select min(id) from table2,
(select max(id) maxID, min(ID) minID from table2) t
where table2.id > t.minID + (t.maxID - t.minID)*rand()

What do you think?

Jun 7 '06 #6
Alexander Kuznetsov (AK************@hotmail.COM) writes:
My server has crashed and I cannot verify it right now, but I have a
feeling that newID() will be calculated for every row, which may be
inefficient. I was thinking of a more efficient way to get a random
row. Suppose there is an identity column, then you could
do something like this to get a random identity:

select min(id) from table2,
(select max(id) maxID, min(ID) minID from table2) t
where table2.id > t.minID + (t.maxID - t.minID)*rand()

What do you think?


That presumes that the values in the id column are decently evenly
distributed. If there are occasional large gaps, the distribution
will be skewed.

Yes, ORDER BY newid() + TOP 1 will read all rows, which for a large
table can be costly.

In SQL 2005 there is TABLESAMPLE, but apparently it's not that random
for smaller tables.
--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Jun 7 '06 #7
thanks guys... i got it to work using this method. This table should
not end up being very large and i'm not to worried about the cost of
this method... If anyone has a more efficient and presice method though
let me know...
Thanks
Jeremy
Jm********@gmail.com
Erland Sommarskog wrote:
JM********@gmail.com (JM********@gmail.com) writes:
i found that this does not get a random value... it only returns the
first record... how would i use this and return a random value.


select col1, col2, col3, col4, col5, col6
from table1
where col1 = @variable1 and col2 = @variable2
union
select col1, col2, col3, col4, col5, col6
from (SELECT TOP 1 col1, col2, col3, col4, col5, col6
from table2
where col2 = @variable2
order by newID()) AS d

You need a derived table into which you can put the TOP 1 and ORDER BY.

--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx


Jun 8 '06 #8

"Erland Sommarskog" <es****@sommarskog.se> wrote in message
news:Xn**********************@127.0.0.1...
Alexander Kuznetsov (AK************@hotmail.COM) writes:
My server has crashed and I cannot verify it right now, but I have a
feeling that newID() will be calculated for every row, which may be
inefficient. I was thinking of a more efficient way to get a random
row. Suppose there is an identity column, then you could
do something like this to get a random identity:

select min(id) from table2,
(select max(id) maxID, min(ID) minID from table2) t
where table2.id > t.minID + (t.maxID - t.minID)*rand()

What do you think?
That presumes that the values in the id column are decently evenly
distributed. If there are occasional large gaps, the distribution
will be skewed.

Yes, ORDER BY newid() + TOP 1 will read all rows, which for a large
table can be costly.

Not sure how large the table Alexander is looking at, but this is basically
what we're doing to retrieve a random ad.

Works well for us and was faster than our old method.

But we're generally selecting from a temple table of less than 100 records.

In SQL 2005 there is TABLESAMPLE, but apparently it's not that random
for smaller tables.
--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx

Jun 9 '06 #9

<JM********@gmail.com> wrote in message
news:11**********************@h76g2000cwa.googlegr oups.com...
thanks guys... i got it to work using this method. This table should
not end up being very large and i'm not to worried about the cost of
this method... If anyone has a more efficient and presice method though
let me know...
I don't, but one I've wanted to try in SQL 2005 (but haven't had time) is to
use ROW_NUMBER to number my results, get a max count and then use the random
function to select from that range.
Thanks
Jeremy
Jm********@gmail.com
Erland Sommarskog wrote:
JM********@gmail.com (JM********@gmail.com) writes:
i found that this does not get a random value... it only returns the
first record... how would i use this and return a random value.


select col1, col2, col3, col4, col5, col6
from table1
where col1 = @variable1 and col2 = @variable2
union
select col1, col2, col3, col4, col5, col6
from (SELECT TOP 1 col1, col2, col3, col4, col5, col6
from table2
where col2 = @variable2
order by newID()) AS d

You need a derived table into which you can put the TOP 1 and ORDER BY.

--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx

Jun 9 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: KENNY L. CHEN | last post by:
Dear experts, I have two tables in my Oracle 8i database: TEST (COL1,COl2,REC_NO) and TEST1 (COL1,COL2,REC_NO). Both tables are unique-indexed on (COL1,COL2,REC_NO). I think the following...
1
by: Jeff Blee | last post by:
I hope someone can help me get this graph outputing in proper order. After help from Tom, I got a graph to display output from the previous 12 months and include the average of that output all in...
5
by: Lyn | last post by:
This one is difficult to explain, so I will cut it down to the basics. I have a major table 'tblA' which has an autonum field 'ID-A' as primary key (of no significance to users). 'tblA' contains...
2
by: Thomas | last post by:
Hi All. I think that if I explain the database layout first it may be easier to ask my question. Table Name Field Name Test TestCode Description SpecimenRequirements FeeSchedule TestCode...
7
by: KoliPoki | last post by:
Hello every body. I have a small issue. Problem: I have a table with 4 descriptor columns (type). I need to formulate a query to retrieve a count for each type so I can group by...etc. The...
4
by: MR USER | last post by:
Hello, I made a union query that works perfectly in Access giving me a table that display all my nice records. when I try to retrieve these records in excel by either queriying the database or...
13
by: kev | last post by:
Hi all, I have created a database for equipments. I have a form to register the equipment meaning filling in all the particulars (ID, serial, type, location etc). I have two buttons at the end...
27
by: MLH | last post by:
How can I turn the following into a make-table query? SELECT & " " & AS Recipient FROM tblVehicleJobs INNER JOIN tblAddnlOwnrs ON tblVehicleJobs.VehicleJobID = tblAddnlOwnrs.VehicleJobID WHERE...
2
kcdoell
by: kcdoell | last post by:
Hello: I am trying to create a union query but do not have a lot of experience. Basically I have the below tables: The Tables: Table Name = tblPrior CreditRegIDFK; Number; Foreign Key...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.