Q
Problem solve Get help with specific problems with your technologies, process and projects.

# Sorting by weekday as text

I have a table with one field which is VARCHAR2 datatype containing weekdays randomly like this:

```FRIDAY
MONDAY
SATURDAY
SUNDAY
THURSDAY
TUESDAY
WEDNESDAY
```

I want to fetch data in order in a single SQL statement without using any user-defined functions. Is there any function in Oracle that returns the weekday (as a number) for a particular day (a string)? That is, if I pass 'WEDNESDAY', then it returns 4, ...
Solution 1: The simplest and fastest way to do it is with CASE or DECODE:

```SELECT DISTINCT
dow_val,
weekday
FROM    (
SELECT  weekday,
DECODE ( UPPER (TRIM (weekday)),
'SUNDAY',    1,
'MONDAY',    2,
'TUESDAY',   3,
'WEDNESDAY', 4,
'THURSDAY',  5,
'FRIDAY',    6,
'SATURDAY',  7,
NULL  -- None of the above
)  AS dow_val
FROM    table_x
)
ORDER BY
dow_val;

DOW_VAL WEEKDAY
---------- ---------
1 SUNDAY
2 MONDAY
3 TUESDAY
4 WEDNESDAY
5 THURSDAY
6 FRIDAY
7 SATURDAY

7 rows selected.
```

Solution 2: We can reduce the typing (and the efficiency) by replacing the big DECODE statement with:

```        TO_CHAR ( NEXT_DAY ( SYSDATE, weekday),
'D'
)
```

TO_CHAR (dt, 'D') returns a single character, not a number, but it works just as well for sorting. The first argument to TO_CHAR must be a DATE, and all we have is a string; that's why we call NEXT_DAY (dt, wstring), which returns a date whose day-of-the-week is given in wstring.

Solution 3: Look how much cleaner your code would be if you were willing to use a user-defined function:

```SELECT DISTINCT
dow_val,
weekday
FROM    (
SELECT  weekday,
dow (weekday)  AS dow_val
FROM    table_x
)
ORDER BY
dow_val;
```

This solution is nearly as efficient as Solution 1, and it's cleaner than Solution 2. The function isn't hard to write, and you only have to write it once. With either of the solutions above, you have to repeat the code in every statement where you need it.

```CREATE OR REPLACE FUNCTION  dow
(
in_weekday_text  IN  VARCHAR2
)
RETURN  PLS_INTEGER

--      *************
--      **  d o w  **
--      *************

--  dow returns a number (1-7) corresponding to the day of
--  the week passed in in_weekday_text.  Inputs do not
--  need to be capitalized, and may include leading or trailing
--  spaces, but they do have to be full words (not like 'MON.')
--  If in_weekday_text is not one of the seven weekday names,
--  dow returns NULL.

IS
BEGIN
RETURN  CASE  UPPER (TRIM (in_weekday_text))
WHEN   'SUNDAY'    THEN  1
WHEN   'MONDAY'    THEN  2
WHEN   'TUESDAY'   THEN  3
WHEN   'WEDNESDAY' THEN  4
WHEN   'THURSDAY'  THEN  5
WHEN   'FRIDAY'    THEN  6
WHEN   'SATURDAY'  THEN  7
ELSE  NULL
END;
END;
/
SHOW ERRORS

GRANT  EXECUTE  ON  dow  TO  PUBLIC;

CREATE PUBLIC SYNONYM  dow  FOR  foo.dow;
```

This was last published in November 2003

## 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

• ### Hyperledger Fabric offers path to enterprise blockchain future

Blockchain arose from bitcoin, but it's looking to find a place in the enterprise. Frameworks like Hyperledger Fabric could ...

• ### MongoDB 4.0 takes ACID transactions to multi-document level

MongoDB is taking a deeper step into SQL-style processing waters with a 4.0 update that brings increased support for ...

• ### Data lake concept needs firm hand to pay big data dividends

Data lakes pose technology deployment and data management challenges that can leave analytics users high and dry if the ...

• ### AI functionality limited today but could be a game-changer

Limited AI capabilities could soon give way to technology that is truly transformative for enterprises, surpassing the overhyped ...

## SearchSAP

• ### ControlPanelGRC app eases Steelcase's compliance pain

When Steelcase's SAP environment grew in size and complexity, it turned to Symmetry ControlPanelGRC to save time, have more ...

• ### Translytical data platforms emerge with SAP HANA as a leader

SAP HANA is a leading translytical platform, according to Forrester, and consulting firm Convergent IS says the combination of ...

• ### SAP HANA and Esri combine for geospatial database platform

SAP and Esri are combining SAP HANA's in-memory database capabilities with Esri geospatial applications, and utilities are taking...

## SearchSQLServer

SQL Operations Studio simplifies routine administration of SQL Server and Azure SQL databases, making database development and ...

• ### Meltdown and Spectre fixes eyed for SQL Server performance issues

Microsoft has responded to the Spectre and Meltdown chip vulnerabilities with patches and other fixes. But IT teams need to sort ...

• ### Five SQL Server maintenance steps you should take -- ASAP

Putting off SQL Server administration tasks can lead to database problems. Enact these often-neglected maintenance items to help ...

## TheServerSide.com

• ### Pluralsight IQ, Stack Overflow boost developer street cred

Tying the Pluralsight IQ skills test to the Stack Overflow Developer Story helps developers measure their technical skills and ...

• ### Why this quantum computing breakthrough is a security risk

Quantum computing will void pretty much all security encryption techniques and open the door to hackers. Here's how to protect ...

• ### Database automation drives DevOps into the persistence layer

A new breed of software tools is driving DevOps processes deep into the persistence layer, as database automation and continuous ...

## SearchDataCenter

• ### Evaluate read-intensive and write-intensive SSD use cases

Consider write wear, performance and other factors when choosing between read-intensive, write-intensive and mixed-use ...

• ### Some hyper-converged infrastructure use cases pose pitfalls

Hyper-converged infrastructure adoption is skyrocketing, but that doesn't mean that the technology is the best choice for every ...

• ### Dell hyper-converged reorg streamlines products, ups CI odds

Market pressures and manufacturing synergies drove Dell to integrate its HCI and CI products with its core business units, but ...

## SearchContentManagement

• ### Content management in the cloud a main theme in 2018

The future of content management resides in the cloud and with AI, as several 2018 conferences will assure you.

• ### Six things to know about today's SharePoint implementations

As companies migrate their on-premises Microsoft SharePoint sites to the cloud, here are some things they should know about the ...

• ### Upgrades for the SharePoint Online portal

As more organizations migrate SharePoint sites to the cloud, Microsoft has increased at-a-glance dashboard data and analytics to ...

## SearchHRSoftware

• ### Don't overlook the many benefits of Microsoft Excel for HR

The maligned spreadsheet tool is no substitute for enterprise apps like HRMS and people analytics, but it will do in a pinch and ...

• ### HR is failing to use people analytics tools, new report says

Human resource departments fail to use people analytics tools effectively, a new global study concludes. The findings were called...

• ### Does your company need new human resource management tools?

Finding the best human resource management tools starts with identifying your company's present and future needs, before ...

Close