Basics of SQL 1

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

BASICS OF SQL

Querying Data for Simple Analysis and Reports


School of IT and Digital Innovation Data Management Office
❖Introduction

❖Overview of Databases

❖Relational Databases

❖Primary and Foreign Keys

❖Query Categories
AGENDA ❖Key Words and Some Basic SQL Functions

❖Joining Tables

❖Writing Basic SQL Queries

❖SQL Best Practices

❖Resources for Further Learning


INTRODUCTION
What is SQL ?
o SQL (Structured Query Language) is a
standard language used to store, retrieve,
and manipulate data in relational databases.

o Why Learn SQL?


It is essential for data analysis, reporting, and
managing databases
OVERVIEW OF DATABASES
Database
o A Database (DB) is a collection of data stored electronically in a structured
way.
o Below are some examples of Databases

DATABASE DESCRIPTION DATABASE MANAGEMENT SYSTEM (DBMS)

Relational Databases (SQL) Store data in a structured format with rows and columns. MySQL, Oracle, PostgreSQL, Microsoft SQL Server
NoSQL Databases that store data in documents, usually in
NoSQL Databases MongoDB, Cassandra, Redis, Couchbase
formats like JSON.
NoSQL Databases that store data as pairs of keys and
Graph Databases Neo4j, OrientDB, ArangoDB
values.
NoSQL Databases that store data in tables, rows, and
Document-Oriented Databases MongoDB, CouchDB
dynamic columns.
NoSQL Databases that are designed to handle data whose
Key-Value Stores Redis, Amazon DynamoDB, Riak
relations are best represented as a graph.
Wide-Value Stores Store data in a structured format with rows and columns. Apache Cassandra, Google’s Bigtable, HBase
RELATIONAL DATABASES
o A relational database is a type of database that
organizes data in predefined relationships where data is
stored in one or more tables (or "relations") of columns
and rows, making it easy to see and understand how
different data structures relate to each other.

o They have 4 main properties - ACID (Atomicity,


Consistency, Isolation, Durability) which allow for data
integrity. They are fundamental to ensuring reliable,
consistent, and robust transactions in a database system.
They help maintain data integrity and handle concurrent
access in a multi-user environment
o A relational database stores data as tables (relations)
made up of rows (records or entities) and columns
(attributes).

Relational database o Tables in a relational database are linked by


relationships. Relationships are created using Keys
(Primary key, Foreign Keys).

o A key is an attribute (column) or set of attributes that


uniquely identifies a record in a table
PRIMARY AND FOREIGN KEYS
Primary Key (PK) is a column that uniquely identifies
a record in a table. A table can have only one primary
key. The PK column cannot be null

Foreign Key (FK) is a column in a table that is a


primary key in another table in the database. Foreign
keys create relationships between tables in a
database.
Query Categories
•SELECT
Data Query •WHERE
Language (DQL) •GROUP BY
•ORDER …

Data Manipulation •INSERT


•UPDATE
Language (DML) •DELETE

Data Definition •CREATE


•ALTER
Language (DDL) •DROP …

Data Control •GRANT


Language (DCL) •REVOKE

Transaction Control •COMMIT


•ROLLBACK
Language (TCL) •SAVEPOINT
KEY WORDS AND SQL FUNCTIONS
o SELECT: Specifies the columns to retrieve.

o DISTINCT: returns only distinct (different) values

o FROM: Specifies the table(s) from which to retrieve the data.

o JOIN: Specifies how to join tables if multiple tables are involved.

o WHERE: Filters rows based on specified conditions.

o GROUP BY: Groups rows that have the same values in specified

columns.

o ORDER BY: Sorts the result set. E.g ASC, DESC


KEY WORDS AND SQL FUNCTIONS
o AGGREGATE FUNCTIONS: COUNT, SUM MIN, MAX, AVG etc

o STRING FUNCTIONS: LENGTH, CONCAT, UPPER, LOWER etc

o DATE AND TIME FUNCTIONS: DATEADD, DATEDIFF, etc


Operators
Operators in SQL are special symbols or reserved keywords used to perform operations on one or
more values (operands) and produce a result

o Arithmetic Operators: Perform basic mathematical operations (+, -, *, /, %).


o Comparison Operators: Compare values and return Boolean results (=, !=, <>, >, <, >=, <=).
o Logical Operators: Combine multiple conditions (AND, OR, NOT).
o String Operators: Perform operations on string values (concatenation using || or +).
o Other Operators: Specialized operators for various operations (IN, BETWEEN, LIKE, IS NULL,
EXISTS).
RIGHT JOIN (or RIGHT OUTER JOIN)
Definition: Returns all rows from the right table
and the matched rows from the left table. If
there is no match, NULL values are returned for
columns from the left table.
Use Case: Used when you want to retain all
records from the right table, even if there is no
match in the left table..
JOINING SELECT columns
FROM table1
TABLES RIGHT JOIN table2
ON table1.common_column =
table2.common_column;
LEFT JOIN
Definition: Returns all rows from the left table and the matched rows from the right table. If there is
no match, NULL values are returned for columns from the right table.
Use Case: Useful when you want to retain all records from the left table, even if there is no match in
the right table.
SELECT columns
FROM table1
LEFT JOIN table2
ON table1.common_column = table2.common_column;
INNER JOIN
Definition: Returns only the rows where there is a match in both tables.
Use Case: Used when you want to retrieve only the records that have corresponding
matches in both tables
SELECT columns
FROM table1
INNER JOIN table2
ON table1.common_column = table2.common_column;
FULL JOIN (or FULL OUTER JOIN)

Definition: Returns all rows when there is a match in one of the tables. If there is no match, NULL values are
returned for columns from the table without a match.
Use Case: Used when you want to include all records from both tables, regardless of whether there is a match.
SELECT columns
FROM table1
FULL JOIN table2
ON table1.common_column = table2.common_column;
SELF JOIN

Definition: A self join is a regular join, but the table is joined with itself.
Use Case: Used to query hierarchical data or compare rows within the same table.
SELECT a.columns, b.columns
FROM table a, table b
WHERE condition;
Syntax: Syntax:
SELECT column1, SELECT column1, column2
column2 FROM table_name
FROM table_name; WHERE condition;
WRITING BASIC
Example: Example:
SQL QUERIES SELECT name, SELECT name, age FROM
age students WHERE age > 18;
FROM students;
SOME SQL BEST PRACTICES

Writing Readable Queries Limit the use of subqueries Write Efficient WHERE Clauses

Where possible, use joins Filter Early: Apply filters as early


Write SQL queries with instead of subqueries to as possible in your queries to
consistent indentation and improve performance. reduce the amount of data
capitalization to make them processed.
easier to read and understand
Resources for Further Learning
Books
SQL for Dummies by Allen G. Taylor
Online Courses
Coursera
Udemy
Udacity
Data Camp
W3schools
Documentation
Official documentation for MySQL
Official documentation for PostgreSQL
Q&A
Open floor for questions and discussions
CONCLUSION
❖ Recap of Key Points

❖ Importance of SQL, Query

Optimization and SQL Best Practices

❖ Next Steps

❖ Encourage further practice and

exploration

You might also like