0

I have the following scenario where I have 2 tables and I am joining them to get some results from the second table, however I want to keep the similar column values in the order shown in the main table:

Below you can see a basic example of the issue:

EMP table DEPT table

They both have a common column called deptno (department number). When I query the department names from the DEPT table the result is the following:

Original

ACCOUNTING
RESEARCH
SALES
OPERATIONS

When I join the 2 tables as follows:

SELECT DISTINCT d.DNAME 
FROM DEPT d 
LEFT JOIN EMP e ON d.deptno = e.deptno

The result is the following:

JOIN

RESEARCH
SALES
ACCOUNTING
OPERATIONS

If, I sort the joined query, the result is the following:

SORTED

ACCOUNTING
OPERATIONS
RESEARCH
SALES

The question here is, How do I get the data sorted as follows when joining these 2 tables?

Original

ACCOUNTING
RESEARCH
SALES
OPERATIONS
Learner
  • 123
  • 1
  • 13
  • Since SQL includes data definition, a [mcve] for an [SQL question](//meta.stackoverflow.com/q/333952/90527) should include [DDL](//en.wikipedia.org/wiki/Data_definition_language) statements for sample tables (rather than an ad hoc table specification) and [DML](//en.wikipedia.org/wiki/Data_manipulation_language) statements for sample data (rather than a dump or ad hoc format). Desired results don't need to be presented as sample code, as results are the output of code and not code themselves. – outis Apr 22 '22 at 21:39
  • 1
    Does this answer your question? [How can I retrieve rows in a given sequence in Oracle / SQL?](//stackoverflow.com/q/12532399/90527) – outis Apr 22 '22 at 21:42

0 Answers0