ioSamurai ioSamurai - 1 year ago 43
SQL Question

Please help me understand SQL vs C like programming?

Specifically I am trying to grasp how SQL statements differ from normal C style programming, I can't seem to understand how to do stuff like "for every userid in this table that has another column of data equal to such and such, run this stored procedure" which in programming would be a for loop, how the heck do you do stuff like that?

Or like, for each row in tableA that has a contentID of 11, add a new row to tableB containing this data and the userID from the row of tableA found containing contentID of 11...

Anyone mind possibly writing a bit on how I should understand SQL statements compared to programming? I feel like I could wield it better if I understood how I was suppose to think about it...

Answer Source

They are approaching the world from different points of view. C is about performing actions. SQL is about storing data, and manipulating data. The only "actions" it is good at are pulling and changing data.

Think of all your data like a Venn diagram- SQL lets you "look" at any part of that diagram you want.

If you want to actually do something to that data, then in C, you might say "Go to every user and perform this action on them", as in

//if a customer is late, send them a reminder
for(int i=0;i<USER_COUNT-1;++i){
  }  //if cust is late on their payments
}  //for ea customer

In SQL, you would be able to ASK for the list of users, as in:


Or you could change data regarding those customers, as in:

SET TRUST_LEVEL = TRUST_LEVEL - 1  --trust a little less when they are late

Note that this UPDATE could affect any number of rows, but there is no loop... you are simply saying "look up these records, and change them in this way".

But if you wanted to send them a reminder, well that's just too bad... you've got to use C or a stored procedure to do that.

You really get the best of both worlds when you combine a traditional language with SQL. If you can replace the earlier example in C with this (disclaimer: I know this is bogus code, it's just an example):

//if a customer is late, send them a reminder

//get all the late customers
dataSet = GetDataSet(sqlCommand);

//now loop through the late customers i just retrieved    
for(int i=0;i<dataSet.RecordCount - 1;++i){
}  //for ea customer

Now the code is more readable, and everyone is pointed at the same data source at runtime. You also avoid the potentially messy code in C that would have been involved in building your list of customers - now it is just a dataset.

Just as SQL sucks at doing imperative actions, C sucks at manipulating data sets. Used together, they can easily get data, manipulate it, and perform actions on it.