0

I'm trying to execute the following query:

DELETE FROM table_name WHERE ID>9;

But i can't since the 'ID' field is of type 'varchar'. How can i cast it to 'int' and have it act properly? (deleting all rows with ID greater than 9 rather than converting it to a numeric varchar value)

8
  • 1
    DELETE FROM table_name WHERE ID::int > 9; Commented Oct 5, 2017 at 15:41
  • 3
    If you forsee a need to treat ID as a number, then consider storing it in a numeric column, not as text. Commented Oct 5, 2017 at 15:42
  • Trying your first solution i get invalid input syntax for integer: "" Commented Oct 5, 2017 at 15:44
  • The cast should work. Maybe you are doing something else or maybe you are using a really old version of Postgres. Let me post an answer. Commented Oct 5, 2017 at 15:46
  • It's because you have empty values on the column... and empty is not a number. Commented Oct 5, 2017 at 15:50

1 Answer 1

4

I don't know why you would store a numeric value as a string. You might want something more like:

DELETE FROM table_name
    WHERE regexp_matches(ID, '^[1-9][0-9]');

This will delete from the table any id that starts with two digits, where the first is not 0. If you attempt a conversion, then you might get a conversion error if not all ids are numbers. This will also work for long numbers that would overflow an int (although numeric would fix that problem).

EDIT:

For a general solution, I think I would write it as:

where (case when regexp_matches(id, '^[0-9]+$')
            then id::numeric
       end) > 70000

The case should prevent any error on non-numeric ids.

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

1 Comment

I'm working on somebody else's project, not mine. I didn't really understand your solution, how can i generalize it? Like 'WHERE ID > 70000'

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.