How to Create a Blank/Hardcoded Column in a SQL Query

How can I create a blank/hardcoded column in a sql query?

SELECT
hat,
shoe,
boat,
0 as placeholder
FROM
objects

And '' as placeholder for strings.

how to have hardcoded blank value of integer data type union with integer datatype column

If you want strings, then convert to strings:

select id , cast('' as varchar(255)) as employee_id from table1
union all
select id , cast(emp_id as varchar(255) as employee_id from table2;

Normally, you would use NULL rather than '', which is more compatible with more types:

select id , NULL as employee_id from table1
union all
select id , emp_id as employee_id from table2;

Note that I changed the union to union all. union incurs overhead for removing duplicates. Only use it if you want to incur that overhead.

How to hardcode row in Select statement?

You can just keep cross joining your table:

SELECT  TOP 1000 0 AS A, 1 AS B 
FROM someTable a
CROSS JOIN someTable b
CROSS JOIN someTable c
CROSS JOIN someTable d;

I am assuming from the fact that you have tagged with SSMS this is SQL Server, If not you may need to use LIMIT

SELECT  0 AS A, 1 AS B 
FROM someTable a
CROSS JOIN someTable b
CROSS JOIN someTable c
CROSS JOIN someTable d
LIMIT 1000;

The problem here is that if SomeTable only has 1 row, it won't matter how many times you cross join it, you will still only have one row. If you don't actually care about the values in the table, and only want to use it to generate rows then you could just use a system view that you know has more rows than you need (again assuming SQL Server):

SELECT  TOP 1000 0 AS A, 1 AS B
FROM sys.all_objects a;

Even on an empty database sys.all_objects will have 2083 rows. If you might need more then just CROSS JOIN the views:

SELECT  TOP 1000 0 AS A, 1 AS B
FROM sys.all_objects a
CROSS JOIN sys.all_objects b;

This will give you 4,338,889 rows.

Adding A Column that doesn't exist in a query

Yes, sure:

select a, b, 3 as c from table_test

That's it. It works on three db engines you've mentioned.

ISNULL returns 0 for a hardcoded column with NULL value

NULL does not have a clear type, but in a plain SELECT NULL, it gets returned as type int. When you have an expression involving an int and a char(N), int wins, the char(N) value gets converted to int, not the other way around. To make things more confusing, '' happens to be convertible to int without any problem, and the result of the conversion is 0.

SELECT ISNULL((SELECT CAST(NULL AS char(1)) AS col), '') should return an empty string.

Select a dummy column with a dummy value in SQL?

Try this:

select col1, col2, 'ABC' as col3 from Table1 where col1 = 0;


Related Topics



Leave a reply



Submit