Q

# Select another row if first choice is not available

## I have a table with two columns, col1 and col2. I would like, for a given col1, to return the record whose col2 is CM, but if col2 as CM is not available, then return the record whose col2 is ML. Can this be achieved using an SQL query?

I have a table with two columns, col1 and col2. The data in the table is as follows:

col1 col2
4587 TP
4587 ML
4587 CM
3509 TP
3509 BL
3509 ML

Notice that for 4587, CM is available. For 3509, CM is not available. I would like, for a given col1, to return the record whose col2 is CM, but if col2 as CM is not available, then return the record whose col2 is ML. Can this be achieved using an SQL query?

Yes, there are several ways to do it. Here's one way that very closely resembles the way you stated the problem:

select col1, col2
from yourtable
where col2 = 'CM'
union all
select col1, col2
from yourtable as t1
where col2 = 'ML'
and not exists
( select *
from yourtable
where col1 = t1.col1
and col2 = 'CM' )

This method employs a UNION in which the first SELECT returns CM rows, while the second SELECT returns ML rows for each col1 that doesn't have a CM row. Notice that the NOT EXISTS subquery is correlated. In my opinion, this solution is a good one because its purpose is clear and easy to understand.

Now here's another way to do it:

select col1, min(col2)
from yourtable
where col2 in ( 'CM', 'ML' )
group
by col1

This solution uses grouping and the MIN aggregate function, and relies on the fact that CM collates lower than ML. It works perfectly well, and it's more efficient than the first solution, too. However, in my opinion, it's not as good. What happens if we need to return a third column from the row? Suddenly it no longer works at all.

This was last published in December 2005

## Content

Find more PRO+ content and other member only offers, here.

#### Have a question for an expert?

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

#### Start the conversation

Send me notifications when other members comment.

## SearchDataManagement

• ### With better scaling, semantic technology knocks on enterprise's door

Cambridge Semantics CTO Sean Martin says better scalability can lead to richer representations of data. Such advances are behind ...

• ### Big data management and analytics weather tumult -- with more in store

Cloud had a big impact on big data management and analytics last year. Machine learning and streaming designs will contribute to ...

• ### Embedded analytics to feel widest impact of machine learning projects

Ovum analyst Tony Baer discusses machine learning tools, IoT-driven streaming analytics and Hadoop in the cloud, all of which ...

• ### Researchers work on AI algorithms to detect fake news

A new challenge to identify fake news will test the boundaries of AI technology and offer a proving ground for innovative new ...

• ### Don't let a data-driven approach ax judgment from analytics equation

Data analytics can help improve decision-making in organizations. But human intuition and judgment need to be part of the picture...

• ### Lack of skills remains one of the biggest data science challenges

Many enterprises are struggling with the complexity of today's big data and data science ecosystem, though they recognize the ...

## SearchSAP

• ### SAP futurists name five future technology trends to plan for now

Three SAP futurists explain what future technology trends in augmented reality, blockchain, AI, robotics, and contingent labor ...

• ### Abakus acquisition beefs up SAP Hybris marketing portfolio

SAP acquires Abakus marketing measurement software for SAP Hybris marketing suite; openSAP adds new courses for S/4HANA, data ...

• ### The five best ways to manage SuccessFactors support after go-live

SuccessFactors skills are scarce in the job market, but you can manage a new system with a few organizational moves and a solid ...

## SearchSQLServer

• ### Four trends that will impact SQL Server DBAs in 2017

Flash storage adoption, cloud computing's growth, Linux's increased importance and broader big data integration are a few trends ...

• ### DATEADD and DATEDIFF SQL functions for datetime values

DATEADD and DATEDIFF SQL functions allow you to easily perform calculations, like adding a time interval from a datetime value. ...

• ### SQL Server on Linux signals Microsoft's changing development landscape

Expert Joey D'Antoni explains what SQL Server on Linux and the addition of some Enterprise Edition features to the database's ...

## TheServerSide

• ### Is JSON and XML your REST performance bottleneck?

Learn how ASCII encoding formats like JSON and REST can adversely impact server application performance compared with emerging ...

• ### Making multi-cloud deployment a reality at Netflix with Spinnaker

Learn how Netflix leveraged automation and Spinnaker to perform 4,000 multi-cloud deployments per day.

• ### The benefits of Java microservices in a Docker and DevOps world

To seasoned developers, microservices may sound like SOA by another name. But Java microservices apps delivered via Docker ...

## SearchDataCenter

• ### Test yourself on modern data center networking architecture

Evolving business needs demand a new approach to data center networking. Keep yourself updated on SDN, VXLAN and other ...

• ### To reap the benefits of hyper-convergence, manage it right

Use a policy-based approach to manage hyper-converged infrastructure.

• ### Easier management among the benefits of hyper-converged infrastructure

Implementing a hyper-converged infrastructure product is a big decision and one that needs to include a discussion about how ...

## SearchContentManagement

• ### Using Microsoft MyAnalytics to improve workers' time management

Microsoft MyAnalytics has been hailed as the next great thing for analyzing worker productivity. But how can employees be assured...

• ### Is the Drupal content management system right for your business?

The open source Drupal content management system offers users responsive design and WYSIWYG content and web development tools, as...

• ### Manage your content with the IBM Digital Experience WCM platform

IBM Digital Experience is a WCM platform that offers users features for creating and managing digital content that can be ...

## SearchFinancialApplications

• ### Experts lack consensus on discrimination risks of video interviewing

When used too early in the hiring process, video can lead to discrimination based on race, age or sex, but it can have positive ...

• ### Five frontrunners named in enterprise performance management software

Oracle, Anaplan, Tagetik, IBM and Adaptive Insights lead the pack in an evaluation of EPM software that examines functional ...

• ### Mobile HR deployment slowed by security worries, lack of BYOD policies

Vendors keep hammering the mobile HR message, but organizations are slow to buy into the pitch. One major reason is HR's failure ...

Close