You are on page 1of 26

SQL Basics, Part 1

Name:___________________

First, you’ll need access to a database with a command line interface. You can use a Linux
installation, a VirtualBox or VMWare installation with Linux, or the mariadb download from
https://www.mariadbtutorial.com/getting-started/install-mariadb/ . I personally find Linux to be
easier to use because the Windows tool has a GUI that is not intuitive and requires more steps for
each command. For the sake of simplicity, I ask everyone to use either a Linux platform or a
virtual machine.

MariaDB “should” be preinstalled on Kali and Ubuntu linux. That means you already have it
and can skip this step! Check if you have it by attempting to start the service. If you do not have
MariaDB, try these instructions to install it.
For UBUNTU Linux
https://linuxize.com/post/how-to-install-mariadb-on-ubuntu-18-04/
For KALI Linux
https://computingforgeeks.com/how-to-install-mariadb-on-kali-linux/

Assuming that you now have mariadb installed, let’s continue.


Start the service with
# service mysql start (if you are root)
or $ sudo service mysql start (if you are not root)
2. Issue the login command.

If this is your first time using mariadb, issue the command:


mysql -u root -p
You will be prompted for a password. Give a password, or leave blank for no password.

In my root example, I have no password.


As root, you can issue the command:
mysql -u root

Or, as a user, use ‘sudo’


If you used a password, then start mariadb with mysql -u root -p then give the password.

Now you are ready to begin!

Please confirm each step in the assignment below with a SCREEN CAPTURE where indicated.
That means your screen capture MUST show the command you used, and a sample of the results.
You should be able to prove each result with one screenshot per task but if you make mistakes
then you can add a few more screens.
ASSIGNMENT

Part 1: Show, Create, Drop

In this section we are going to look at what is available, create a junk database, then get rid of it.
If you don’t know the commands, do a simple google search or look through the class notes for
this week. Consider this an exercise in research since the commands are short and simple.

Task 1: Issue the command to ‘show databases’.


What happens if you just type ‘show databases’ ? Remember, you need to add a character
to the end before something happens. If you are getting an error or extra blank prompts
then you missed something.

Show your successful command with a screen capture here:


Next, let’s create a quick database that won’t last very long.

Task 2: Issue the command to create a database called ‘doomed’, then prove your results
by issuing the ‘show’ command. Show your success with a screen capture here.

Next, we’ll delete the doomed database.

Task 3: Issue the command to drop database ‘doomed’.


Show your success with a screen capture.
Part 2: Tables

Remember that tables are components of a database. A database itself does not necessarily mean
a spreadsheet of rows and columns. Instead it is a structure of one or more tables which could
resemble spreadsheets, and could have related entries (“keys”) that tie information together
between tables.

Let’s look at the ‘mysql’ database. Switch to it by using the ‘use’ command.
Ex:“use mysql;”

Notice that the prompt changed to reflect the current database.

Let’s see what’s in this database.


Task 4: Show tables

Issue the command that reveals what tables are in the database. The name of this task is a
strong hint. Copy your screenshot here, and be sure it includes your command and a few
lines of output.
Task 5: Create a table
The mysql database is crowded. Let’s create a new database and switch to it.

First, create database “CS509”. Now issue the ‘use’ command to make our new database
active.

Next, let’s add a simple table.

Create a table named ‘Player’. This time, I’ll give you the command from the slide
presentation so you can just copy this to your prompt:

CREATE TABLE Player (

id SMALLINT UNSIGNED,

firstname VARCHAR(35),

lastname VARCHAR(35),

birthdate DATE NOT NULL

);
If the copy and paste worked, each line should have been on its own prompt. Because the first
line did not end with a semicolon, a new prompt appeared to allow you to add more details to the
command. This process repeated until the last line featured the ); characters. This ended the
command, and if it was valid you would have seen a ‘Query OK’ message.

Copy your screenshot here, and of course make sure the screenshot includes the command
and output.

Task 6: Modify the table

Let’s add a column to the table. Use the following command once again:

ALTER TABLE Player

ADD rating CHAR(1);

Then modify the table:

ALTER TABLE Player


MODIFY lastname VARCHAR(40);

Now let’s use the DESCRIBE command to see what we did.

Issue the command ‘describe Player;’ confirm that your modifications are in the table. Show
your results here with a screen capture.

Task 7: Clearing the table

Next let’s purge the contents of the table, but keep the bare minimum structure available.

Issue the command to truncate the Player table. Show the contents of the table to demonstrate
what you did. Copy the screen capture here.
Task 8: Delete the table

The table is empty, let’s get rid of it entirely.

Issue the command to delete the Player table. Hint: it is NOT ‘delete’. Use the command
that shows all current tables in the nation database, and copy the screen capture here.
Task 9: Constraints and Keys

Next we will test constraints. This is how we define a column to be a primary key.
Remember that keys help connect multiple tables so that operations on one table may
update another to keep both tables current.

Issue the following commands:

CREATE TABLE Team(

id SMALLINT UNSIGNED AUTO_INCREMENT,

name VARCHAR(35),

color VARCHAR(35),

PRIMARY KEY(id)

);

CREATE TABLE League(

leagueID SMALLINT UNSIGNED,

name VARCHAR(35),

FOREIGN KEY(leagueID) REFERENCES Team(id)

);

Copy your screen capture here that shows you performed the two commands above.
How does this work? When issuing a command to create or alter a table, you can specify one or
more columns. Furthermore, the same command can define one of the columns as a primary key.

Primary keys not only connect data in one table with the related foreign key in another table, but
they are also guaranteed to be unique. This unique quality can also be applied by a user
command if other columns need to be unique but are not primary keys. Such attributes are then
called ‘alternate keys’, and as long as they are unique, they can be linked to foreign keys in other
tables.

Task 10: Another constraint

Normally the word ‘constraint’ means a limitation. In the last exercise we applied the ‘primary
key’ constraint which forces uniqueness, and the ‘foreign key’ constraint which prevents
modification and is connected to a primary key. Other constraints like ‘unique’ also exist. Next,
we’ll use ‘check’ which requires a comparison and limits the scope of values that an attribute
may have.

MariaDB [nation]> alter table Team


-> ADD CHECK(color <> 'green');

Notice, if creating a new table and adding a constraint, then that constraint can go at the end like
‘PRIMARY KEY’ did in previous examples. But, if we are modifying an existing table, then we
have to use ALTER and ‘ADD CHECK condition. This pattern works for other constraints like
‘UNIQUE(attributeName)’.

You can also provide a name to the constraint rule so that you can access the rule directly instead
of updating the column.
ADD CONSTRAINT your_constraint_name
CONSTRAINT (attribute)

Notice, we only use ADD with the constraint name, we don’t add the name and add the
constraint. Also, we only have to use ADD if we are making a change to an existing table. We
would not use ‘add’ if the constraint was part of the creation of a new feature.

Apply the command above to add a check to the team color to make sure no color is green.
Copy your screen capture showing the command here.
Task 11: Named constraints

Constraints all have names. If you do not supply a name, the system will generate one for you.
Sometimes we need to name a constraint so that we can modify the constraint itself rather than
modify the attributes completely.

ALTER TABLE Team

ADD CONSTRAINT unique_color

UNIQUE(color);

Let’s reverse our decision and delete the constraint.

ALTER TABLE Team


DROP CONSTRAINT unique_color;

Apply your commands to add and drop the constraint, and copy your screen capture here
that shows both commands and the results.

One more tip: If you set constraints but did not name the constraints, you can use a command
like ‘SHOW CREATE TABLE tableName’, and the system-generated names of the constraints
will appear.

Part 3

In this last segment we’ll add, update, and delete data from tables.

Task 12: Insert Data


First, let’s recreate the Player table:

CREATE TABLE Player (

id SMALLINT UNSIGNED,

firstname VARCHAR(35),

lastname VARCHAR(35),

birthdate DATE NOT NULL,

rating CHAR(1)

);

You can review the table with ‘describe Player;

Next, issue the following command:

INSERT INTO Player Values(1,'Julie', 'Zion', '2000-08-08', 'B');

Show that the table contains the data by issuing the following command:

select * from Player;

Take a screen capture of the command and output and copy the image here:
Task 13: Delete rows

To delete one entry, use:

delete from table where column = value;

The condition can be made more complex to target multiple rows with accuracy. We could use
other operators like ‘not equals’ !=, less than <, greater than or equal >=, and so on. Not equals
can also be <>.

Determine what command will delete the row containing Julie from the table. Take a
screen capture of the command and its results, and show it here.
Task 14: Insert multiple rows.

Let’s add 3 teams to the team table:

INSERT INTO Team VALUES

(1, 'Rockets','Red/White'),

(2, 'Comets','Blue/White'),

(3, 'Tar Heels','Orange/Green');

Use the select command to display the whole table and copy a screen capture here that
shows the command and the output.se
Task 15: Update
First let’s add a new column to the Player table.

alter table Player add salary int default 1000;

Now add a few players to the roster. Notice that we are overwriting the default value in the last
entry, or leaving it blank so that the default value is used instead.

INSERT INTO Player Values(1,'Jay', 'Zion', '2000-08-08', 'B', DEFAULT);

INSERT INTO Player Values(2,'Ahmed', 'Argle', '1999-07-05', 'C', 900);

INSERT INTO Player Values(3,'Prithi', 'Bargle', '1998-03-10', 'A', 1300);

INSERT INTO Player Values(4,'Sandeev', 'Choppeser', '2001-10-05', 'B',


DEFAULT);

Use the select command to confirm your table.

Can also use another format for using default values:


Update

INSERT INTO Player (id, firstname, lastname, birthdate, rating) values (5,
'Kate', 'Dingo', '2002-9-05', 'B');

Notice in the above format, we can exclude the default value entirely.

However, if you try to cross the two formats by using ‘insert into player values’ and then leave
the default field blank, you will get an error that the column count doesn’t match.
Next, let’s give all players a 5% increase in salary.

UPDATE Player
SET salary = salary * 1.05;

Display the contents of the table using the select command, and take a screen capture of the
previous command and its output, and copy the image here.

Now let’s give “A” rated players an additional 3% boost by only selecting rows where the rating
is ‘A’.

UPDATE Player
SET salary = salary * 1.03

WHERE rating = 'A';

Take another screen capture that shows the updated table output.

Task 16: Delete everything

To clear all rows, simply do the following:


delete from table_name;

Or, you can truncate table_name and get the same result.
Last screenshot: show the delete command and then display the contents of the empty
table. Copy the screen capture here.
ASSIGNMENT

In this assignment we will work with a sample file and perform more SQL commands.

You will need the sample file from:

www.mariadbtutorial.com/getting-started/mariadb-sample-database/

For Windows, extract the sample file to the mariadb directory. The location is below.

For Linux, extract the sample file anywhere you have access whenever you are ready. The home
directory ~/ is easiest.

The link to the Windows installation utility is here:


To start we’ll add the ‘nations’ database that we downloaded during our setup.

at the prompt issue the command ‘source <location of the nations.sql file>’

Linux:

For Windows, use source and the path that you extracted the zip file to.
Example:
[nation] > source C:\mariadb\nation.sql

(now we use nation)


select
from, where, group by, having, order by
show columns from
alias
distinct

The next assignment should cover chapter 5

You might also like