Reputation: 47
I am trying to solve a SQL query where i ALWAYS get 4 records, if one of the records does not exist it can be null.
Let's say i have the following table named names
Name id: Name:
1 John
2 Mike
3 Marcel
Now i will use the following sql query:
Select names.name from names
I will get the following results
John
Mike
Marcel
But what i am trying to achieve is:
John
Mike
Marcel
NULL
so i always want 4 records even when there are only 3. Its not an option to add a 4th.
Someone know how to achieve this?
Upvotes: 0
Views: 180
Reputation: 8497
You can try with simple SQL Query. Assuming that you are using SQL Server.
SELECT TOP 4
id,name
FROM
(SELECT id, name from t
UNION ALL
SELECT TOP 4
NULL,null
FROM sys.columns) T
Upvotes: 0
Reputation:
You didn't specify your DBMS so this is ANSI SQL:
with numbers (nr) as (
values (1),(2),(3),(4)
)
select names.name
from numbers
left join (
select id,
name,
row_number() over (order by id) as rn
from names)
) names on names.rn = numbers.nr;
If you don't know if there are 3 or 4 rows in the table, you can apply a limit the join condition: on names.rn = numbers.nr and names.nr <= 3
. This will ensure that you will never retrieve more than three rows from the names
table.
If you you only care about the ids 1,2,3 and there will never be other IDs you can do something like this:
with numbers (nr) as (
values (1),(2),(3),(4)
)
select names.name
from numbers
left join names on names.id = numbers.nr;
You can replace 4
with any value that will definitely not exist in your table.
Upvotes: 0
Reputation: 1270401
You can do this with a union all
and order by
. You don't specify the database, but the following gives one method:
select name
from (select name
from table t
limit 4
) union all
(select null union all
select null union all
select null union all
select null
)
order by (case when name is not null then 1 else 0 end) desc
limit 4;
Some aspects of the syntax might vary, depending on the database, but the idea is the same.
Upvotes: 2