0% found this document useful (0 votes)
23 views

Lecture 2 Examples

Uploaded by

maeveschoudel21
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Lecture 2 Examples

Uploaded by

maeveschoudel21
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

IE 3425 Eng’g.

Database
Lecture 2 SQL
Topics: Introduction to SQL, SQLite, Creating a
DB in SQLite, Table Schema, Data Insertion,
select statement, Filters, Aggregate Functions,
Action Queries

© Professor Zeid, Northeastern University


Structured Query Language (SQL)

 The primary way to work with a relational database is to use Structured Query
Language, SQL (pronounced “sequel,” or simply stated as S-Q-L)
 SQL is a language to operate databases; it includes database creation,
deletion, fetching rows, modifying rows, etc. SQL is an ANSI (American
National Standards Institute) standard language, but there are many different
versions of the SQL language.
 Almost all applications that work with databases (such as database
management systems) make use of SQL to analyze and manipulate relational
data
 From a simple request for data to a complex update operation, SQL is a
mainstay of programmers and database administrators.

2
A Brief History of SQL

 1970 − Dr. Edgar F. "Ted" Codd of IBM is known as the father of


relational databases. He described a relational model for
databases.
 1974 − Structured Query Language appeared.
 1978 − IBM worked to develop Codd's ideas and released a
product named System/R.
 1986 − IBM developed the first prototype of relational database
and standardized by ANSI.
 2000’s – Current SQL Standards supported by most database
vendors
Why SQL?
SQL is widely popular because it offers the following advantages:
 Allows users to access data in relational database management
systems
 Allows users to describe the data.
 Allows users to define the data in a database and manipulate
that data.
 Allows to embed within other languages using SQL modules,
libraries & pre-compilers.
 Allows users to create and drop databases and tables.
 Allows users to create view, stored procedure, functions in a
database.
 Allows users to set permissions on tables, procedures and views.
What does SQL give us?

 We use SQL to write queries against a DB to retrieve information


from it
 Reiterating the above point, a database consists of data. When
queried using SQL, we retrieve information (revisit Lecture 1
notes if required)
 SQL query ≡ SQL statement
 The result of a SQL query is either a table or a scalar value
 The select statement is one of the most important statements in
SQL
See Example 1
SQL Code - Example
To give you a quick peek at what SQL looks like, here is are a couple of examples using
a sample student Table.

Example 1 student Table Attributes/Columns/Fields

Records/Rows/Tuples

select * from students; Prints all the rows from the table

select id, email


Prints the ID and email of the students from the table
from students;

Don’t worry, we will demonstrate how these queries work!


SQLite

 In this class, we will be using SQLite Database, a command-line


database program compatible with most operating systems
 It can be used to create a database, define tables, insert and
change rows, run queries and manage an SQLite database file
 Install SQLite on your system using the
“Download_and_Install_SQLite” document, that can be found in
Canvas
 Note that you need to learn the basics of navigating files via your
computer’s Command Line Interface (CLI)
 See this link
https://riptutorial.com/cmd/example/8646/navigating-in-cmd for
basics on Command Prompt (Windows) navigation
 See this link https://docs.jamf.com/education-services/jamf-100-
course/4.1/Lesson_14__Navigate_the_File_System_with_Terminal.ht
ml for basics on the Terminal (MacOS) navigation
Getting Started with SQLite
 An example of what the folder structure looks like – this is very helpful
in navigating the contents of your computer via CLI
 The contents of the SQLite program have been extracted into a folder
called “SQLite” in the “C:” drive

MacOS users can simply open the Terminal and type “sqlite3” to open the program
SQLite Via Command Line
- You may first have to navigate to C:\ by typing ”cd C:\”
- You can then type “cd SQLite” to navigate to the SQLite folder shown in the
previous slide

cd – Change Directory SQLite Folder


Creating a Database
 Unlike other database management systems, there is no create database
command in SQLite
 Simply typing “sqlite3 Your_Database_Name.db”. We create “retailapp.db”
that we will be using throughout this course

“sqlite3 retailapp.db”

.database command
prints the DB’s that
are created
Tables
 Tables are the basic structures where data is stored in the database.
 Given that in most cases, there is no way for the database vendor/software to
know ahead of time what your data storage needs are, you will need to
create tables in the database yourself.
 Many database tools allow you to create tables without writing SQL but given
that tables are the container of all the data, it is important to briefly
introduce the create table syntax in this lecture.

create table [if not exists] [schema_name].table_name (


table_column_1 data_type primary key,
This is a statement
table_column_2 data_type not null,
to create a table
table_column_3 data_type default 0,
that consists of 3
table_constraints
columns.
);

11
create table Syntax
create table [if not exists] [schema_name].table_name (
table_column_1 data_type primary key,
table_column_2 data_type not null,
table_column_3 data_type default 0,
table_constraints
);

 First, specify the name of the table that you want to create after the create table keywords.
The name of the table cannot start with sqlite_ because it is reserved for the internal use of
SQLite.
 Second, use if not exists option to create a new table if it does not exist. Attempting to
create a table that already exists without using the if not exists option will result in an error.
 Third, optionally specify the schema_name to which the new table belongs. The schema can
be the main database, temp database or any attached database.
 Fourth, specify the column list of the table. Each column has a name, data type, and the
column constraint. SQLite supports primary key, unique, not null, and check column
constraints.
 Fifth, specify the table constraints such as primary key, foreign key, unique constraints.
Table Design
 A DB table has two views
 Design (Schema) view: defines table attributes, attributes data type, PK
or CPK, FK
 Datasheet (data) view: shows table data or records
 Table design means deciding on the table schema
 The following steps are to be used to determine table schema (both
attributes and data types):
 Decide on tables needed for the DB
 Identify the attributes for each table
 Select meaningful names for tables and attributes
 Populate the DB tables with data
 Attribute data types of attributes: integer, text, numeric, real, etc.
Table Naming Convention

 Table names are all lower case


EX: employee

 Table attribute are all lower case, use first the full table name as a
prefix
Example:
employee_id employee_last_name employee_first_name

100 Zeid Abe

 Do not use plural names for table names, i.e. do not use employees as
a name, instead use ‘employee'
Creating an Employee Tables
 Now that we have “retailapp.db” created in sqlite3, let’s add a table to it

We use the “create table” statement to create an employee table.

Use “.tables” to see existing tables

The data type for employee_id is integer, and it is designated as the PK.
employee_first_name, is the employee’s first name in text and employee_last_name is the employee’s
last name in text. Both employee_first_name and employee_last_name cannot be null.

To learn more about datatypes in sqlite, visit: https://www.sqlite.org/datatype3.html


and https://www.w3resource.com/sqlite/sqlite-data-types.php
Inserting Records into Tables
always terminate sql query with a
semcolon (;)

 To Insert records into a table, use the “insert into” statement


 We specify the table in which we would like to insert data, then provide the
names of the columns, and then the values that we would like to insert into
those columns

insert into statement employee table

attributes of employee table values to be inserted

Task: Create additional tables in your DB, create a product Table with product_code,
product_description, and product_price
Opening a Upon starting the CLI, the .database command does not
show the retailapp.db that we have created
Database
 You have created the
retailapp.db, the employee table
and have inserted some records
into it.
 Suppose you want to close out of
the terminal and want to resume
your work later, you may notice
that the database that we have
created isn’t immediately
accessible.
 To access our DB, we can use the
“.open” command and provide the Upon using the .open command and specifying
file path to where the database is the file path, we can see that the DB has been loaded
stored

MacOS users, how to get file path? – see this link


https://www.maketecheasier.com/reveal-path-file-mac/
MacOS - Copy and Paste the filepath into the CLI after the .open command as shown above
Before we move on… Case Sensitivity

 Case Senstivity – by default, SQLite is Case-Insensitive.


 This means that “SelECt * fRoM EmPLOyeE;” is the same as
“SELECT * FROM EMPLOYEE;” or ”select * from EMPLOYEE”
 This can be problematic, when we are comparing strings, or
trying to find a name, etc.
 To avoid confusion, it is best to stick to a convention, i.e., all
lower-case.

Read more here:


https://stackoverflow.com/questions/7662/database-table-and-
column-naming-conventions
Another Important Point

 SQLite supports “Multi-line Command Input”.


 This means you can hit enter after writing some code, and then continue
writing the rest of the query on the next line.
 The query will not “Run” until it is appropriately ”closed”. What does this
mean?
After this point, hit
“Enter”,
It will take you to
the next
Code will only run when semicolon “closes” the query. line instead of
running the code
Exiting SQLite

 To exit sqlite, type the command “.exit”

 This will keep you in the CLI but exit from the sqlite3 program.
 You can restart the program by typing “sqlite3”
select Statement
There are two types of select statements in SQL: Unconditional select
and Conditional select statements
 Unconditional select

select column name, column name, …


from table name, table name, … ;

 Sometimes you need the dot notation to tie an attribute to a table:

select customer.customer_id, invoice.invoice_total


from customer, invoice;

Class discussion
 Why and when must you use the dot notation?
 See Example 3
Example 2: Unconditional select Statement

Ex) Using a table


select employee_first_name,
employee_last_name
from employee;
Class discussion: What is
Ex) Use wild card * the result of each select
select * statement?
from employee;

Ex) Using 2 tables


select employee _id, product_code
from employee, product;
Example 2: Results
SQL select syntax

 Conditional select
select column name, column name, …
from table name, table name, …
where clause;
 Operators used in where
 Relational: =, !=, <, >, <=, >=
 Logical: not, and, or
 Other: in, between

 Sometimes you need the dot notation to tie an attribute to a table:


select customer.customer_id, invoice.invoice_total
from customer, invoice;
where invoice_number=100;
 See Example 2
Example 3: Conditional select
Statement
Ex) Using relational operator
select product_name
from product
where product_code = 202;
Class discussion: What is
Ex) Use logical operator the result of each select
select invoice_number statement?
from invoice
where invoice_date = 10/01/2012
and invoice_total > 500;
Filters

 Filters
enable you to control the result of an SQL
statement
 Different types of filters exist in SQL
 distinct Filter: filter repetitions in query results; Example 4
 like and not like; Example 5
 order by filter; Example 6
 Class discussion
 What does each filter do?
Example 4: distinct Filter
Ex) distinct Filter:

select distinct invoice_num


from invoice;
Example 5: like and not like Filters
Ex) like Filter: Ex) not like Filter:

select employee_last_name select employee_last_name


from employee from employee
where employee_last_name where employee_last_name
like “z%” not like “z%”
“%z” “%z”
“%z%”; “%z%”;

THINK: How does moving the position of the “%”


change the results?
Example 6: order by Filter

Ex) order by Ascending Filter: Ex) order by Descending Filter:

select employee_last_name, select employee_last_name,


employee _first_name employee _first_name
from employee from employee
order by employee_last_name; order by employee_last_name
desc;
 Class discussion
 What is the default order?
Aggregate Functions

 These functions summarize (aggregate) the results of a


query instead of listing them as a table (by rows) i.e.,
the result of an aggregate query is a scalar
 Aggregate functions include avg( ), count( ), max( ),
min( ), sum( )
 Class discussion
 What is the result of an SQL query?
 See Example 6
Example 7: Aggregate Functions
 Example
select avg(invoice_total), count(*), max(invoice_total),
min(invoice_total), sum(invoice_total)
from invoice;
 Class discussion
 What is the result of this SQL query?
Action Queries

 We break SQL statements into 2 groups:


1. DML (Data Manipulation Language)
select
Does not change DB data/content
2. DDL (Data Definition Language)
Also known as Action queries
Changes table data and DB content, i.e., add/delete tables
 DDL includes insert, delete, update, create table, alter table
 Class discussion
 When should you use DML or DDL queries?
Action Queries
 Syntax
insert into table name
values (.., .., .., …); What other syntax for insert query?
delete from table name
where condition;
update table name
set condition
where condition;
create table table name (column name data type,
column name data type, …);
 Class discussion
 What happens if delete does not have a condition?
group by Filter

 A very important filter is group by: allows you to include table and scalar
query results in one query
 Class discussion
 What happens if you do not use the group by filter?
 Example 8: insert
 Example 9: delete
 Example 10: create
Example 8: Action Queries - insert
Ex) Sequential
insert into employee
values (100, “zeid”, “abe”);

Ex) Non-Sequential
insert into employee (emp_lname)
values (“smith”);

 How to specify data types (number, text, date) in insert query:


 insert into employee(100, “abe”, ”zeid”, ‘2018/01/02’, …)

 Class discussion
 What does sequential mean?
Example 9 Action Queries – delete and
update
Ex) delete

delete from employee


where emp_lname = “zeid”;

Ex) update
Class discussion:
update employee What are the results?
set emp_lname = “smith”
where emp_lname = “zeid”;
Example 10 Action Queries – create and
group by
Ex) create table

create employee
(employee_id int primary key, employee_last_name text);

ex) group by filter Class discussion:


What are the results?
select customer_number, max(invoice_total) You get the max
from invoice invoice_total for each
customer
group by (customer_number);
Additional Resources

Web-based
 https://www.geeksforgeeks.org/introduction-to-sqlite/
 https://www.javatpoint.com/sqlite-tutorial
 https://www.techonthenet.com/sqlite/index.php

You might also like