Here are some tricky Sql statements that can be used in some specific cases. I figured them out in certain cases where I needed to do data manipulation directly on the database instead of writing script to accomplish them. I will describe them in case study style.
In one of my project there is a user table containing fields like userId, UserName, UserLoginID, Password etc. The UserLoginID field is basically the email address. Almost 95% of the email addresses belongs to a specific domain that is the domain of the project. Let’s say testproject.com. The table contains approx 12,000 records. In that project client decided to shift their main tld from .com to .org like testproject.com to testproject.org. Now they asked me to change the all the users’ email from .com to .org. That means email@example.com to firstname.lastname@example.org I needed to do this job within a shortest span of time. So I decided to run a sql command directly in the database to do the modification. A simple UPDATE sql won’t work in that situation as I needed to change some part of a field and also update statement shouldn’t affect those rows which do not contain testproject.com. So I tried with different types of update sql to do the job but finally derived the following one :-
UPDATE tblUser SET UserLoginID = REPLACE(UserLoginID, ‘ testproject.org’, ‘ testproject.com’);
The beauty of this statement lies in the usage of replace function. This replace function will synchronously select records having ‘testproject.com’ implementing functionality of the Where clause and generate the value to be set for the field UserLoginID as