02 Core SQL 4

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

Relational

Databases
and
PostgreSQL
Charles Severance
www.pg4e.com
SQL

Structured Query Language is the


language we use to issue commands to
the database
- Create/Insert data
- Read/Select some data
- Update data
- Delete data

http://en.wikipedia.org/wiki/SQL
https://en.wikipedia.org/wiki/ANSI-SPARC_Architecture
SQL
Architecture
USING SQL
pgAdmin
(Browser / SQL

Desktop) Database
User
D.B.A. Server
psql PostgresSQL
(Command SQL

Line)
STARTING POSTGRESQL
COMMAND LINE
$ psql –U postgres
Password for user postgres: <password here>
psql (9.3.5, server 11.2)
Type "help" for help.
postgres=#

Super User Prompt


YOUR FIRST POSTGRESQL
COMMAND
postgres-# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------+----------+----------+---------+-------+-----------------------
postgres | postgres | UTF8 | C | C |
template0 | postgres | UTF8 | C | C | =c/postgres +
| | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | C | C | =c/postgres +
| | | | | postgres=CTc/postgres
(3 rows)

postgres-#
CREATING A USER AND
DATABASE
postgres=# CREATE USER dbUser WITH PASSWORD 'secret';

CREATE ROLE

postgres=# CREATE DATABASE people WITH OWNER 'dbUser';

CREATE DATABASE

postgres=# \q

https://www.postgresql.org/docs/11/sql-createuser.html
https://www.postgresql.org/docs/11/sql-createdatabase.html
CONNECTING TO A DATABASE
$ psql people
Password for user : <password here>
psql (9.3.5, server 11.2)

people=> \dt
No relations found.
people=>

Not a Super User Prompt

https://www.postgresql.org/docs/11/app-psql.html
people=> CREATE TABLE users(
people(> name VARCHAR(128),
CREATING A
TABLE
people(> email VARCHAR(128)
people(> );
CREATE TABLE
people=> \dt CREATE TABLE users(
List of relations
Schema | Name | Type | Owner name VARCHAR(128),
--------+-------+-------+------- email VARCHAR(128)
public | users | table |
(1 row) );
people=> \d+ users
Table "public.users"
Column | Type | Modifiers | Storage | Stats target | Description
--------+------------------------+-----------+----------+--------------+-------------
name | character varying(128) | | extended | |
email | character varying(128) | | extended | |
Has OIDs: no

people=>
SQL: INSERT
The INSERT statement inserts a row into a table

INSERT INTO users (name, email) VALUES ('Chuck', 'csev@umich.edu') ;


INSERT INTO users (name, email) VALUES ('Somesh', 'somesh@umich.edu') ;
INSERT INTO users (name, email) VALUES ('Caitlin', 'cait@umich.edu') ;
INSERT INTO users (name, email) VALUES ('Ted', 'ted@umich.edu') ;
INSERT ImNTO users (name, email) VALUES ('Sally', 'sally@umich.edu') ;
SQL: DELETE
Deletes a row in a table based on selection criteria

DELETE FROM users WHERE email='ted@umich.edu';


SQL: UPDATE
Allows the updating of a field with a WHERE clause

UPDATE users SET name='Charles' WHERE email='csev@umich.edu';


RETRIEVING RECORDS: SELECT
Retrieves a group of records - you can either retrieve all the records or a
subset of the records with a WHERE clause

SELECT * FROM users;

SELECT * FROM users WHERE email='csev@umich.edu';


SORTING WITH ORDER BY
You can add an ORDER BY clause to SELECT statements to get the
results sorted in ascending or descending order

SELECT * FROM users ORDER BY email;


THE LIKE CLAUSE
We can do wildcard matching in a WHERE clause using
the LIKE operator

SELECT * FROM users WHERE name LIKE '%e%';


THE LIMIT/OFFSET CLAUSES
„ We can request the first "n" rows, or the first "n" rows after skipping some rows.
„ The WHERE and ORDER BY clauses happen *before* the LIMIT / OFFSET are
applied.
„ The OFFSET starts from row 0

SELECT * FROM users ORDER BY email DESC LIMIT 2;


SELECT * FROM users ORDER BY email OFFSET 1 LIMIT 2;
COUNTING ROWS WITH SELECT
You can request to receive the count of the rows that
would be retrieved instead of the rows

SELECT COUNT(*) FROM users;


SELECT COUNT(*) FROM users WHERE email='csev@umich.edu';
SQL SUMMARY
INSERT INTO users (name, email) VALUES ('Ted', 'ted@umich.edu');

DELETE FROM users WHERE email='ted@umich.edu';

UPDATE users SET name='Charles' WHERE email='csev@umich.edu';

SELECT * FROM users WHERE email='csev@umich.edu';

SELECT * FROM users ORDER BY email;

SELECT * FROM users WHERE name LIKE '%e%';

SELECT * FROM users ORDER BY email OFFSET 1 LIMIT 2;

SELECT COUNT(*) FROM users WHERE email='csev@umich.edu'


THIS IS NOT TOO EXCITING (SO FAR)
„ Tables pretty much look like big, fast programmable
spreadsheets with rows, columns, and commands.
„ The power comes when we have more than one table and
we can exploit the relationships between the tables.
Database Keys and
Indexes
AUTO_INCREMENT
Often as we make multiple tables
and need to JOIN them together
we need an integer primary key for DROP TABLE users;
each row so we can efficiently add
a reference to a row in some other CREATE TABLE users (
table as a foreign key. id SERIAL,
name VARCHAR(128),
email VARCHAR(128) UNIQUE,
PRIMARY KEY(id)
);
POSTGRESQL FUNCTIONS
Many operations in PostgreSQL need to use the built-in functions (like NOW() for
dates).

https://www.postgresql.org/docs/11/functions.html
INDEXES
„ As a table gets large (they always do), scanning all the data to
find a single row becomes very costly
„ When drchuck@gmail.com logs into Twitter, they must find my
password amongst 500 million users
„ There are techniques to greatly shorten the scan as long as you
create data structures and maintain those structures - like
shortcuts
„ Hashes or Trees are the most common
B-TREES
A B-tree is a tree data structure that keeps data sorted and allows searches,
sequential access, insertions, and deletions in logarithmic amortized time. The
B-tree is optimized for systems that read and write large blocks of data. It is
commonly used in databases and file systems.

http://en.wikipedia.org/wiki/B-tree
HASHES
A hash function is any algorithm or subroutine that
maps large data sets to smaller data sets, called
keys. For example, a single integer can serve as an
index to an array (cf. associative array). The values
returned by a hash function are called hash values,
hash codes, hash sums, checksums, or simply hashes.
Hash functions are mostly used to accelerate table
lookup or data comparison tasks such as finding
items in a database...

http://en.wikipedia.org/wiki/Hash_function
SUMMARY
„ SQL allows us to describe the shape of data to be stored and give many hints
to the database engine as to how we will be accessing or using the data.
„ SQL is a language that provides us operations to Create, Read, Update, and
Delete (CRUD) our data in a database.
ACKNOWLEDGEMENTS / CONTRIBUTIONS
These slides are Copyright 2010- Charles R. Severance (www.dr- Nurlan Shaidullaev, University of Central Asia
chuck.com) as part of www.pg4e.com and made available under a
Creative Commons Attribution 4.0 License. Please maintain this
last slide in all copies of the document to comply with the
attribution requirements of the license. If you make a change, feel
free to add your name and organization to the list of contributors
on this page as you republish the materials.

Initial Development: Charles Severance, University of Michigan


School of Information

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy