0

I have two tables. One with int as primary key and other with a varchar primary key.

When an empty string is inserted ( "" ) i get programming error for int but successfully stores for varchar. How does this work?

Is there a way to make varchar fields not accept empty strings? I want them to give some database error which i can catch.

6
  • 3
    Because the empty string is not an integer. Commented Nov 23, 2016 at 13:27
  • 1
    Yes. varchar means Variable-length character data. Commented Nov 23, 2016 at 13:31
  • Is there a way to make varchar fields not accept empty strings? Commented Nov 23, 2016 at 13:36
  • 1
    That is a different question entirely, but typically you validate fields using triggers. Commented Nov 23, 2016 at 13:40
  • 1
    @shadow0359: Looks like there's already an answer for that: stackoverflow.com/questions/2514178/… Commented Nov 23, 2016 at 13:44

4 Answers 4

4

When a empty string is inserted ( "" ) i get programming error for int

Because a string is not an int. And there's no way to automatically convert a non-numeric string to an int.

but successfully stores for varchar

Because a string is a varchar. Columns like CHAR and VARCHAR are for storing character data, which is what a string is.

None of these values are NULL. NULL is the absence of a value. An empty string is still a value.

Sign up to request clarification or add additional context in comments.

Comments

2

An empty string is not NULL, in almost every database and by the ANSI definition.

It so happens that Oracle treats empty strings as NULL values, which is generally rather confusing. But that is an exception to the SQL language.

Comments

1

An empty string is different from null. (This is true in MySQL and in many programming languages as well.) Try inserting null into the primary key for the varchar. It should fail on the insert - just like the int.

As @David says above, the empty string cannot be converted to an int, and so MySQL chooses null instead.

Comments

0

Not sure what you are trying to do, and we need to see the code to know what is the best way to fix this problem, but you can try this:

CASE WHEN IN_IntValue = '' THEN NULL ELSE IN_IntValue

In general, only Oracle as far as I know look at empty string as NULL. In MySQL they are two different things.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.