Selecting TOP 4 records from multiple SQL Server tables. Using vb.net

sql-server, vb.net

Solution

You need to produce union of all tables and then order them to get last four:

SELECT TOP 4 date, link, anchor, thumb 
FROM
(
  SELECT date, link, anchor, thumb 
    FROM archive1
   UNION ALL
  SELECT date, link, anchor, thumb 
    FROM archive2
   UNION ALL
  SELECT date, link, anchor, thumb 
    FROM archive3
   UNION ALL
  SELECT date, link, anchor, thumb 
   FROM archive4 
) archive
ORDER BY date DESC

As you only take four records you might add TOP 4 clause to each query along with ORDER BY date DESC to speed things up.

Problem

I have about 4 different tables with the exact same column names. What I would like to do is select the top 4 records out of all of these tables combined ordered by date (as date is one of the columns that they all share). I keep getting erroneous statements, whether it be a syntax issue or ambiguous record etc. Essentially my statement is similar to: ``` SELECT TOP 4 date, link, anchor, thumb FROM archive1, archive2, archive3, archive4 ORDER BY date DESC ``` To state the obvious, I'm new to all this stuff. Thanks in advance for any assistance.

Original source