1. Home
  2. Explore
  3. Computer Science
  4. SQL and Database Fundamentals

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

SQL and Database Fundamentals

Transcript

You know, every time you log in to Netflix or  check your bank balance online, maybe swipe your   student ID right here at Tarleton, or even just  track a package you order, you're not just like   interacting with an app. You are actually having  this quiet, pretty sophisticated conversation   with a database. Have you ever thought about  that? Just take a second and picture it. This   constant kind of invisible hum of data being  looked up, updated, managed really carefully behind every single click, every interaction you  make. It's happening all the time everywhere.   The thing is our whole digital world doesn't run  on magic, right? It runs on databases and getting   the skills to design them, manage them, keep  them secure. Well, that starts right here with   understanding SQL. Welcome to the deep dive.  Today, we're taking a really essential journey   into the core ideas of BCIS-4301: Database Theory  and Practice. Our mission uh for this deep dive

is basically to demystify SQL for you. We want  to take you from the basic theory to its really   powerful real world uses. So, we're going to dig  into how we design databases, how we develop them,   and then implement them, focusing really heavily  on what's called the relational model. This covers   well, pretty much everything from entity  relationship modeling that's visualizing   the data and this critical idea of normalization  to actually writing SQL code. We'll also touch on database administration, look at some cool  emerging database tech, and really dive into how   these concepts play out in, you know, crucial real  world applications across all sorts of industries.   This deep dive is really tailor made for you.  Whether you're a student right here in Charlton   State University's Dr. Sanpac College of  Business, maybe a future business leader,   or honestly just anyone curious about the language  that basically powers our digital lives. Okay,

before we really jump into the deep end with  data, if you're finding this valuable or you know,   maybe you have a classmate who'd be interested,  please go ahead and hit that follow button,   share it with them, and definitely remember  to check out the episode description. We've   put together a bunch of extra resources just  for you. links to docs, practice exercises,   maybe even some deeper dives on specific things  we talked about. All right, let's unpack this maybe with a real world kind of feel. SQL um it  isn't just some technical skill for, you know,   hardcore programmers. It's actually like a  superpower for pulling out really important   business insights. Like think about a big retail  company. Let's call them Redcat shoes. How do they   figure out which shoes are flying off the shelves?  Which ones are just sitting there? or how do they   know who their best customers are, the ones  spending the most money, or even predict, say,

which months are going to be huge for sales for  their new sneaker line? It's all thanks to SQL.   It's the language that lets them ask these  big questions and instantly turn these huge   mountains of raw sales data into like actual  intelligence they can use. Without it, they'd   just be guessing. Right. Exactly. And what's  really fundamental, you know, is that almost   every application you use daily, from giants  like Amazon to your bank's super secure system, relies heavily on SQL. It's not just a language  for talking to relational databases. It really is   the universal standard. And this isn't just about  like simple day-to-day stuff like processing one   sale at the counter. It's also absolutely critical  for big picture strategic decisions. We're talking   identifying sales trends over years, optimizing  inventory across thousands of locations,

even spotting weird patterns that might indicate  fraud. SQL really is that universal translator. It   turns our kind of abstract business questions into  precise instructions the database understands and   can process incredibly fast. Okay, so how do we  even begin to ask those questions? Like where's   the starting point for pulling information out  of this, you know, potentially huge database?   It all starts with two really fundamental  keywords. Select and from. Select and from. Got it. Precisely. The select statement is where  you tell the database what data you want to see,   which specific columns or pieces of information  you're after. And then the from clause tells   it where to get that data, which specific table  holds the information you need. So for instance,   if you just wanted to grab absolutely everything  from a really simple sales table, you might write   something like select from simplified sales. That  little asterisk is basically shorthand for give

me all the columns. Mhm. But and this is a really  crucial best practice especially as you get into   real world systems, try to avoid using select in  production cutting or when you're dealing with   really big tables as that seems convenient. It  is convenient for quick peaks definitely but the   problem is it forces the database to fetch every  single column for every single row even if you   only needed say the product name and price.  This massively increases what we call the IO load. Basically how much reading and writing the  database has to do and it eats up way more memory   than needed. Right. On a system with millions of  records, this can slow your queries down from like   milliseconds to potentially minutes. It really  impacts performance. Ah, okay. Like asking the   library to read out every word in every book just  to find one author's name. Exactly that. A much

better way, much more efficient is to explicitly  list only the columns you actually need. So for   Redcat shoes, if they just wanted product names  and prices, they'd write select product name price   from simplified sales. It's cleaner, faster, and  easier for others to understand. That makes total   sense. But okay, we rarely want all the data,  even all the columns. What if Redcat Shoes only   wants to see sales for sneakers? Not boots, not  sandals, just sneakers. That's still filtering, right? That's precisely where the wear clause  becomes your best friend. It acts as your filter.   It lets you specify conditions and only the rows  that meet those conditions, where the condition   is true, get returned. So, wear category  sneakers gets you just the sneaker records.   Think of it like um making your hay stack as  small as possible before you start looking for the   needle. This lets the database work much smarter,  scanning only the data it absolutely needs to,

which speeds things up a lot. And SQL gives you  a whole toolkit of comparison operators for your   wear clause. You've got for exact matches like  color, black then, or sometimes the last means   not equal to. You have adu for less than, greater  than, and so on. These work for numbers, dates,   even alphabetically for text. So you could do  like wear price 100. Exactly. Get all products   over a hundred bucks. And for text besides  exact matches, we have the like operator which is super powerful for finding patterns. If Redcat  wanted products starting with men's, they could   use where product name like men percent. That  percent sign percent is a wild card. It matches   any sequence of characters or even no characters.  Oh, cool. And for dates, simple comparisons work,   too. like where sale date equals 2025101 to find  sales from the start of 2025 onwards. The key is

just being precise in your conditions. Okay, so  we can get all sneakers, but what if Redcat wants   to narrow it down even more? Say they only want  black sneakers. Now we're combining conditions.   It sounds like it could get tricky, right?  And this is where ANG andd and ore come in.   They're your main tools, your logical operators  for building these more complex filters. And D   means all the conditions you list must be true  for a row to be included. So for black sneakers, you'd write wear category sneakers and color  black both have to be true. Okay, straightforward   enough. Or on the other hand means any one of the  conditions can be true. So wear category sneakers   or manufacturer name Puma would give you all the  sneakers regardless of brand plus any product   made by Puma even if it's not a sneaker. It kind  of expands your results. Now here's a critical   detail, something that definitely catches  people out, even experienced folks. When

you mix andd and or in the same wear clause, you  really need to use parenthesis. Oh, why is that?   Like order of operations in math. Exactly like  that. And D has higher precedence, meaning SQL   processes all the A andds before it looks at the  OS unless you tell it otherwise with parenthesis.   So imagine you wrote where category sneakers  or category boots and manufacturer name Nike.   You might think you're asking for Nike sneakers  or Nike boots, but because Andy comes first, the database sees it as give me all sneakers from  anyone or give me only Nike boots. The Andy part,   category of boots and manufacturer name, Nike  gets evaluated first. Oh, okay. I see. That's   definitely not what I intended in that case,  right? If you wanted sneakers or boots, but only   if they're made by Nike, you must use parenthesis  to group the O. Wear category sneakers or category   boots and manufacturer name Nike. Always use  parenthesis when mixing A andd and or R. It makes

your logic crystal clear, prevents unexpected  results, and makes your code way easier for anyone   else or you six months later to understand. And  just quickly, there's also the not operator, which   just reverses a condition, like wear not color all  black. Again, use parenthesis if you mix it with   Andy or or R. That parenthesis tip is gold. Devil  like math class flashbacks. Okay, so sometimes we don't want every single row even if it matches our  filters. Like if Redcat just wants a list of the   unique manufacturers they carry sneakers from,  not every single sneaker sale. Perfect use case   for distinct. It does exactly what it sounds like.  It eliminates duplicate rows from your results,   giving you only the unique values. So for that  list of unique manufacturers who sold sneakers,   you'd write select distinct manufacturer name  from simplified saleswear category sneakers.

Even if Nike sold 500 pairs of sneakers, Nike  would only appear once in that list. One important   thing, distinct applies to the entire combination  of columns you select. If you did select distinct   manufacturer name color, you'd get unique  pairs. So Nike black and Nike white would both   show up as distinct combinations. Got it. Unique  combinations. Okay. And once we have the data we   want, especially if it's for a report or something  we need to analyze, just getting a jumbled list isn't always helpful. How do we make it easy to  read? That's where order by Y comes into play. It   sorts your results based on one or more columns  you specify. It makes the output much easier to   understand. By default, it sorts in ascending  order, A to Z for text, smallest to largest for   numbers, earliest to latest for dates. You can  explicitly say ASC for ascending, though it's   usually the default anyway. Or you can specify  DSSE for descending order Z to A, largest to

smallest, latest to earliest. Can you sort by more  than one thing, like by category, then by price?   Absolutely. And that's really powerful for Redcat  shoes. Say they wanted to see their most expensive   sneakers within each color group. They could use  order by color ASC price DESC. This would first   group all the black sneakers together, sort those  from highest price to lowest, then move to blue sneakers, sort those highest to lowest, and so on.  Order by Y doesn't change what data you get back,   only the sequence it's presented in. Really useful  for quick insights. Okay, sorting is great for   organizing, but what if Redcat wants to know more  than just individual sales? like what's the total   money they made from sneakers versus boots or how  many different products does each brand supply

them with? We're kind of summarizing now, right?  Exactly. Now, we're stepping into the real power   of SQL for analysis. This is where group BY and  what we call aggregate functions become absolutely   essential. Group BBY lets you take your rows,  divide them into groups based on the values   in one or more columns, and then you can run  calculations on each of those groups separately.   Some common aggregate functions you'll use all the  time are count and e which counts the number of rows in each group. SUM adds up all the values in  a numeric column for the group. ADG calculates the   average. Min finds the minimum value and max finds  the maximum. Okay, so how would Redcat find the   total revenue per category? Good example. They'd  write something like select category C price   quantity as total revenue from simplified sales  group by category. See the group by category part

first gathers all the sneaker sales together, all  the boots sales together and so on. Then EC price   quantity calculates the total revenue for each of  those category groups. The as total revenue just   gives that calculated sum a nice readable name in  the output. Wow. Okay, that's incredibly useful   for getting that highle view. But what if they  only care about the really big categories? Say they only want to see categories that brought in  more than a million dollars. We're filtering after   the summing, right? Excellent question. That's  exactly what the having clause is designed for.   Think of having as a wear clause, but specifically  for filtering groups after they've been created   and aggregated by group by. You can't use where  to filter on the result of sum or count. Because

where filters individual rows before the group buy  even happens. Ah, okay. Order of operations again.   Precisely. So to get only those categories with  over a million in revenue, you'd add having to our   previous query. Select category sum price quantity  as total revenue from simplified sales group by   category having price quantity 100,000. This gives  Redcat just their top performing categories based on that revenue threshold. Understanding group  by Y and having is really fundamental for any   kind of business intelligence or reporting you  do with SQL. Okay. So, that simple sales table   we use for examples was well, yeah, simplified.  It worked well to show the basics, but you're   saying real world databases aren't usually like  that. They're more complex. Oh, definitely. That   single table was useful for illustration, but  in reality, storing everything, customer name,

address, product details, manufacturer info,  sale info, all in one giant table is a really   bad idea. Why is that? Seems like it would keep  everything in one place. It sounds convenient,   but the huge problem is redundancy. Imagine  storing a customer's full name and address   with every single purchase they ever make. If  they buy a hundred items, you've stored their   address a hundred times. Now, what happens if  they move? You'd have to find and update that address and potentially hundreds, maybe thousands  of places. Did you get them all? What if you miss   one? Now you have conflicting information.  It's a recipe for errors and inconsistencies,   not to mention incredibly inefficient storage.  Okay. Yeah, I can see how that would get messy   fast. So what's the alternative? The alternative,  and this is a core concept in database design,   is normalization. The idea is to strategically  split your data into multiple smaller related

tables. Each table focuses on one specific thing  or entity. So for Redcat shoes, instead of one   giant table, you'd likely have a customer table  with customer info, a product table with product   details, a manufacturer table, and a sale table  recording the transaction. Okay, separate tables.   But how do they relate to each other? How do you  know which customer bought which product? That's where keys come in. Each table has a primary key  PK. This is usually a single column like customer   ID or product ID that contains a unique value  for every single row in that table. It's like   a unique ID number. Then to link tables, we use  foreign keys FK. A foreign key in one table is a   column whose value matches the primary key value  in another table. So the sale table wouldn't store

the customer's name and address. Instead, it would  just have a customer ID column, a foreign key that   contains the unique ID of the customer who made  the purchase. That ID then points back to the   full customer record in the customer table where  customer ID is the primary key. Ah, I see. So, you   only store the full customer details once in the  customer table. Exactly. Same for products. The sale table has a product ID foreign key linking  to the product table. The product table might   have a manufacturer ID foreign key linking to the  manufacturer table. It's like a library catalog.   The book is cataloged once with all its details  and a unique ID. When someone borrows it,   the loan record just notes the borrower's ID and  the book's ID, not the entire book description.   Again, it avoids redundancy and keeps things  consistent. This whole process of organizing data

to minimize repetition is normalization. Okay,  so normalization sounds smart. Splitting data   makes sense. But now, if the data I need is spread  across, say, the sale table and the product table,   how do I get all back together? like how do  we find those sneaker sales again now that the   category sneakers is in the product table not the  sale table. That is precisely what joins are for.   They are the mechanism for recombining data from  these related normalized tables. The most common type and often the default if you just write  join is the inner join. An inner join combines   rows from two tables based on a related column  between them. Almost always matching a foreign key   in one table to the primary key in the other. The  key thing about inner join is that it only returns   rows where there's a match in both tables. If you  have a product in the product table that has never   been sold, so there's no matching producted in  the sale table, that product won't show up in

the results of an inner join between sale and  product. Okay, only matching rows. So how would   that sneaker query look now with separate tables,  right? You need to connect sale and product using   their shared product ID. The query would look  something like this. Equila select sale, maybe be   more specific later. product at category product.p  price as product list price sale. This is our left   table join product on sale producted eagle  product producted. This is the join condition where product category sneakers filter on the join  table. See that on sale productive productd part.   That's the crucial join condition. It tells the  database how these tables are related. Match the   product ID from the sale table with the product  ID from the product table. The result is like a   temporary merge table containing columns from  both but only for sales that involve sneakers.

And again, that select sale is okay for exploring,  but using select with joins can get really messy   fast. You get all columns from both tables, right?  Potentially confusing and probably inefficient,   too. Exactly. It's much better practice to list  out exactly the columns you need from each table   like select sale date. Name product.category  product.pric. It makes the query clearer,   avoids pulling unnecessary data, and prevents  potential confusion if both tables happen to have a column with the same name, like  maybe a date added column. Be specific   #2.3 chaining joins and table aliases for complex  queries. Okay, joining two tables makes sense now,   but what if Redcat wants even more info? Like they  want to see the sneaker sold, but also the name   of the manufacturer for each sneaker. And that  manufacturer name lives in yet another table,   the manufacturer table. Can we link three tables  together? Absolutely. This is where the real power

comes in. You can chain joints together. You just  follow the relationships defined by your T's. So   we know sale links to product via product  date. And let's say the product table has   a manufacturer I foreign key that links to the  manufacturer table where manufactured D is the   primary key. We just add another join to our  query. It would look something like this. A   square select SAI. Notice the S prefix Sale date  P product name and PM manufacturer name. Mm from sale as S. Assigning alias S to sale join product  PNS product D product reversed join manufacturer   as M on MP manufacturer DS second joint wear  P category sneakers. Whoa. Okay. What are the   SPNM and the AS? Great question. Those are table  aliases. They're like temporary nicknames you give   to your tables within that specific query. Using  the AS keyword, though sometimes AS is optional,   just say less often works too. Using aliases like  S for sale, P for product, M for manufacturer

makes the query much shorter, cleaner, and easier  to read. Especially when you have long table names   or like here, you're joining several tables.  Instead of writing product product name and   manufacturer mannufacturer name over and over, you  just write P product name and M manufacturer name.   It reduces clutter and makes the logic clearer.  They are invaluable for complex queries. And think   about a more complex realworld request. Maybe  someone asked for a list of all products made by manufacturers based in Texas which were sold to  customers living in California. Okay. Wow, that   sounds like it involved sale product manufacturer  and customer tables. Exactly. You'd need to chain   four joints together. Sale to customer on  customer ID, sale to product and product to B,   product to manufacturer on manufacturer. Then your  wear clause would filter on customer state EW is   and manufacturer state equals TX. SQL handles this  kind of multi-table weaving really elegantly with

these chained join on clauses. Now, while inner  join is the most common one you'll use, it's   important to know it's not the only type. SQL also  offers what are called outer joins. The main ones   you'll encounter are left join or left outer join,  right join, right outer join, and full join. Full   outer join. Outer joins. How are they different  from inner joins? The key difference is how they handle rows that don't have a match in the other  table. Remember, inner join only keeps rows that   match in both tables. A left join, however, keeps  all the rows from the left table, the one listed   first before the join keyword, and then includes  matching rows from the right table. If a row from   the left table doesn't have a match in the right  table, it still appears in the result, but the

columns from the right table will just contain NL  values for that row. Oh, okay. So, when would you   use that? Imagine Redcat Shoes wants a list of all  their products, but they also want to see the date   of the last sale for each one if it ever sold. You  could do a left join from product, the left table,   to sale, the right table. Every product would be  listed. Products that have sold would show sale dates. Products that have never sold would still  be listed, but the sale date column would just   be NLLL. Okay, that makes sense. Keep everything  from the first table. And right join is just the   opposite. Exactly. Keeps all rows from the right  table, fills in NL's for non-matching left table   columns. and full join keeps all rows from both  tables, filling in NLs on either side where there

isn't a match. It's like combining a left join and  a right join. We'll definitely dive deeper into   these outer joins later, but just knowing they  exist and handle non-matching rows differently   from inner join is important context for now.  Think of it like ven diagrams. Inner join is   just the overlapping intersection part. Left join  is the whole left circle plus the intersection.   Right join is the whole right circle plus the  intersection. Full join is everything in both circles. Good visual. Okay. You know, one really  critical warning about joins in general. Always,   always double check your onend condition, the part  that specifies how the tables relate. Onend table   A. ID equals table B. ID. If you make a mistake  here, maybe forget the on-end clause entirely or   use the wrong columns, you can accidentally create  what's called a cartisian product or a cross join.

Cartisian product sounds bad. It usually is. It  means every single row from the first table gets   combined with every single row from the second  table. If you have a thousand rows in table A and   a thousand in table B, you suddenly get a thousand  1,000 was 1 million rows in your result. If you   have millions of rows, well, you can imagine it  can instantly overwhelm your database, consume all memory and CPU, and basically crash your system.  It's almost never what you actually want. So,   be meticulous with those onm clauses. And briefly,  you might sometimes see natural join. It tries to   guess the join columns based on matching names.  It's generally less recommended because it's less   explicit and can lead to surprises if column  names change. Stick with the explicit join.n   syntax. Okay, we've spent a lot of time on  getting data out of the database, selecting,

filtering, joining, but databases aren't just  static archives, right? They're constantly   changing. New customers sign up. Redcat adds new  shoe styles. Sales happen every minute. How do we   actually put new information into the database?  Right? That's where the data manipulation   language or DML commands come in. Specifically,  insert. Insert statements are how you add new   rows, new records into a table. The basic  structure is pretty straightforward. Insert into table name column one, column two values,  value one, value two, it's strongly recommended,   really best practice to always explicitly  list the columns you're inserting data into.   Why is that? If you're providing values for all  columns anyway, well, for a few reasons. First,   it makes your code much clearer. You know exactly  which value corresponds to which column. Second,   it makes your code more resilient to changes. If  someone adds a new column to the table later, your

insert statement won't break if you've explicitly  listed the columns you are providing values for.   If you just relied on the default order and  didn't list columns, adding a new column would   break your code. So, always list the columns.  For example, adding a new customer to Redcat's   database might look like this. SQL.insert into  customer customer id first name last name state   email values 501 jane dot txjane.do@ample.com.  This creates a new row in the customer table with these specific values. Now, what about columns  we didn't list? Maybe there's a phone number   column or a date join column. Good question. What  happens to those? If those columns have a defined   default value in the table structure, they'll  get that default. If not, they'll typically   be assigned the value null. Anal is an important  concept. It doesn't mean zero or an empty string.   It means the value is unknown or not applicable  or simply missing. Understanding how NAL works

is pretty important for data integrity. If  we didn't know Jane's email, we might insert   any for the email column. You can also insert  multiple rows at once, often by selecting data   from another table. Maybe Redcat wants to archive  old sales. They could do insert into sale archive   select from sale where sale date 201401 01. This  takes all rows matching the wear clause in sale   and inserts them into sale archive. But this  brings up a crucial point about data integrity. When you insert a row, especially one with foreign  keys, the database checks things. For example,   if you try to insert a sale with a customer ID  that doesn't actually exist in the customer table,   the database will and should reject the insert.  Same if you try to insert a customer ID that's   already being used as a primary key. These rules  maintain consistency. Okay, inserting new data   makes sense, but data changes over time. What  if customer moves and changes their address? Or

maybe Redcat decides to run a sale and needs to  update the prices for a whole category of shoes.   How do we change data that's already in the  database? For modifying existing records, we use   the update statement. The general syntax is update  table name set column 1 equals new value 1, column   2 equals new value 2 where condition. You specify  the table which columns to change. Set column new value. And critically, you use the wear clause to  specify which rows should get updated. Okay, that   wear clause sounds really important again because  my understanding is and this sounds terrifying.   If you forget the wear clause on an update, it  changes every single row in the table. Is that   right? Like no, I sure you are absolutely 100%  correct. And yes, it is terrifying. It's probably   one of the easiest ways to cause catastrophic  data loss or corruption in a database. An update

without a wear clause will apply the changes to  every single row. Imagine accidentally running   update product set price 10 without a wear clause.  Suddenly, every single product Redcat sells costs   $10. Yikes. Oh man. Okay, so the mantra is  always use wear with update. Always, always,   always. And here's an even better practice.  Before you run your update statement, run a select   statement using the exact same wear condition.  So before you run update product set list price equal list price at 0.90, wear categories boots.  To give a 10% discount on boots, first run select   producted product name list price from product  wear category boots. This select query acts as   a preview. It shows you exactly which rows will be  affected by your updates. You can check the count,   check the current values, make absolutely sure  it's targeting the right records before you   make the change permanent. It's a simple safety  step that can save you from disaster. And it's

interesting, different database systems sometimes  handle updates involving multiple tables slightly   differently. Like my SQL lets you do epotate sale,  join customer on that set sale, status, shipped,   customer, lastlast order date, app number down,  wear, all in one go. But SQL server for example   might require you to update sale and customer in  separate update statements. Maybe using a from clause with the join in the upate date to identify  the row. So it's always good to know the specifics   of the database system you're working with. All  right, we can add data with insert change it   with update. But sometimes data just needs to go  away permanently. Like maybe Redcat discontinues   a specific shoe model entirely and they want  it out of the active product list. How do we   remove records? For removing entire rows, we use  the delete statement. The basic syntax is pretty

simple. Delete from table name wear condition.  Okay. And I'm guessing just like update. Yeah,   that wear clause is absolutely critical here  too. Forgetting it would delete everything.   Exactly the same danger. A delete statement  without a wear clause will delete every single   row in the table. Leaving it completely empty  but still existing as a table structure. Again,   the cardinal rule applies. Run a select with the  exact same wear condition first to preview exactly what you're about to delete. Select from product  where is discontinued true before you run delete   from product where is discontinued true. Verify  before you destroy. And once it's deleted this   way, unless you have a backup where you're inside  a transaction you can roll back, that data is   typically gone for good. For example, delete from  product where producted key a keys 30 removes just   that one specific product. Now deleting raises  an interesting point about those relationships

we talked about referential integrity and foreign  keys. What happens if you try to delete a record   that other records depend on? Like trying to  delete a manufacturer record when there are   still products in the product table linked to that  manufacturer. Precisely. How the database handles   this depends on how the foreign key constraint  was set up when the database was designed. The   options are usually one restrict the default.  The database will simply prevent the delete. It will give you an error saying you can't delete  the parent record because child records still   exist. This is the safest option. two, cascade. If  it's set to cascade, deleting the parent record,   the manufacturer, will automatically delete all  the child records, all products linked to that   manufacturer. This is powerful, but can be very  dangerous if you're not careful. Deleting one   thing, could wipe out huge amounts of related  data. Three, set NUL, set default. This means

when the parent is deleted, the foreign key column  in the child records, for example, manufacturer   ID in the product table will be automatically  set to NUL or to a predefined default value,   effectively breaking the link but keeping the  child record. Wow. Okay. So, you really need to   know how those relationships are configured before  you start deleting things. Absolutely. You need to   understand the schema and the consequences.  Because of this complexity and the desire to keep historical data, sometimes companies use  a soft delete strategy instead. Soft delete.   Yeah. Instead of actually running delete, you just  update a status column on the record. Maybe set an   isactive flag from true to false or set a deleted  date timestamp. The data is still physically there   in the table for reporting or auditing, but your  application logic just filters it out from normal

views. It's often a safer approach, especially for  critical data. So, we've talked about DML insert,   update, delete, which manipulates the data  inside tables. But there's another category   data definition language DDL which changes the  structure of the database itself. And the most   drastic DDL command related to removal is drop  table. Drop table. That sounds final. It is. Drop   table doesn't just delete the rows like delete  does. It removes the entire table structure, the columns, the indexes, everything and all the  data within it completely and permanently from the   database. It's gone. Poof. Okay. Definitely  something to use with extreme caution then.   Extreme caution is an understatement. The best  practices here are non-negotiable in any serious   environment. One, backup first. Always, always  have a reliable, recent backup before dropping   anything significant. Two, check dependencies.  Understand which other tables, views, or stored

procedures might rely on the table you're about to  drop. Use database tools to check for foreign key   relationships pointing to this table. Three, test  in non-production. Ideally, test the drop script   in a development or staging environment first  to ensure it doesn't cause unexpected problems   elsewhere. Four, use if exists. For safety in  scripts, you can write drop table if exists your   table name. This prevents the script from failing  with an error if for some reason the table was already deleted or never existed. And just like  with deleting records that have dependencies,   the order matters when dropping tables. If table  B has a foreign key that points to table A,   you must drop table B, the referencing or child  table, before you can drop table A, the referenced   or parent table. Trying to drop table A first  will usually result in an error because table B   still depends on it. Understanding your schema's  dependency graph is crucial for these kinds of

structural changes. Okay, we've covered a lot.  We know how to get data, join it, change it,   even delete it or drop tables, but just knowing  the commands isn't the whole story, right? You   mentioned writing better queries. What does that  actually mean? How do we prioritize when we're   writing SQL? That's a fantastic question because  it gets to the heart of writing professional,   maintainable code. There's a common saying in  software development, premature optimization is the root of all evil. And it applies to SQL, too.  So, I recommend a clear priority order first above   all else, correctness. Does your query actually  return the right data? Is it accurate? A query   that runs in a millisecond but gives you the wrong  answer is completely useless. maybe even harmful.   Get it right first. Okay, correctness first.  Makes sense. What's next? Second, readability.   Can someone else on your team or you looking back  at it 6 months from now easily understand what

the query is doing? Can they debug it? Can they  modify it safely? Clean, well formatted, commented   code is crucial for long-term maintenance. Only  then, as the third priority, comes optimization.   If and only if your correct and readable query is  running too slowly and it's a query that gets run   frequently or deals with very large amounts of  data, then you start investing time in making   it faster. Trying to optimize too early often  leads to overly complex code that might not even be targeting the real bottleneck. Correctness,  readability, then optimization. Readability seems   really key, especially for teamwork. What are  some quick wins for making SQL more readable? Oh,   absolutely. Readability is huge. Some simple  things make a big difference. First, use comments.   Explain the why behind complex logic, not just  the what. Why did you choose the specific filter   or join. Second, use table aliases consistently  when joining multiple tables. P product name is

much clearer than product. Pro product name when  you've got five tables joined together. Third,   prefer explicit joon on insects over the older  style of putting join conditions in the wear   clause. It clearly separates filtering logic  from joining logic. Fourth, formatting matters.   Be consistent. Put each selected column on a new  line. Put each condition in your wear clause on   a new line. Maybe indented. Use capitalization  consistently like keyword select from where and uppercase. Even little things like where  you put commas add up. It just makes the   structure immediately visible. Hashtag tag tag 4.2  understanding query execution order and minimizing   search space. So beyond making it readable when  you do need to optimize, it helps to have a mental   model of how the database generally processes  a query. Now the internal query optimizer is   incredibly smart and might reorder things but the  conceptual order often looks something like this.

One from and joins happen first identifying the  initial large set of potential rows. Two where   filters those individual rows. Three group by  aggregates the filtered rows into groups. Four   having filters those aggregated groups. Five  select determines the final columns to output.   Six union if used combines results. Seven order by  sorts the final output. Okay, so there's a logical   flow even if the optimizer mixes it up sometimes.  How does knowing that help with optimization? The key principle is to eliminate unwanted data as  early in that process as possible. The fewer rows   the database has to carry through to the later  more expensive steps like grouping or sorting,   the faster the query will be. So for instance,  always try to filter rows using where before   you filter groups using having. The wear clause  runs earlier. Reducing the number of rows that   even need to be considered by group BY. Filtering  early makes a huge difference. It's like trimming

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent