Operand data type nvarchar is invalid for divide operator.

Sudarshan Sampath 65 Reputation points
2023-04-18T06:32:02.2566667+00:00

When i am using the statement, SELECT location, date, total_cases, total_deaths, (total_deaths /total_cases) FROM CovidPortfolioProject..coviddeaths I'm getting the error Msg 8117, Level 16, State 1, Line 17 Operand data type nvarchar is invalid for divide operator.

SQL Server Reporting Services
SQL Server Reporting Services
A SQL Server technology that supports the creation, management, and delivery of both traditional, paper-oriented reports and interactive, web-based reports.
3,063 questions
SQL Server | Other
{count} votes

5 answers

Sort by: Most helpful
  1. Raisul Islam Akil 45 Reputation points
    2023-08-28T19:45:33.2933333+00:00

    Need to convert the data type. I hope this will solve your problem. @Sudarshan Sampath


    Select Location, date, total_cases, total_deaths, (CONVERT(float, total_deaths) / NULLIF(CONVERT(float, total_cases), 0))*100 as DeathPercentage

    From PortfolioProjects..CovidDeaths

    order by 1,2


    9 people found this answer helpful.

  2. Anonymous
    2023-04-18T06:43:43.13+00:00

    Hi @Sudarshan Sampath

    The error message is already obvious. You need to check the character types of the total_deaths and total_cases.

    You can take a look at the requirements for dividend and divisor in the official documentation.

    https://learn.microsoft.com/en-us/sql/t-sql/language-elements/divide-transact-sql?view=sql-server-ver16

    Best regards,

    Percy Tang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    2 people found this answer helpful.
    0 comments No comments

  3. Olaf Helper 47,441 Reputation points
    2023-04-18T06:48:52.13+00:00

    Operand data type nvarchar is invalid for divide operator.

    I think you get a pretty clear error message. You can apply math operation like a divison only on numeric data, not on string. You may have to convert first the strings to nuermic, but with that less on informations ... Please post table design as DDL, some sample data as DML statement and the expected result.

    0 comments No comments

  4. Solomon Opi 0 Reputation points
    2023-08-01T13:17:19.0033333+00:00

    In your particular query, try using the Cast() function.

    0 comments No comments

  5. Paria Faez 15 Reputation points
    2024-01-10T04:57:07.07+00:00

    You need to converts a value to a float datatype

    Select location, date, total_cases, total_deaths, (cast(total_deaths as float)/cast(total_cases as float))*100 as DeathPercentage

    From CovidDeath

    order by 1,2


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.