Git Product home page Git Product logo

sql-insert-select-update-code-along's Introduction

Inserting, Selecting, Updating, and Deleting Database Rows

Overview

In this lesson, we'll cover different ways to manipulate and select data from SQL database tables.

Objectives

  1. Use the INSERT INTO command to insert data (i.e. rows) into a database table
  2. Use SELECT statements to select data from a database table
  3. Use the WHERE Clause to select data from specific table rows
  4. Use comparison operators, like < or >, to select specific data
  5. Use UPDATE statements to update data within a database table
  6. Use DELETE statements to delete data from a database table

Setting Up Our Database

In this code along, we'll be creating a cats table in a pets_database.db. So, let's navigate to our terminal and get started.

First let's create our pets_database by running the following the command in the terminal:

sqlite3 pets_database.db

Now that we have a database, let's create our cats table along with id, name, age and breed columns.

CREATE TABLE cats (
	id INTEGER PRIMARY KEY,
	name TEXT,
	age INTEGER,
	breed TEXT
);

Okay, let's start storing some cats.

Code Along I: INSERT INTO

In your terminal, in the sqlite prompt, type the following:

INSERT INTO cats (name, age, breed) VALUES ('Maru', 3, 'Scottish Fold');

We use the INSERT INTO command, followed by the name of the table to which we want to add data. Then, in parentheses, we put the column names that we will be filling with data. This is followed by the VALUES keyword, which is accompanied by a parentheses enclosed list of the values that correspond to each column name.

Important: Note that we didn't specify the "id" column name or value. Since we created the cats table with an "id" column whose type is INTEGER PRIMARY KEY, we don't have to specify the id column values when we insert data. Primary Key columns are auto-incrementing. As long as you have defined an id column with a data type of INTEGER PRIMARY KEY, a newly inserted row's id column will be automatically given the correct value.

Let's add a few more cats to our table. This time we'll do this via our text editor. Create a file, 01_insert_cats_into_cats_table.sql. Use two INSERT INTO statements to insert the following cats into the table:

name age breed
"Lil' Bub" 5 "American Shorthair"
"Hannah" 1 "Tabby"

Hint: You can use double single quotes (') to escape the apostrophe in 'Lil'' Bub'.

Each INSERT INTO statement gets its own line in the .sql file in your text editor. Each line needs to end with a ;. Run the file with the following code in your terminal:

sqlite3 pets_database.db < 01_insert_cats_into_cats_table.sql

NOTE: This is a bash command, run this from your bash not sqlite console.

Now, we'll learn how to SELECT data from a table, which will help us to confirm that we inserted the above data correctly.

Selecting Data

Now that we've inserted some data into our cats table, we likely want to read that data. This is where the SELECT statement comes in. We use it to retrieve database data, or rows.

Code Along II: SELECT FROM

A basic SELECT statement works like this:

SELECT [names of columns we are going to select] FROM [table we are selecting from];

We specify the names of the columns we want to SELECT and then tell SQL the table we want to select them FROM.

We want to select all the rows in our table, and we want to return the data stored in any and all columns in those rows. To do this, we could pass the name of each column explicitly:

SELECT id, name, age, breed FROM cats;

Which should give us back:

1|Maru|3|Scottish Fold
2|Lil' Bub|5|American Shorthair
3|Hannah|1|Tabby

A faster way to get data from every column in our table is to use a special selector, known commonly as the 'wildcard', * selector. The * selector means: "Give me all the data from all the columns for all of the cats" Using the wildcard, we can SELECT all the data from all of the columns in the cats table like this:

SELECT * FROM cats;

Now let's try out some more specific SELECT statements:

Selecting by Column Names

To select just certain columns from a table, use the following:

SELECT name FROM cats;

That should return the following:

Maru
Lil' Bub
Hannah

You can even select more than one column name at a time. For example, try out:

SELECT name, age FROM cats;

Top-Tip: If you have duplicate data (for example, two cats with the same name) and you only want to select unique values, you can use the DISTINCT keyword. For example:

SELECT DISTINCT name FROM cats;

Selecting Based on Conditions: The WHERE Clause

What happens when we want to retrieve a specific table row? For example the row that belongs to Maru? Or to retrieve all the baby cats who are younger than two years old? We can use the WHERE keyword to select data based on specific conditions. Here's an example of a boilerplate SELECT statement using a WHERE clause.

SELECT * FROM [table name] WHERE [column name] = [some value];

Let's retrieve just Maru from our cats table:

sqlite> SELECT * FROM cats WHERE name = "Maru";

That statement should return the following:

1|Maru|3|Scottish Fold

We can also use comparison operators, like < or > to select specific data. Let's give it a shot. Use the following statement to select the young cats:

SELECT * FROM cats WHERE age < 2;

Advanced: The SQL statements we're learning here will eventually be used to integrate the applications you'll build with a database. For example, it's easy to imagine a web application that has many users. When a user signs into your app, you'll need to access your database and select the user that matches the credentials an individual is using to log in.

Updating Data

Let's talk about updating, or changing, data in our table rows. We do this with the UPDATE keyword.

Code Along III: UPDATE

A boilerplate UPDATE statement looks like this:

UPDATE [table name] SET [column name] = [new value] WHERE [column name] = [value];

The UPDATE statement uses a WHERE clause to grab the row you want to update. It identifies the table name you are looking in and resets the data in a particular column to a new value.

Let's update one of our cats. Turns out Maru's friend Hannah is actually Maru's friend Hana. Let's update that row to change the name to the correct spelling:

sqlite> UPDATE cats SET name = "Hana" WHERE name = "Hannah";

One last thing before we move on: deleting table rows.

Deleting Data

To delete table rows, we use the DELETE keyword.

Code Along IV: DELETE

A boilerplate DELETE statement looks like this:

DELETE FROM [table name] WHERE [column name] = [value];

Let's go ahead and delete Lil' Bub from our cats table (sorry Lil' Bub):

sqlite> DELETE FROM cats WHERE id = 2;

Notice that this time we selected the row to delete using the Primary Key column. Remember that every table row has a Primary Key column that is unique. Lil' Bub was the second row in the database and thus had an id of 2.

View Inserting, Selecting, Updating, and Deleting Database Rows on Learn.co and start learning to code for free.

sql-insert-select-update-code-along's People

Contributors

annjohn avatar asialindsay avatar dannylee8 avatar deniznida avatar drakeltheryuujin avatar eaud avatar franknowinski avatar gilmoursa avatar gj avatar ipc103 avatar lcorr8 avatar rrcobb avatar sophiedebenedetto avatar tmb41 avatar victhevenot avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sql-insert-select-update-code-along's Issues

Escaping the single quote in SQL

The code along has students enter a value with an escaped single quote: 'Lil\' Bub'. Everything in the reading shows the string being escaped with a backslash, but the actual SQL command to escape is to put two single quotes, eg 'Lil'' Bub'. Might be worth including a hint, resource, or note.

unable to create table in IDE sandbox in this and subsequent labs

A student and I worked through the lab together. He was able to build the database, but when he created the file 01_create_cats_table.sql:

CREATE TABLE cats (
	id INTEGER PRIMARY KEY,
	name TEXT,
	age INTEGER,
	breed TEXT
);

and tried to run it using:
sqlite3 pets_database.db < 01_create_cats_table.sql

It wouldn't work.

Lil\'Bub vs Lil'Bub

The name of the cat is spelled 2 different ways as mentioned above. Lil'Bub is added to the table, but Lil'Bub is to be deleted.

404 error in codealongs

The first three codealongs in this track, SQL "getting started" have had dead links to github. Maybe you updated the names recently? Anyway, I'd love to be able to follow along in the exercises!

Thanks.

@avidor Lab instructions are unclear for connecting Sqlite to pets_database

One student showed confusion when trying to access their pets_database after exiting the Sqlite console, since the lab did not specify that Sqlite needed to "connect' or be made aware of the pets_database in order to modify pets_database.

Student was able to resume working on the lab after running sqlite3 pets_database.db from BASH again.

needs edit: CODE ALONG IV: DELETE

At the very end of this reading, in the section CODE ALONG IV: DELETE,

the syntax for this line:
sqlite> DELETE * FROM cats WHERE id = 3

should be changed to
sqlite> DELETE FROM cats WHERE id = 3;

(get rid of * and add semicolon at end)

Ide not working properly

Not able to see pets_database. Getting an error when adding files to01_insert_cats_into_cats_table.sq ..There should be an explanation that Control d is a way to exit sql

I am not able to finish the lab as is.

Insert Into Error

In the Code Along, Insert Into section the line:
pets_database.db > 01_insert_cats_into_table.sql

should read:
pets_database.db < 01_insert_cats_into_table.sql

Additionally, every time this notation is shown it might be helpful to clarify this is done in terminal with a preceding sqlite3 command, and not inside the database with 'sqlite>' leading the inputs.

in progress

Refer to outline in Readme

Deadline: 9/15/2015

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.