CRUD Commands
CRUD is an acronym for the different types of interactions you have with a database:
Create
Read
Update
Delete
You've already seen create and a bit of read:
This section will focus on reading via SELECT
, updating via UPDATE
, and deleting via DELETE
.
SELECT (Read)
Here's the basic syntax for selecting all data with restrictions on what columns you want back:
Adding conditions using WHERE
When reading a database, you're almost never reading every row. You usually are trying to pull out particular pieces. That's where the WHERE
clause comes in.
Here's the basic syntax for WHERE
:
Note: The WHERE
clause is useful for UPDATE
and DELETE
too, not just SELECT
. (You usually want to update or delete specific things, not your entire database/table.)
Aliases
When displaying a table's columns, I can specify an alias that changes how it appears (without changing the database).
Syntax:
Pro tip: Aliases are useful when you create JOIN
tables. For example, if you have a dogs
table and cats
table, they may both have the column name
. During your JOIN
, you can create aliases to make it clear which is which, i.e., dog_name
and cat_name
.
UPDATE
Sometimes you need to UPDATE
values in a database. For example, maybe a user forgot their password and wants to change it. Here's the syntax for that:
Pro tip: Run the SELECT
equivalent of your UPDATE
command first. Once your SELECT
command returns the data you expect, then update it. Example:
DELETE
The basic syntax for the DELETE
command is this:
Running SQL Files
Bonus!
You can run a series of SQL commands by running source filename.sql
inside of mysql-ctl cli
(provided you're in the same directory as filename.sql
).
This is a quick way of executing a bunch of commands at once after having written it in a nice text editor.
Last updated