DEV Community

Cover image for SQL Basics - Manage Your Data
Jessica Triana
Jessica Triana

Posted on

SQL Basics - Manage Your Data

It's good to brush up on different languages and technologies as you start your coding journey. There are SO many overlapping aspects to programming that can help you build better projects, maybe even a bit faster than your last.

When I built my first Rails app I knew that I was writing SQL statements to create my tables and check my schema, but I never gave SQL it's own space in my brain.

Here's a quick overview of some basic SQL commands to manipulate your database.

In this example, we're creating a small table called "Dogs".

1) Create the table called dogs with column titles: id, first_name, breed. We are making the id an integer and setting it as the Primary Key for each row in this table. We are saying that the first_name of each dog must be unique text and the breed cannot be empty.

CREATE TABLE dogs (id INTEGER PRIMARY KEY, first_name TEXT UNIQUE, breed TEXT NOT NULL);

2) Insert 3 rows into the dogs table to give us some data to work with.

INSERT INTO dogs (id, first_name, breed) VALUES (1, 'Shylah', 'Cockapoo'), (2, 'Mitsi', 'Chow'), (3, 'Shadow', 'Husky');

3) Any time you want to see the current data in the dogs table, use the "Select All" command.

SELECT * FROM dogs;

Alt Text

4) Add a column called age to the end of the dogs table that takes an integer for the value.

ALTER TABLE dogs ADD age INTEGER;
SELECT * FROM dogs;

Alt Text

5) Add a column called last_name to the end of the dogs table that takes a text value. If no text is entered, 'NOT APPLICABLE' is the default value.

ALTER TABLE dogs ADD last_name TEXT DEFAULT 'NOT APPLICABLE';
SELECT * FROM dogs;

Alt Text

6) Let's add an age value to the second dog, Mitsi.

UPDATE dogs SET age = 5 WHERE id = 2;
SELECT * FROM dogs;

Alt Text

7) Add another column called trained that will take a boolean value. SQL accepts 1 for TRUE, 0 for FALSE, and NULL for an empty value.

ALTER TABLE dogs ADD trained BIT;
SELECT * FROM dogs;

Alt Text

8) Let's say that the first dog, Shylah, was trained.

UPDATE dogs SET trained = 1 WHERE id = 1;
SELECT * FROM dogs;

Alt Text

9) Let's delete the record of the dog that doesn't have any value in the age column, which would be the dog Shadow.

DELETE FROM dogs WHERE age IS NULL;
SELECT * FROM dogs;

Alt Text

This was a quick overview of some of the most-used SQL statements. Understanding these statements helps you to understand your data, update the values and debug your programs.

To learn more, take the free 7-hour "Learn SQL" course on www.codecademy.com

Top comments (1)

Collapse
 
thisdotmedia_staff profile image
This Dot Media

Super helpful! Thanks Jessica