Session 4: Understanding Keys, Altering Tables, Inserting Values for the Altered Table in SQL

Session 4: Understanding Keys, Altering Tables, Inserting Values for the Altered Table in SQL

This is Session 4: Altering Tables, Inserting Values for the Altered Table in SQL.

 If you haven’t viewed the previous article, I would highly recommend reading the following articles before you delve into this one to get the core steps down and this article builds upon the previous articles.

https://baknowledgeshare.com/sql-part-1-learning-the-basics-of-sql/

Session 2: Preparing to code in SQL
https://baknowledgeshare.com/session-3-inserting-and-viewing-values-in-sql/

I the previous article I went over Inserting and Viewing Values in SQL. In this session I will go through setting up primary keys and setting up ID’s.

Using the same data base from the previous article we created the following table with values.

class_name

 

 

 

price

SQL Part 1

 

 

 

800

SQL Part 2

 

 

 

1200

SQL Part 3

 

 

 

200

SQL Part 4

 

 

 

350

SQL Part 5

 

 

 

150

Before we create keys and delve into the wonderful world of keys. Let’s understand what they are.

What are Keys?

A key in a database management system, is an attribute or a set of attributes that help to uniquely identify a row on a table. Keys are also used to establish relationships between the different tables and columns of a relational database. Individual values in a key are called key values.

Why are the Keys Needed?

A Key enables records or rows on a database to be identified uniquely. It solves for the duplicate records.

As an example in the database that we created above, what attribute do you think will uniquely identify each class? You could refer to the class by the class name but in this case we could add an ID to the class name to make each class unique.

Let’s insert another column call class_id using the following sql statement.

 

ALTER TABLE table_name ADD column_name data_type constraints;

 

ALTER TABLE training 
ADD class_id VARCHAR(20); 

 For the next step, we will insert values in the new column we use the following syntax:

INSERT INTO training(class_id) VALUES('001'); 

 When you run the following statement you will see the following output:

 Select * training;

 This is what you will see a new column class_id with default values of NULL’s

 The question is how do you insert values for each class_id that correspond to a training class and the price.

UPDATE training

SET class_id=‘002’

WHERE price=‘800’;

Now write some SQL query to insert a class_id for the rest of the price point

In the next session we will go over creating another table and inserting values in the new table.

How is your journey going along so far.

 Here are a couple of resources you can use to learn SQL:

SQL for Data Analysis Do comment below in the comments section to let me know how it’s going.