Include table name in column from select wildcard sql - sql

Is it possible to include table name in the returned column if I use wildcard to select all columns from tables?
To explain it further. Suppose I want to join two tables and both tables have the column name “name” and many other columns. I want to use wildcard to select all columns and not explicitly specifying each column name in the select.
Select *
From
TableA a,
TableB b
Where
a.id = b.id
Instead of seeing two column with same name "name", could I write a sql to return one column name as "a.name" (or TableA.name) and one as "b.name"(or TableB.name) without explicitly putting the column name in select?
I would prefer a solution for mssql but other database could be a reference too.
Thanks!

You can use select a.*, ' ', b.* from T1 a, T2 b to make it more visible where columns from T1 end and columns from T2 begin.

You are basically joining two tables on the ID field, so you will only see one column labeled "ID", not two, because you are asking to see only those records where the ID is the same in table a and table b: they share the same id.

Try ...
SELECT 'TableA' AS 'Table', A.* FROM TableA A
WHERE A.id IN (SELECT id FROM TableB)
UNION
SELECT 'TableB' AS 'Table', B.* FROM TableB B
WHERE B.id IN (SELECT id FROM TableA)
ORDER BY id, [Table]

Related

How to distinguish the same field names of two Oracle tables?

I have two different table.
One table has 70 Columes, the other has 80.
I want to display all the Columes of the two tables.
But there are some Columes with the same Columes-name.
EX:
SELECT *
FROM TABLE1 A INNER JOIN
TABLE2 B ON A.ID = B.ID
enter image description here
I want to distinguish which table does the Columes comes from.
I know have to list your column list explicitly and provide aliases to them in the SELECT list.
How can I modify my program?
Is there any other easier way.
Because there are too many field names
You'll have to list your column list explicitly and provide aliases to them in the SELECT list.
SELECT
A.ID AS A_ID,
B.ID AS B_ID
FROM TABLE1 A INNER JOIN
TABLE2 B ON A.ID = B.ID
As a best practice
Never use SELECT * in production queries, always list the required columns explicitly. Why is SELECT * considered harmful?
When you have more than one table referenced in the query (e.g you join two tables), always give an alias to all tables and use that alias when you are referencing any columns of the tables.
You can build a query and let it to compose the query for you. It's not that hard as it seems
I've created tables TEST1 and TEST2 with identical column names and managed database to list me all the columns with prefixes.
select 'select ' txt from dual
union all
select listagg('t1.' || atc.COLUMN_NAME, ', ') within group (order by atc.COLUMN_NAME) || ', '
from all_tab_cols atc
where table_name = 'TEST1'
union all
select listagg('t2.' || atc.COLUMN_NAME, ', ') within group (order by atc.COLUMN_NAME)
from all_tab_cols atc
where table_name = 'TEST2';
The output is
TXT
----------
select
t1.NUM_COL, t1.TEXT_COL,
t2.NUM_COL, t2.TEXT_COL
So you may run the query, copy the output and then add the FROM and WHERE and other parts you need
If the only column names in common are used a JOIN keys, then you can phrase this as:
SELECT *
FROM TABLE1 A INNER JOIN
TABLE2 B
USING (ID);
The ID column only appears once in the result set.
If other columns are common, then you need to use column aliases. Sometimes, it is convenient to use something like this:
SELECT A.*, B.col1 as b_col1, B.col2 as b_col2, . . .
FROM TABLE1 A INNER JOIN
TABLE2 B
USING (ID);
To make this simpler, you can use the metadata tables.

How to print all columns when columns are dynamic and one common column is present?

Lets say i have 2 table A,B .In both the tables (id) is the common column ,and rest columns dynamic.so write a query to print id of "A" and rest all columns .
A(id,name,city),B(id,phone,phone_num). Here I only know "id" column ,rest columns(name,city,phone) are coming dynamically,So i can not use A.name,A.city,B.phone etc .In
select * from A FULL OUTER JOIN B ON A.id = B.id;
is printing id column twice.
If you want to display the id column only once, use the using clause for the join :
SELECT *
FROM tableA a
JOIN tableB b using (id)
The using clause as the effect that the join column(s) are only included once with select *.
If I'm not wrong, you want to display all the column of both the tables and the common column i.e id should come only once.If that's the case use the below query and replace the column name with the column names you want to display.
SELECT a.id,a.column1,a.column2,b.column1,b.column2
FROM tableA a
INNER JOIN tableB b ON a.id=b.id
Demo
create table my_table_1 (id int,c1 int,c2 int,c3 int);
create table my_table_2 (id int,c4 int,c5 int);
select array_to_string(array_agg (table_name || '.' || column_name::text),',')
from information_schema.columns
where table_name in ('my_table_1','my_table_2')
and not (table_name,column_name) = ('my_table_2','id')
my_table_1.id,my_table_1.c1,my_table_1.c2,my_table_1.c3,my_table_2.c4,my_table_2.c5

Getting common fields of two tables in PL/SQL

Suppose Table A and Table B have various fields. What is an easy way to get the common fields among Table A and Table B ? I want to do an inner join on these tables but I don't know what the common fields are.
Note that this is in PL/SQL. When I table A. or B. I get the list of fields names of each table in a drop down menu. But I would like to get the common fields.
It depends on what do you mean by "common fields".
If you want to get all colums which names are the same in both tables, then you can use this query:
SELECT t1.column_name
FROM user_tab_columns t1
JOIN user_tab_columns t2
ON t1.COLUMN_NAME = t2.COLUMN_NAME
/*
AND t1.DATA_TYPE = t2.DATA_TYPE
AND t1.DATA_LENGTH = t2.DATA_LENGTH
*/
WHERE t1.table_name = 'A'
AND t2.table_name = 'B'
;
Demo: http://sqlfiddle.com/#!4/2b662/1
But if you look at tables in the above demo, you will see that table A has a column named X with datatype VARCHAR2, and table B has also a column named X but of different type INT.
If you want to get all columns that have the same names, the same datatypes and the same length, then uncomment respective conditions in the above query.
Do mean something like this:
TableA has 2 columns: Id and Name.
TableB has 2 columns: Name and PhoneNumber
Query:
SELECT A.Id, A.Name, B.PhoneNumber
FROM TableA A, TableB B
WHERE A.Name = B.Name;
Edit:
If you want know what Columns names there a re from your table I believe you can use DESC TableA. Then you get a list a column names. You can use those to compaire against another list, for example from TableB.

Issues with SQL Select utilizing Except and UNION All

Select *
From (
Select a
Except
Select b
) x
UNION ALL
Select *
From (
Select b
Except
Select a
) y
This sql statement returns an extremely wrong amount of data. If Select a returns a million, how does this entire statement return 100,000? In this instance, Select b contains mutually exclusive data, so there should be no elimination due to the except.
As already stated in the comment, EXCEPT does an implicit DISTINCT, according to this and the ALL in your UNION ALL cannot re-create the duplicates. Hence you cannot use your approach if you want to keep duplicates.
As you want to get the data that is contained in exactly one of the tables a and b, but not in both, a more efficient way to achieve that would be the following (I am just assuming the tables have columns id and c where id is the primary key, as you did not state any column names):
SELECT CASE WHEN a.id IS NULL THEN 'from b' ELSE 'from a' END as source_table
,coalesce(a.id, b.id) as id
,coalesce(a.c, b.c) as c
FROM a
FULL OUTER JOIN b ON a.id = b.id AND a.c = b.c -- use all columns of both tables here!
WHERE a.id IS NULL OR b.id IS NULL
This makes use of a FULL OUTER JOIN, excluding the matching records via the WHERE conditions, as the primary key cannot be null except if it comes from the OUTER side.
If your tables do not have primary keys - which is bad practice anyway - you would have to check across all columns for NULL, not just the one primary key column.
And if you have records completely consisting of NULLs, this method would not work.
Then you could use an approach similar to your original one, just using
SELECT ...
FROM a
WHERE NOT EXISTS (SELECT 1 FROM b WHERE <join by all columns>)
UNION ALL
SELECT ...
FROM b
WHERE NOT EXISTS (SELECT 1 FROM a WHERE <join by all columns>)
If you're trying to get any data that is in one table and not in the other regardless of which table, I would try something like the following:
select id, 'table a data not in b' from a where id not in (select id from b)
union
select id, 'table b data not in a' from b where id not in (select id from a)

SQL join, getting multiple columns with same name

I have one table with a column ID and SERVICE_TYPE_TEXT, and another table with columns
ID, SERVICE_TYPE ...
and lots of other columns.
The SERVICE_TYPE in the second table contains the ID from the first table. I want to query so I can get the SERVICE_TYPE_TEXT from the first table that matches the ID given in the second table.
I've tried to join, and setting different names on ID with AS, but always at the end of the query result I get the original ID from the first table with column name ID, as well as the name I defined in the AS.
Any suggestions on how I can get the ID from the first table to stay away ? :)
Try something like this,
SELECT a.ID AS ServiceID,
a.Service_Type_Text,
b.ID AS table2ID,
b.Service_Type
FROM table1 a
INNER JOIN table2 b
ON a.ID = b.Service_Type
Set your query so that it returns all data from the second table but only the required field (column) from the first.
Something like this:
SELECT TAB1.SERVICE_TYPE_TEXT, TAB2.*
FROM TAB1
INNER JOIN
TAB2
ON TAB1.ID = TAB2.SERVICE_TYPE
TRY
SELECT a.ID AS ServiceID,
a.Service_Type_Text,
b.ID AS table2ID,
b.Service_Type
FROM table1 a
INNER JOIN table2 b
ON a.ID = b.Service_Type AND b.ID='YOUR_ID';