JAVA Development: Databases - SQL

Download as pdf or txt
Download as pdf or txt
You are on page 1of 38

JAVA Development

Databases - SQL
Databases - What is a database?

A database is just a collection of data...


Databases - What is a database?

● technically, any of the previous examples is a database


● all of them include structured data easy to retrieve or update
● some of them might be useful for small organizations only
● advantage of database software: ability to store related data across multiple
tables -> relational databases (RDBMS)
Databases - RDBMS

Data organized into tables (or relations)


● Employee
● Shipment
● Package

Each table has columns of a certain type:


● ID: bigint
● Name: varchar(100)
● Position: varchar(10)

An entry in the table is called a row:


● 53, John, CEO, 1000000, n/a
Databases

Tables are linked together by relationships


● not the same thing as relations!

Primary key: usually the ID from one table


● Employee.EmployeeID

Foreign key: a column in another table that


references the first:
● Shipment.Manager

● One-to-one: 1 PK - 1 FK
● One-to-many: 1 PK - n FK
● Many-to-many: n PK - m FK
Databases

Constraints: conditions that the rows in the table must follow

Primary Key Constraint: a set of one or more columns that must be unique
● External: e.g CNP, email
● Surrogate key: generated ID, e.g automatically incremented number

There can be only one primary key (only one set of columns)

More Examples:
● ID: numeric: 0, 1, 2, 3, …
● ID: GUID: ebec3303-3705-4c3b-8a3a-452519c702c9
● Email: “[email protected]”, “[email protected]
● [First Name + Last Name]: [“Jim”, “Jones”], [“Some”, “User”]
Databases

Foreign Key Constraints:


● The IDs used in Foreign Key columns must exist in the referenced table as
Primary Keys

Example:
● Order.customerId –> references: Customer.id
● Song.albumId –> references: Album.id
● Song.artistId –> references: Artist.id
Databases

Other types of constraints:

● NOT NULL constraint: ensures that a value in a column cannot be null


○ Account.email

● UNIQUE constraint: values of columns must be unique


○ Account.username

● CHECK constraint:
○ ‘age’ must be greater than 21
○ length of a credit card number must be between 12 and 15 characters
Databases

SQL = Structured Query Language:


● A programming language (family) for describing database operations

Multiple flavors: Each vendor creates its own extensions:


● ISO SQL: supported by most database systems
● PL/SQL: Oracle variant
● T-SQL: Microsoft SQL Server
● ..and others, for the rest of the vendors
Databases

Types of statements:
● SELECT: fetch some data from the database
● INSERT: create one or more rows
● UPDATE: update the values in one or more existing rows
● DELETE: delete some rows
● others: creating/updated tables, creating/updating permissions, etc.
Databases - selecting data

SELECT statement: fetching data from the database:

SELECT column1, column2, ... FROM table_name <WHERE cond1 AND/OR cond2>;

SELECT * FROM tableName;


SELECT id, firstName, lastName FROM users AS u
WHERE u.email LIKE '%@yahoo.com'
SELECT reviews.text, reviews.stars, users.name
FROM reviews
JOIN users ON reviews.userId = users.id
WHERE reviews.movieId = 54362;

More info:
● https://technet.microsoft.com/en-us/library/bb264565(v=sql.90).aspx
● https://en.wikipedia.org/wiki/Select_(SQL)
Databases - selecting data

Many more things possible with select:


● selecting expressions: SELECT firstName + ' ' + lastName
● inner queries
● right joins, left joins, cross joins
● aggregations:
○ GROUP BY / HAVING
○ COUNT
○ AVG
○ MAX
● limiting the number of results
● etc.
Databases - adding data

INSERT: creating new rows:

INSERT INTO table_name (column1, column2,...) VALUES (value1, value2, ...);

INSERT INTO phone_book (name, number)


VALUES ('John Doe', '555-1212');

INSERT INTO users


VALUES ('johnny5442', 'John', 'James', '65')
^- the number of values must exactly match the table columns!

More info:
● https://en.wikipedia.org/wiki/Insert_(SQL)
Databases - updating data

UPDATE: changing the values of existing rows:

UPDATE table_name SET column1=value1 <,… > WHERE condition(s);

UPDATE users
SET emailProvider = 'GMAIL'
WHERE email LIKE '%gmail.com'

UPDATE song_plays
SET played = played+1, lastPlayed = '2018-02-05'
WHERE song_id = 17583 AND user_id = 48971

More info:
● https://en.wikipedia.org/wiki/Insert_(SQL)
Databases - deleting data

DELETE: deletes rows following a criteria:

DELETE FROM table_name WHERE condition;

DELETE FROM users


WHERE email = '[email protected]'
DELETE FROM users
WHERE email LIKE '%gmail.com'
Databases - deleting data

DELETE: deletes rows following a criteria:

DELETE FROM table_name WHERE condition;

DELETE FROM users


WHERE email = '[email protected]'
DELETE FROM users
WHERE email LIKE '%gmail.com'

Note: Be careful when deleting records in a table!


Notice the WHERE clause - it specifies which record(s) should be deleted.
If you OMIT the WHERE clause, ALL records in the table will be deleted!
Databases - creating tables

To define a table in the database you can use:

CREATE TABLE table_name (column1 datatype, column2 datatype, ...);

● SQL statements: https://en.wikipedia.org/wiki/Data_definition_language


CREATE TABLE employees (
id INTEGER PRIMARY KEY,
first_name VARCHAR(50) not null,
last_name VARCHAR(75) not null );

● Visual Tools:
○ http://squirrel-sql.sourceforge.net/ , https://sqldbm.com/
○ many IDEs have one built in(IDEA Enterprise, Visual Studio)
Databases - primary keys

A primary key is a special relational database table column (or combination of


columns) designated to uniquely identify all table records.
A primary key’s main features are:

● It must contain a unique value for each row of data.


● It cannot contain null values.
● most tables use an ID as a primary key: customer ID, product ID, invoice ID
● if we have several customers with the same name, how can we identify the
record we need?
Databases - creating primary keys

Method 1:
CREATE TABLE table_name
(
column1 datatype null/not null,
column2 datatype null/not null, ...
CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ... column_n)
);
Databases - creating primary keys

Method 1:
CREATE TABLE table_name
(
column1 datatype null/not null,
column2 datatype null/not null, ...
CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ... column_n)
);

Example:
CREATE TABLE supplier
(
supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id, supplier_name)
);
Databases - creating primary keys

Method 2:
ALTER TABLE table_name
ADD CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ... column_n);
Databases - creating primary keys

Method 2:
ALTER TABLE table_name
ADD CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ... column_n);

ALTER TABLE supplier


ADD CONSTRAINT supplier_pk PRIMARY KEY (supplier_id);

In this example, we've created a primary key on the existing supplier table called supplier_pk.
It consists of the field called supplier_id.
Databases - creating primary keys

Method 2:
ALTER TABLE table_name
ADD CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ... column_n);

ALTER TABLE supplier


ADD CONSTRAINT supplier_pk PRIMARY KEY (supplier_id);

In this example, we've created a primary key on the existing supplier table called supplier_pk.
It consists of the field called supplier_id.

We could also create a primary key with more than one field as in the example below:

ALTER TABLE supplier


ADD CONSTRAINT supplier_pk PRIMARY KEY (supplier_id, supplier_name);
Databases - foreign keys

● besides primary keys, we can have foreign keys as well


● foreign key is used to define a relation between two tables: it references an
existing record in another table
Databases - foreign keys

● A foreign key is a way to enforce referential integrity within your database. A


foreign key means that values in one table must also appear in another table.
● The referenced table is called the parent table while the table with the foreign
key is called the child table. The foreign key in the child table will generally
reference a primary key in the parent table.

As with primary keys, there are two ways of creating foreign keys:
Databases - foreign keys

● A foreign key is a way to enforce referential integrity within your database. A


foreign key means that values in one table must also appear in another table.
● The referenced table is called the parent table while the table with the foreign
key is called the child table. The foreign key in the child table will generally
reference a primary key in the parent table.

As with primary keys, there are two ways of creating foreign keys:
● when executing a CREATE TABLE statement
Databases - foreign keys

● A foreign key is a way to enforce referential integrity within your database. A


foreign key means that values in one table must also appear in another table.
● The referenced table is called the parent table while the table with the foreign
key is called the child table. The foreign key in the child table will generally
reference a primary key in the parent table.

As with primary keys, there are two ways of creating foreign keys:
● when executing a CREATE TABLE statement
● with an ALTER TABLE statement
Databases - create foreign keys

CREATE TABLE table_name


(
column1 datatype null/not null, column2 datatype null/not null, ...
CONSTRAINT fk_name
FOREIGN KEY (column1, column2, ... column_n)
REFERENCES parent_table (column1, column2, ... column_n)
);
Databases - create foreign keys

CREATE TABLE table_name


(
column1 datatype null/not null, column2 datatype null/not null, ...
CONSTRAINT fk_name
FOREIGN KEY (column1, column2, ... column_n)
REFERENCES parent_table (column1, column2, ... column_n)
);
Example:
CREATE TABLE products
( product_id numeric(10) not null,
supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
CONSTRAINT fk_supplier_comp
FOREIGN KEY (supplier_id, supplier_name)
REFERENCES supplier(supplier_id, supplier_name)
);
Databases - create foreign keys

ALTER TABLE table_name


ADD CONSTRAINT constraint_name
FOREIGN KEY (column1, column2, ... column_n)
REFERENCES parent_table (column1, column2, ... column_n);
Databases - create foreign keys

ALTER TABLE table_name


ADD CONSTRAINT constraint_name
FOREIGN KEY (column1, column2, ... column_n)
REFERENCES parent_table (column1, column2, ... column_n);

Example:

ALTER TABLE products


ADD CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id, supplier_name)
REFERENCES supplier(supplier_id, supplier_name);
Databases - SQL Joins

● we use JOINS to combine rows from two or more tables, based on related
columns
○ INNER JOIN: Returns records that have matching values in both tables
○ LEFT JOIN: Return all records from the left table, and the matched records
from the right table (null is returned from the right side if there is no match)
○ RIGHT JOIN: Return all records from the right table, and the matched
records from the left table (null is returned from the left side if there is no
math)
○ FULL JOIN: Return all records when there is a match in either left or right
table
Databases - SQL Joins
Databases - SQL Joins

Example:

This query will return all customers that have orders:

SELECT orders.ORDER_ID, orders.TOTAL, customers.ID FROM orders


INNER JOIN customers ON orders.CUSTOMER_ID=customers.ID
Databases - Deleting… stuff

We saw how can we delete records from the database but what about other
entities?

● delete constraints (foreign keys, indexes)


○ ALTER TABLE "table_name" DROP [CONSTRAINT|INDEX] "CONSTRAINT_NAME";

● delete a table
○ DROP TABLE table_name; - yes, it’s that simple…
Databases - Deleting… stuff

We saw how can we delete records from the database but what about other
entities?

● delete constraints (foreign keys, indexes)


○ ALTER TABLE "table_name" DROP [CONSTRAINT|INDEX] "CONSTRAINT_NAME";

● delete a table
○ DROP TABLE table_name; - yes, it’s that simple… to ruin everything.
Databases - Deleting… stuff

We saw how can we delete records from the database but what about other
entities?

● delete constraints (foreign keys, indexes)


○ ALTER TABLE "table_name" DROP [CONSTRAINT|INDEX] "CONSTRAINT_NAME";

● delete a table
○ DROP TABLE table_name; - yes, it’s that simple… to ruin everything.

Note: Be careful before dropping a table.


Deleting a table will result in loss of ALL information stored in the table!
Questions?

You might also like