DS4001 Databases (7.
5 credits)
Lecture 2 – Basic SQL Statements 1
Yuantao Fan
[email protected]
Halmstad University
Overview
• Relational Databases
• Introduction of the DBMS tools
– MySQL
– SQLite
• Basic SQL statement
– Conventions
– Data Manipulation Language
• SELECT, INSERT, UPDATE, DELETE, MERGE
– Data Definition Language
• CREATE, ALTER, DROP, TRUNCATE, RENAME
– Query filtering with WHERE clause
• IN, BETWEEN, Comparison Operators
Relational databases
• Data stored in tabular form – columns and rows
• Columns contain item properties, e.g. Last Name, First Name, etc.
• (Can also be viewed as mathematical relations)
Student
Name Student_number Class Major
Relational databases Smith 17 1 CS
Brown 8 2 CS
• Data stored in tabular form Grade_Report
Student_number Section_identifier Grade
– Columns and rows
17 112 B
– Columns contain item properties 17 119 C
• Cross referencing 8 85 A
Course
– what grade did Smith get in Discrete Course_name Course_number Credit_hours Department
Mathematics? Intro to Computer
CS1310 4 CS
Science
• Primary keys Data Structures CS3320 4 CS
– Column attributes with underlines, Discrete
MATH2410 3 MATH
Mathematics
row value must be unique
Section
Section_identifier Course_number Semester Year Instructor
85 MATH2410 Fall 07 King
112 MATH2410 Fall 08 Chang
119 CS1310 Fall 08 Anderson
The concept of relations
• A mathematical relation is a set of fixed length typles
• Relations give a simple but powerful theoretical foundation for databses
Student_number Section_identifier Grade
{(17, 112, B),
17 112 B
17 119 C
(17, 119, C),
8 85 A (8, 85, A)
}
Table Mathematical relation
SQL Basic Statements
• DDL for creating tables
– CREATE, ALTER, DROP, TRUNCATE, RENAME
• DML for insert or modify values in tables
– SELECT, INSERT, UPDATE, DELETE, MERGE
• and query tables for data
– The use of statement “WHERE” as a filter
Views derived from the databse
Actors on the Scene
• Small personal database or operation with a limit size
– One person defines, constructs, and manipulates the database
• Database administrator (DBA)
– Authorizing access to the database, coordinating and monitoring its use
• Database Designers
– Identifying data to be stored
– Choosing appropriate structure
• End users
– Casual, naïve, sophisticated, standalone
• Workers behind the Scene
– DBMS system designers and implementers
– Tool developers
– Operators and maintenance personnel
Database System Concepts and Architecture
• Data abstraction
– Generally refers to the suppression of details of data organization and storage, and the
highlighting of the essential features for an improved understanding of data
• Data model
– A collection of concepts that can be used to describe the structure of a database - provides the
necessary means to achieve this abstraction
– Most also include a set of basic operations
• Structure of a database
– Data types, relationships, and constraints apply to the data
Schemas, Instances, and Database State
• Database schema
– description of the database
– schema diagram
– Compact blueprints of relations
• Schema construct
– Object in the schema, e.g. STUDENT,
COURSE
Let’s start practising SQL!
SQL Basic Statements
• DDL for creating tables
– CREATE, ALTER, DROP, TRUNCATE, RENAME
• DML for insert or modify values in tables
– SELECT, INSERT, UPDATE, DELETE, MERGE
• and query tables for data
– The use of statement “WHERE” as a filter
MySQL
• MySQL is a very popular open-source relational database management system
(RDBMS)
– open-source, free, ideal for both large and small projects
• MySQL workbench
– GUI
• Administration, Schema
• Query
• Action output
– Schemas
• Relational databse
• Tables, views, stored procedures, functions
CREATE Statement
• Use to create a table
• A Data Definition Language for creating entities or tables in a database, including
– Names of columns or attributes
– Data types of columns
– And other optional values if requires such as the primary key constraint
– Every table elements is either a column or a constraint
• Syntax
CREATE TABLE <table_name> (
<list of table elements>
);
Hello World in SQL
Hello World in SQL
A table with two columns of
texts, as attributes
<table_name>
Insert a row into the table
Query for content in the table
Query Result
Case convention
• SQL is case insensitive
– Except in text values, e.g. ‘TEXT’, ‘texts’
• Here are the suggestions
– Keywords of the SQL language use UPPERCASE
– The name of any attribute use lowercase
– (The name of the table should be capitalized)
• Examples
– SELECT attribute1 FROM Data WHERE attribute2 = 42;
– select attribute1 from data where attribute2 = 42;
CREATE Statement
• Syntax • Table elements (columns) consist of
– Name, e.g. word1
CREATE TABLE <table_name> (
– Type, e.g. TEXT
<list of table elements>,
); • Most common types:
– INT - integer
– REAL – float
– NUMERIC(n, m) with n digits before and m digits after the
floating point
– CHAR(n) – for fixed size strings of size n
– TEXT – for variable sized strings
– VARCHAR(n) – for variable sized strings with max size n
– TIMESTAMP – for data+time (time resolution ms)
– DATE and TIME – for dates and times of days independently
SELECT Statement
• Retrieve data from a relational database table
• After creating a table and inserting data into the table, we want to see the data
• A Data Manipulation Language (DML) statement used to read and modify data
– Input: Query
– Output: Result set / table
• Format/Syntax
– SELECT <column1, column2, ...> FROM <table_name>;
SELECT Statement
• Examples
– SELECT * FROM Products;
– SELECT * FROM Products WHERE unit_price > 1
– SELECT * FROM Products WHERE unit_price > 1 AND unit_price <= 2;
– SELECT * FROM Products WHERE unit_price > 1 AND unit_price <= 2 AND
quantity_in_stock > 50;
Specify or Restricting the result set: WHERE Clause
• Restructs the result set
• Syntax
– SELECT <column1, column2, ...> FROM <table_name> WHERE <condition>;
• Always requires a Predicate
– Operator “AND”, “OR”, “NOT”
– Evaluates to:
• True, False or Unknown
– Used in the search condition of the WHERE clause
– IN (”x”, “y”, “z”)
– BETWEEN 1000 AND 3000
– Comparison Operators
• =, >, <, >=, <=, <>
INSERT statement
• Insert one or multiple row into a table
• Syntax
– INSERT INTO <table_name> <column1,column2,column3...> VALUES
<value1,value2,value3...>;
• Example
– INSERT INTO products VALUES (11, "apple", 100, 1);
UPDATE statement
• Altering rows of a table
– After creating a table and innserting data into the table, we can alter/change/modify the data
– Can update multiple attributes
– Condition can be omitted to change all rows
– Update never removes or adds any rows
• Syntax
– UPDATE <table_name> SET <attr = expression> WHERE <condition on rows>;
• Example
– UPDATE products SET name="apple_pie", unit_price = 40 WHERE product_id = 11;
DELETE statement
• Romove one or more rows from the table:
• Syntax
– DELETE FROM <table_name> WHERE <condition on rows>;
• Examples
– DELETE FROM products;
– DELETE FROM products WHERE product_id = 11;
– DELETE FROM products WHERE unit_price > 1 AND unit_price <= 2;
ALTER statement
• Add or remove columns
• Modify the data type of columns
• Add or remove keys
• Add or remove constraints
• Syntax
ALTER TABLE <table_name>
ADD COLUMN <column_name_1> datatype
ADD COLUMN <column_name_2> datatype
…
ADD COLUMN <column_name_n> datatype
TRUNCATE statement
• Delete all rows in a table
– Using IMMEDIATE to specify the operation can not be undone
• Syntax
DROP TABLE <table_name> IMMEDIATE
DROP statement
• Delete a table from a database
• Syntax
DROP TABLE <table_name>
Cheat Sheet
Command Syntax Description Example
SELECT SELECT column1, column2, ... FROM SELECT statement is used to fetch data from SELECT city FROM placeofinterest;
table_name; a database.
WHERE SELECT column1, column2, ...FROM WHERE clause is used to extract only those SELECT * FROM placeofinterest WHERE city
table_name WHERE condition; records that fulfill a specified condition. == 'Rome' ;
INSERT INSERT INTO table_name INSERT is used to insert new rows in the INSERT INTO placeofinterest
(column1,column2,column3...) table. (name,type,city,country,airport)
VALUES(value1,value2,value3...); VALUES('Niagara
Waterfalls','Nature','Toronto','Canada','Pearso
n');
UPDATE UPDATE table_name UPDATE used to update the rows in the UPDATE placeofinterest SET name = 'Niagara
SET[[column1]=[VALUES]] WHERE table. Falls' WHERE name = "Niagara Waterfalls";
[condition];
Source: IBM Databases
Cheat Sheet
Command Syntax Description Example
CREATE TABLE CREATE TABLE table_name (col1 CREATE TABLE statement is to create the table. CREATE TABLE employee ( employee_id char(2)
datatype optional keyword, col2 Each column in the table is specified with its PRIMARY KEY, first_name varchar(30) NOT
datatype optional keyword,col3 name, data type and an optional keyword which NULL, mobile int);
datatype optional keyword,..., coln could be PRIMARY KEY, NOT NULL, etc.,
datatype optional keyword)
ALTER TABLE - ALTER TABLE table_name ADD COLUMN ALTER TABLE statement is used to add the ALTER TABLE employee ADD COLUMN
ADD COLUMN column_name_1 datatype....ADD COLUMN columns to a table. income bigint;
column_name_n datatype;
ALTER TABLE - ALTER TABLE table_name ALTER COLUMN ALTER TABLE ALTER COLUMN statement is ALTER TABLE employee ALTER COLUMN
ALTER COLUMN column_name_1 SET DATA TYPE datatype; used to modify the data type of columns. mobile SET DATA TYPE CHAR(20);
ALTER TABLE - ALTER TABLE table_name DROP COLUMN ALTER TABLE DROP COLUMN statement is ALTER TABLE employee DROP COLUMN
DROP COLUMN column_name_1 ; used to remove columns from a table. mobile ;
ALTER TABLE - ALTER TABLE table_name RENAME COLUMN ALTER TABLE RENAME COLUMN statement is ALTER TABLE employee RENAME COLUMN
RENAME current_column_name TO new_column_name; used to rename the columns in a table. first_name TO name ;
COLUMN
TRUNCATE TABLE TRUNCATE TABLE table_name IMMEDIATE; TRUNCATE TABLE statement is used to delete TRUNCATE TABLE employee IMMEDIATE ;
all of the rows in a table. The IMMEDIATE
specifies to process the statement immediately
and that it cannot be undone.
DROP TABLE DROP TABLE table_name ; Use the DROP TABLEstatement to delete a table DROP TABLE employee ;
from a database. If you delete a table that
contains data, by default the data will be deleted
alongside the table.
Source: IBM Databases
Quiz
• What does the following statement do?
UPDATE products SET unit_price = unit_price * 2 WHERE quantity_in_stock < 10;
• Given the following table named “products”
Preparation for the labs
• Installing MySQL
– MySQL community edition & workbench
– www.mysql.com
• Installing SQLite
– https://www.tutorialspoint.com/sqlite/sqlite_installation.htm
• Installing Python and Jupyter notebook
– SQLite3, Pandas, Matplotlib …
– Anaconda - https://docs.anaconda.com/anaconda/install/index.html
MySQL Installation
• Installation guide
– https://dev.mysql.com/doc/mysql-installation-excerpt/5.7/en/
• Or just go to www.mysql.com
– Downloads
– MySQL Community Downloads
• MySQL Community edition
– Download and install MySQL Community Server
• MySQL workbench
– Download and install MySQL workbench
– Delete the existing local instance 3306
– Set up a new connection
Installing SQLite
• CLI
• Guide
– https://www.tutorialspoint.com/sqlite/sqlite_installation.htm
• For different platforms
– Binaries for Windows
– Linux: most distributions should have SQLite pre-installed, if not compile and install from
source
– OsX: should have SQLite pre-installed
• Optional
– SQLite workbench
Installing Python and Jupyter notebook
• Python
– https://www.python.org/downloads/
• Juypyter notebook
– https://jupyter.org/install
• Or Anaconda
– https://docs.anaconda.com/anaconda/install/index.html
– With many popular data analysis packages