SQL Update query question.

Can someone decipher and explain what this query is doing.
I need to explain this in non-sql terms..

UPDATE customer_applications
SET loan_purpose = fetch_loan_purpose_subquery.loan_purpose
FROM (
SELECT id AS customer_application_id,
CASE
WHEN loan_purpose_from_step_1_subquery.loan_purpose is null
THEN substring( substring(information FROM
': &' || substring(information from E':step_1: \\*([0-9]+)') ||
'.*:step_1:' ) from E'loan_purpose: ([^\n]+)')
ELSE loan_purpose_from_step_1_subquery.loan_purpose
END AS loan_purpose
FROM (
SELECT
customer_applications.id,
customer_applications.information,
/* Look for things of the form
loan_purpose: ([^\n]+)'
occurring after :step_1 */
substring(
substring(customer_applications.information FROM E':step_1.*')
FROM E'loan_purpose: ([^\n]+)')
AS loan_purpose
FROM customer_applications
INNER JOIN loans ON loans.customer_application_id = customer_applications.id
ORDER BY id DESC) loan_purpose_from_step_1_subquery
) fetch_loan_purpose_subquery
WHERE customer_applications.id =
fetch_loan_purpose_subquery.customer_application_id;

Open in new window


Below is an example of a value in customer_applications.detail (which is a text blog):

:lead_raw: !ruby/
hash:ActiveSupport::HashWithIndifferentAccess
Loan_Amount_Requested: '5000'
Purpose_Of_Loan: ''
First_Name: John
Last_Name: Carson
Email: jcarson@gmail.com
Primary_Phone: '5555555555'
Home_Street_Address: 111 ABC Street
Home_City: New Orleans
Home_State: LA
Home_Zip: '70119'
Home:Type: rent
Income_Net_Monthly: '2501'
Employer_Time: '24'
PayFrequency: BIWEEKLY
Employer_Name: ABC Steel
Employer_Phone: '5555555555'
Employer_Street_Address: 123 Main Street
Employer_City: New Orleans
Employer_State: LA
Employer_Zip: '70119'
SSN: '999999999'
Bank_Name: Bank ABC
Bank_Routing_Number: '5555555555'
Bank_Account_Number: '5555555555'
Bank_Account_Type: checking
Date_of_Birth: 1915-10-08
Income_Type: employment
Home_Time: '24'
controller: leads
action: inbound
lead_provider: personal_96_151
:lead: &99451720
:loan_amount_requested: '5000'
:loan_purpose: 'boat repair'
:email: jcarson@gmail.com
:person_attributes:
:first_name: John
:last_name: Carson
:home_phone: '5555555555'
:ssn: '55555555'
date_of_birth: 1985-10-08
:bank_accounts_attributes:
0:
:name: FIRST NAT BANK
:routing_number: '555555555'
:account_numbner: '555555555'
account_type: checking
:incomes_attributes:
0:
:monthly_net_income: '2501'
:time_at_job: '24'
income_type: employment
:pay_frequency: BIWEEKLY
:employer_attributes:
:name: ABC Steel
:phone_number: '5555555555'
address_attributes:
:state: LA
:address_1: 2811 ABC Street
:city: New Orleans
:zip: '70119'
:rent_or_own: rent
:time_at_address: '24'
:stepC_1 *99451720

Open in new window

swaggrKAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Vikas GargAssociate Principal EngineerCommented:
HI,

is this query working fine ?

Since I could not get this working due to errors in it.
swaggrKAuthor Commented:
It is more of a conceptional question. I am trying to figure out what it is trying to accomplish in non-technical terms.
Vitor MontalvãoMSSQL Senior EngineerCommented:
That's not SQL Server. May be MySQL but can be sure of that.
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Vitor MontalvãoMSSQL Senior EngineerCommented:
Looks like is updating loan_purpose where the value is null with this value returned from this formula:
substring( substring(information FROM ': &' || substring(information from E':step_1: \\*([0-9]+)') ||'.*:step_1:' ) from E'loan_purpose: ([^\n]+)')
Vikas GargAssociate Principal EngineerCommented:
HI,

@Vitor, it can be seen that the query is trying to update based on the logic
and I think the help is asked for understanding of that Logic...
swaggrKAuthor Commented:
Correct. I am trying to understand the logic in very basic terms..
Vikas GargAssociate Principal EngineerCommented:
Hi,

But SwaggrK, I am unable to identify the logic since the part of the query with substring is wrong

May be you should write actual running query if exist for logic description and if you do not have any query and want to develop is as per the logic then have to provide with example.
PortletPaulEE Topic AdvisorCommented:
MySQL's SUBSTRING function allows

           SUBSTRING(str FROM pos FOR len)

which T-SQL does not support. So the query in the question is more likely to be MySQL.

Can you confirm which database is being used please? (looks much more likely to be MySQL)

Also. You refer to `customer_applications`.`detail`
but the query uses `customer_applications`.`information`

Which is the correct column name? (`Detail` or `Information`)

Note
The uses of SUBSTRING() in the query however would not work.
SUBSTRING(..... FROM ????) requires a POSITION in the string at ????

Hence there probably should be uses of INSTR()

e.g.
            substring(customer_applications.information FROM E ':step_1.*')

probably SHOULD be

              substring(`information` FROM INSTR(`information`,':step_1') )

see: https://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_instr
==================

But the SQL query provided appears to aim at this:

a. Find ':step_1' followed by any digit 0 to 9
b. then find, AFTER that, the first occurrence of 'loan_purpose:` followed by a line break (I think)
c. if that value is NULL, then concatenate a string which looks quite strange
d. Update a column called `loan_purpose` in the table customer_applications with either the discovered or concatenated string (b. or c.)

formatted query:
UPDATE customer_applications
SET loan_purpose = fetch_loan_purpose_subquery.loan_purpose
FROM (
     SELECT
        id AS customer_application_id
      , CASE
            WHEN loan_purpose_from_step_1_subquery.loan_purpose IS NULL 
                THEN substring(
                               substring(information FROM ': &' || substring(information FROM E ':step_1: \\*([0-9]+)') || '.*:step_1:') FROM E 'loan_purpose: ([^\n]+)') 
            ELSE loan_purpose_from_step_1_subquery.loan_purpose 
        END AS loan_purpose
     FROM (
          SELECT
                customer_applications.id
               , customer_applications.information
               /* Look for things of the form
                loan_purpose: ([^\n]+)'
                occurring after :step_1 */
               , substring(substring(customer_applications.information FROM E ':step_1.*') FROM E 'loan_purpose: ([^\n]+)') AS loan_purpose
          FROM customer_applications
          INNER JOIN loans ON loans.customer_application_id = customer_applications.id
          ORDER BY id DESC
          ) loan_purpose_from_step_1_subquery
     ) fetch_loan_purpose_subquery
WHERE customer_applications.id = fetch_loan_purpose_subquery.customer_application_id
;

http://sqlfiddle.com/#!9/f47faa/3

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.