-10

There are two tables as cats and dogs with 'id' and 'name' for each pet in both tables. The schema can be understood from below:

TABLE 'dogs'
    id INTEGER NOT NULL PRIMARY KEY,
    name VARCHAR (50) NOT NULL
TABLE 'cats'
    id INTEGER NOT NULL PRIMARY KEY,
    name VARCHAR (50) NOT NULL

The question asks to 'Write a query that select all distinct pet.name'

mansi_29
  • 3
  • 2
Devin Murzello
  • 9
  • 1
  • 1
  • 1

5 Answers5

5
SELECT name FROM dogs 
UNION 
SELECT name FROM cats

Using UNION removes the duplicate rows so using DISTINCT is not necessary here. If you want to display every pet name not only the distinct ones, you should use UNION ALL instead.

1
CREATE TABLE Pets(
ID INTEGER NOT NULL PRIMARY KEY
,Name VARCHAR(50) NOT NULL);

SELECT DISTINCT Name FROM Pets
Erfan Mohammadi
  • 424
  • 3
  • 7
1

Firstly create a temp table which will hold data from both the tables as mentioned below

create Temp table pet
as select name from dogs
union 
select name from cats;

Select the distinct names from the temp table

select distinct name from pet;
Adriaan
  • 17,741
  • 7
  • 42
  • 75
  • Your named the key(word)s to solution (`UNION` and `select DISTINCT`), good!. You could explain them and please check if [temp table is created like this in MySQL](https://stackoverflow.com/questions/5859391/create-a-temporary-table-in-a-select-statement-without-a-separate-create-table). – hc_dev Mar 11 '19 at 13:06
  • @hc_dev, do you mean to say the difference between `TEMP` and `TEMPORARY` keyword, both are acceptable – Rohit Hannurkar Mar 11 '19 at 13:36
  • I did not try to use this *abbrevation*. But good you have written that both will work. Since the asking OP is obviously new to SQL and MySQL it would be good teaching to explain keywords (add links: e.g. to [MySQL docs](https://dev.mysql.com/doc/refman/8.0/en/create-temporary-table.html), and avoid shortcut-keywords which could confuse when further researching SO. – hc_dev Mar 11 '19 at 13:49
0
select distinct name from dogs
union
select distinct name from cats
Bhanuchander Udhayakumar
  • 1,581
  • 1
  • 12
  • 30
Ab Bennett
  • 1,391
  • 17
  • 24
-1

select name from (select name, "dog" as pet from cats union all select name, "cat" as pet from dogs) group by name order by name

  • 3
    Welcome to Stack Overflow! Thank you for this code snippet, which might provide some limited short-term help. A proper explanation [would greatly improve](//meta.stackexchange.com/q/114762) its long-term value by showing *why* this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you've made. – Toby Speight Mar 20 '18 at 18:26
  • @TobySpeight How nicely put your comment! Should be an _auto-expandable template_ on SO for `[exp-code]`. – hc_dev Mar 11 '19 at 13:57