February 1, 2016

Mafia Games Monday (MGM) – Writing SQL 103

This is my third installment of the “Writing SQL” series. If you’re curious about the other two, you can check them out here and here.

So today is time to update some data!

Consider the following scenario:

A student (ID 54356) has just recently gotten married and changed their last name to ‘Beser’. The following are the relational tables below:

STUDENT(ID, LAST_NAME, FIRST_NAME, MIDDLE_INIT, SSN, DOB)
COURSE(ID, NAME, DESCR)
STUDENT_COURSE(SID, CID, SEMESTER_VAL)

We want to keep up with what their current last name is!

This will involve some new syntax:

UPDATE: This keyword is to signify that you want to change some data on a table.
SET: This keyword is to signify which field(s) you would like to update on said table to what value.

This would be another query. Now, this is what an update query would look like:

UPDATE table
SET field = value
WHERE 1=1;

So, taking the scenario above, we can then write the following query to perform the update:

UPDATE STUDENT
SET LAST_NAME = 'Beser'
WHERE ID = 54356;

That’s the query right there! Pretty simple, isn’t it? Wait a minute though! Why did I surround “Beser” in single quotes?

There’s a pretty simple answer: “Beser” is what is called a string type. If you want to write any string within a SQL query, you have to surround it in quotes. This guarantees that the SQL engine will understand that “Beser” is in fact a string. Why single quotes though? Well, if I used double quotes, some SQL engines may not recognize it, and instead treat it like you’re attempting to label the field and/or column. Labeling will come in a later installment.

Well wait, what if this was the scenario?

A student (ID 54356) has just dropped a course (ID 589) for the current semester (SEMESTER_VAL 22015).

Keeping history aside, you just want to delete it, as they are no longer enrolled. That would involve writing a DELETE query.

Doing this will involve some new syntax:

DELETE: This keyword is to signify that you want to delete data from a table.

The syntax would look like this:

DELETE FROM table
WHERE 1=1;

So, taking the scenario above, we can then write the following query to perform the delete:

DELETE FROM STUDENT_COURSE
WHERE SID = 54356
AND CID = 589
AND SEMESTER_VAL = 22015;

Starting to look a little more advanced now, aren’t we? But that query will accomplish the job!

Tune in on my next installment for some more advanced SQL writing!

That’s all for now, until next time…keep that tech gear ticking.

~Goliath7470