💻
IT Documentation
  • 🥳Welcome!
  • General Concepts
    • SCRUM
      • Workflow
    • DevOps
      • What is DevOps?
      • What is TDD? (Test Driven Development)
      • What is CI? (Continuous Integration)
      • What is code coverage?
      • Linting best practices
      • Ephemeral Environments
      • Rolling Deployments
      • Blue/Geen Deployments
      • Canary Deployments
      • What is autoscaling & serverless?
      • What is service discovery?
      • What is Log Aggregation?
      • Metric Monitoring
  • AI
    • ChatGPT
      • Better prompts for ChatGPT
  • Cloud
    • AWS
      • AWS - 40 most common Services
      • AWS CLI Cheatsheet
      • Account & IAM
        • Create AWS Account
      • Lambda
        • Create Lambda function for Lightsail
      • Route 53
        • Set up R53 DNS Entry for GitBook
      • RDS
        • AWS RDS Burst Balance
      • VPC
        • What is a VPC
      • EC2
        • Removing EC2 user from sudo list
        • Create a Windows Gaming VPS
        • Connecting to a AWS EC2 instance
    • Azure
      • Courses
        • AZ900 Course
          • Overview
            • Describe Core Concepts
            • Cloud Models (IaaS, PaaS, SaaS)
          • Benefits of Cloud Computing
          • Cloud Models and Cloud Types
            • Overview of Cloud Models
            • IaaS, PaaS, SaaS
            • The Serverless Model
            • Cloud Types
          • Core Azure Architectural Components
            • Overview
            • Regions & Availability Zones
            • Resource Groups & Subscriptions & Management Groups
            • Resources & Resource Manager
          • Core Resources available
            • Compute Resources
            • Networking Resources
            • Storage Resources
            • Database Services
            • Azure Marketplace
          • Azure Core Solutions
            • Overview
            • Internet of Things (IoT) Solutions
            • Big Data Solutions
            • AI Solutions
            • Azure Functions & Logic Apps and Event Grid
            • DevOps Solutions
          • Azure Management Tools
            • Overview
            • Managing Azure with ARM Templates
            • Azure Monitor & Azure Service Health
          • Azure Security Features
            • Overview
            • Azure Security Center
            • Azure Key Vault & Azure Sentinel
            • Azure Dedicated Hosts
          • Azure Network Security
            • Network Security Group (NGS), Firewall and DDoS Protection
          • Azure Identity Services
            • Overview
            • Benefits
            • Multi-Factor Authentication (MFA)
            • Authentication vs Authorization
          • Azure Governance Features
            • Authentification and RBAC
            • Resource Locks
            • Azure Policy
            • Azure Blueprints
            • Cloud Adoption Framework (CAF)
          • Compliance Features
            • Core tenets of Security, Privacy and Compliance
            • Privacy Statement and Online Service Terms (OST)
            • Trust Center
            • Azure Sovereign Regions
          • Manage Azure Costs
            • Overview
            • Best practices
            • Pricing calculator
            • Azure Cost Management
          • SLA (Service level Agreements)
      • Virtual Machines
        • VM
          • Create a VM in a VNET
          • Azure VM LVM corruption fix
        • VMSS
          • Add SSH Key to VMSS
  • Containerization
    • Docker
      • Docker Cheatsheet
      • Install docker on Debian
      • Docker misc stuff
    • Docker Swarm
      • Docker Swarm Cheatsheet
      • Set up docker swarm
      • Delete docker swarm
      • Mount and bind volumes
      • Deploy Portainer via docker swarm
    • Docker Compose
      • Jenkins via Docker Compose
      • PostgreSQL via Docker Compose
      • Wireguard via Docker Compose & HTTPS
    • Rancher
      • Rancher installation guide
  • Cluster Computing
    • Slurm
      • Job Manager is not responding
      • Create new user
    • OpsCenter
      • Clear old Snapshots
      • Issues listing snapshots with nodetool
  • Database
    • General SQL
      • Database introduction
      • SQL 101
      • SQL Cheatsheet
      • User rights
      • Table Creation
      • SQL Replication - Best practice
      • SQL Database Design
    • MS SQL
      • Update whole table fast
    • Oracle SQL (PL/SQL)
      • Oracle SQL Cheatsheet
      • Oracle SQL - Kill Sessions
    • PostgreSQL
      • Install PostgreSQL
      • Create PostgreSQL Role and Database
      • Managing Postgres with PgAdmin GUI
      • Enable remote access for PostgreSQL
      • Authentication on PostgreSQL
      • Returning in Postgres
    • SQLite
    • Flyway Overview
    • SSRS Overview
    • Cassandra
      • GC OutOfMemoryError
  • DevOps
    • Ansible
      • Ansible Cheatsheet
      • Common Ansible Tasks
    • Git
      • Git 101
      • Git 1kb files
      • Git Commit changes before merge
      • Git Misc
      • Git Markdown
      • Git Clone Repo via SSH
    • Github
      • How to use multiple accounts
      • Delete commits fully
      • Set up git ignore file
    • Github Actions
      • Install self hosted runner
      • Scheduling jobs cron style
      • Passing ENV variable in script
      • SSH to Server
    • GitLab
      • GitLab Cheatsheet
    • Terraform
      • Terraform components
  • Hardware
    • UPS - Njoy
  • IoT
    • Home Assistant
      • Valetudo configs
      • Mini Media Player
      • HACS
    • Valetudo
      • Roborock Gen 1
      • Roborock quick guide
      • Roborock full Valetudo install guide
    • Tasmota
      • Tuya-Convert
    • LibreELEC
      • Quick LibreELEC guide
      • Configure X96 Mini Remote
  • OS
    • Linux
      • Learning guidelines
        • LPIC1 Notes
        • Linux Academy Notes
      • Install / Update Guides
        • Set up Raspberry PI
        • Update Debian 10 (buster) to Debian 11 (bullseye)
      • Increase disk size
      • umask
      • inodes
      • at jobs
      • yum
        • yum update vs yum upgrade
      • find
      • ssh
        • SSH returns: no matching host key type found. Their offer: ssh-rsa
        • Generate Public Key from Private Key
        • Run local bash scripts on remote server
      • crontab
        • Crontab 1st Sunday of every Month
        • Set crontab to execute after restart
      • vim
        • Use sed inside vim
      • networking
        • Check Port
      • fail2ban
      • bashrc
      • lvm
      • fallocate
        • Generate dummy file with actual size
      • openssl
        • Create Certificate via CNF file
        • OpenSSL cert conversion
    • Windows
      • Windows - Get App port by PID
      • Windows - Upgrade Windows build
      • Windows - Server
    • Android
      • Android - Motorola Unlock
      • Android - /E Project
    • PinePhone
      • PinePhone - Instructions for creating a PureOS image for PinePhone
  • Monitoring
    • Nagios
      • CPU threshold value calculation
    • New Relic
      • New Relic Flex Integration
      • NRQL Alerts examples
    • Zabbix
      • Zabbix Proxy not communicating with Windows Server
  • Microsoft Suite
    • Outlook
      • Change View
    • Excel
      • Excel Shortcuts
    • Windows Subset for Linux
      • WSL no internet connection
  • Networking
    • General Networking
      • IP Classes and Subnet Masks
      • Network CIDR Charts - /-es or IP Prefix
      • OSI Model Overview
      • Three Way Handshake & TCP Overview
    • F5
    • Authelia
      • What is Authelia
    • Nginx Proxy Manager
      • Nginx Proxy Manager - DuckDNS going down
    • Nmap
    • OpenWRT
      • Securing OpenWRT
      • OpenWRT - Read logs
      • OpenWRT - Adding DHCP Entry
      • OpenWRT - Wireguard
      • OpenWRT - Set up OpenVPN
      • OpenWRT - Internal DNS Service
      • OpenWRT - Set up new Wifi Interface
      • OpenWRT - Set up VLAN
      • OpenWRT - VPN Policy Routing
    • Pihole
      • Enabling HTTPS for your Pihole Web Interface
      • Edit Pihole DNS entries
    • RVS
      • RVS - Observer Modification
      • RVS - All Parameters
      • RVS - Adding a station
    • Wireguard
    • FTP
      • Connect to FTP anonymously
  • Pen Testing
    • CTF
      • CTF Links
  • Programming
    • Python
      • Classic Python
        • Python Cheatsheet
        • Python Shortcuts
        • Dunder Methods
        • hasattr(), getattr(), delattr()
        • Useful Exceptions
        • Dictionary
        • isinstance()
        • isdigit(), isdecimal(), isalpha()
        • return
        • Functions
        • Lists
        • ord(), chr()
        • squares, twos, odds
        • Bubble sort
        • append() and insert()
        • Bitwise operators
        • while, for & else
        • Arithmetic Operators
        • equal operators
        • Structure Projects
      • Modules
        • Webscraping
          • BeautifulSoup
        • PySimpleGui
          • Fast Crashcourse on PySimpleGui
        • os
        • python-docx
          • Generate DOCX file
        • psycopg2
          • PostgreSQL Connection
        • Pydantic Model vs SQLAlchemy Model
      • Frameworks
        • FastAPI
          • FastAPI Quick overview
          • Installing FastAPI and Dependencies
          • Starting FastAPI
          • Path Operations
          • Creating HTTP Operation paths
          • Send Data via Body of HTTP Request
          • Schema Validation with Pydantic
          • CRUD Operations
          • Storing in Array
          • Retrieve one individual entry
          • Changing response Status Codes
          • Deleting entries
          • Updating entries
          • API Documentation
          • Setup App Database & connect to database
          • FastAPI Response Model via Pydantic
          • Hashing passwords via FastAPI
          • Getting user by ID
          • FastAPI Routers
          • Router Prefix
          • Router Tags
          • JWT Token Basics
          • Login Process
          • Creating Token with OAuth2
          • OAuth2 PasswordRequestForm
          • Verify user is Logged In
          • Protecting Routes
          • Fetching User in Protected Routes
        • SQLAlchemy
          • What is an ORM
          • SQLAlchemy setup
          • Adding CreatedAt Column
          • CRUD via SQLAlchemy
          • Efficient way of passing params in SQLAlchemy
          • Creating Users Table via SQLAlchemy & FastAPI
      • Virtual Environments (venv)
    • General Programming Concepts
    • Interview Questions & Answers
      • General Programming Questions
      • Python Interview Questions Beginner
    • Courses
      • Python - PCAP-31-03 Course
        • Overview & Introduction
          • Exam Syllabus
          • Basics of variables
          • Basic Data Types
          • Basic Arithmetic in Python
          • Indexing and Slicing Strings
          • Basic String Methods
          • Format Method
          • Strings are Immutable
        • Lists, Tuples and Dictionaries
          • Lists
          • Accessing Elements in Nested Lists
          • Finding Index positions in Lists and counting duplicates
          • Tuples
          • Dictionaries
          • Comparison Operators
        • Functions and Variable Scope
          • Creating functions
          • *args and **kwargs
          • Basic Variable scope
          • Scope and Nested functions
        • Control Flow
          • If & Else Statements
          • Elif Statements
          • For Loops
          • Pass Statement in For Loops
          • While Loops
          • Looping and Unpacking with Dictionaries and Tuples
          • Range, Enumerate and Zip Functions
          • More Handy Functions and the Random Package
          • Accepting Input from User
        • Modules, Packages and OOP
          • Revising the Difference between Methods and Functions
          • Classes and Objects
          • Classes Attributes vs Object Attributes
          • Calling Python Code that is Saved in Another File
          • Inheritance and Polymorphism
          • Abstract Classes and Methods
          • Practical Application of OOP
          • Double Under (Dunder) Methods
          • Python Script Files
          • Python Files
          • Understanding the if __name__ == '__main__' Syntax
        • File IO and Exception Handling
          • Exception Handling
          • File IO
          • File IO with Exception Handling
          • OS Module
          • argv Command Line Arguments and the re Module
        • Misc Stuff and Q&A
    • IDE
      • Virtual Studio Code
        • Cheatsheet
    • Postman
      • Postman Overview
      • Create a GET HTTP request
      • HTTP Requests
      • Saving Postman requests
      • Environment Variables
  • Virtualization
    • Proxmox
      • Proxmox Cheatsheet
      • Proxmox Common Errors
      • Install Home Assistant in Proxmox via script
      • Create cloud-init template
      • Install guest-agent on new VM
      • Proxmox post install script
  • Webservers
    • Apache
      • Redirect 301 - Apache to index.html
    • Glassfish
      • Redirect 301 Glassfish
    • Tomcat
      • Useful tomcat files
  • Storage
    • NetApp
      • Netapp Overview
      • How to create symlinks
    • Nextcloud
      • Nextcloud Snap install and S3 Storage Bucket
      • Nextcloud Fail2Ban Regex
      • Set up OnlyOffice on Nextcloud
      • Set up Joplin and CalDav on Nextcloud
  • Software
    • Ansys
      • Ansys missing libraries
      • Ansys install
    • Jboss
      • Jboss process not working
Powered by GitBook
On this page
  • SQL Statements:
  • The 4 Fundamental Database functions are CRUD
  • SQL Statement Analysis
  1. Database
  2. General SQL

SQL 101

SQL is a simple languadge with a Simple Syntax to manage Relational Databases

SQL Statements:

A statement is the unit of execution in SQL

SELECT * FROM Countries WHERE Continent = 'Europe';

An SQL statement usually includes 1 or more Clauses

FROM clause
  • This specifies which table the Statement will use

WHERE clause
  • This specifies which rows will be selected

The WHERE clause requires an EXPRESSION: Logical Expression:

Continent = 'Europe'

The 4 Fundamental Database functions are CRUD

  • Create

  • Read

  • Update

  • Delete

The SELECT statement is used for ALL STATEMENTS that retrieve values. - (This is the R in CRUD)

The INSERT statement is used to ADD A ROW to a TABLE - (This is the C in CRUD)

The UPDATE statement is used to CHANGE DATA - (This is the U in CRUD)

The DELETE statemnt is used to DELETE ROWS from a TABLE - (This is the D in CRUD)

The WHERE clause is used to select which row or rows are to be UPDATED

Purpouse of a Database is to organize your data and make it available in convinient from. SQL is a Languadge for managing a RELATIONAL DATABASE. This is organized in 2 dimentional tables comprised of ROWS and COLUMNS

A Database has Tables. Can have 1 or more tables which are organized in ROWS and COLUMNS:

A ROW is like an individual RECORD in the table. A COLUMN is like a FIELD in the table. EACH ROW in the TABLE has a UNIQUE KEY. Sometimes the KEY is HIDDEN but a TABLE must have one.

When a COLUMN is used as a UNIQUE KEY it is often called the PRIMARY KEY

In the above example the DEPT_ID COLUMN is used as the PRIMARY KEY.

Note: Different Engines do this differently but there is ALWAYS a UNIQUE KEY.

The TABLES are RELATED by the TABLES KEYS

In this example the ADMIN TABLE has COLUMNS for DEPT_ID that make reference to the DEPT TABLE This is called aFORIGN KEYbecause it refers to the KEYS of OTHER TABLES.

These relationships allow to make JOINT QUERIES, to treat ROWS and SEVERAL TABLSE as JOINT UNITS.

SQL Statement Analysis

SELECT Statement:

SELECT ‘Hello, World’ AS Result;
  • This uses a SELECT statement to retrieve information. Simple quotations ' ' are used to select a STRING.

  • AS is a KEYWORD.

  • When you execute the Query it changes the COLUMN name to Result.

To SELECT all from a TABLE use:

SELECT * FROM Country;

If we want them in a Different order you can use ORDER BY:

SELECT * FROM Country ORDER BY Name; 

If we don’t want all the rows you can specify the names denominated by a “,”:

SELECT Name, LifeExpectancy FROM Country ORDER BY Name; 

Example: This might not result right so you might want to give an alias for LifeExpectancy to be AS Life Expectancy

SELECT Name, LifeExpectancy AS “Life Expectancy” FROM Country ORDER BY Name; 

Note: You have to use Double Quote “ “ The Quotes are needed as the IDENTIFIER has SPACES in it, if it wouldn’t then you don’t even need the Quotes.

SELECT Name, Continent, Region FROM Country WHERE Continent = ‘Europe’; 
  • This selects the 3 columns NAME, CONTINENT, REGION from the Table Country where the Continent Column is Europe.

If we want them in a particular order we can use ORDER BY for example:

SELECT Name, Continent, Region FROM Country WHERE Continent = ‘Europe’ ORDER BY name;

If we want to LIMIT the results we can use the LIMIT CLAUSE:

SELECT Name, Continent, Region FROM Country WHERE Continent = ‘Europe’ ORDER BY name LIMIT 5;

This LIMITS the results to the first 5 results. So the above, orders in Alphabetical order by NAME and then shows only the first 5 RESULTS as opposed to the 46 ROWS without LIMIT.

  • If we want to skip the first 5 but want the next 5 we can use the OFFSET CLAUSE:

SELECT Name, Continent, Region FROM Country WHERE Continent = ‘Europe’ ORDER BY name LIMIT 5 OFFSET 5; 

QUIRCKS OF SQL:

  • The ORDER BY clause has to be AFTER any WHERE clause (if used)

  • LIMIT and OFFSET have to be LAST

  • FROM needs to be FIRST after the SELECT STATEMENT.

SELECT Name AS Country, Continent, Region FROM Country;
  • This RENAMES the NAME Column as COUNTRY

You can also swap the order by changing the order of the COLUMNS after the SELECT STATEMENT:

SELECT Name AS Country, Region, Continent FROM Country;

COUNT function allows you to count the ROWS within a table.

SELECT COUNT (*) FROM Country; 

You can limit the RESULTS by doing

SELECT COUNT (*) FROM Country WHERE Population > 1000000;
  • This will COUNT the rows only where the population is greater then 1 mil.

To limit by other factors too you can use AND

SELECT COUNT (*) FROM Country WHERE Population > 1000000 AND Continent = ‘Europe’;

COUNT (*) is a Special case as it counts all the rows, if we use COUNT (LifeExpectancy) it will have a different number as it will count ONLY THE ROWS WITH DATA IN THEM.

INSERT Statement:

To insert Values into a table you can use the insert statement:

AFTER:

INSERT INTO customer (name, address, city, state, zip)
    VALUES (‘Fred Flintstone’, ‘123 Cobblestone Way’, ‘Bedrock’, ‘CA’, ‘9123’);
  • This inserts the values in each field. When you specify the name of the column you have to order the values as well.

  • I.e. Name = Fred Flintstone.

You can also insert information just in some fields and the other ones will be denoted by NULL:

INSERT INTO customer (name, city, state)
	VALUES (‘Jimi Hendrix’, ‘Renton’, ‘WA’); 

UPDATE Statement:

TO CHANGE DATA in a TABLE we use the UPDATE STATEMENT:

UPDATE customer SET address = ‘123 Music Avenue’, zip = ‘98056’ WHERE id=5;

IF THE WHERE CLAUSE DOES NOT EXIST IT WILL DO IT TO THE ENTIRE TABLE! SO YOU HAVE TO LIMIT IT!

  • This will populate the Address field and Zip field with the strings provided where the ID of the entry is 5.

To update already populated field it is the same command but with new strings:

UPDATE customer SET address = ‘Washington ST’, zip = ‘9999’ WHERE id=5;

To add NULL values you will have to specify this in the UPDATE statement:

UPDATE customer SET address = NULL, zip = NULL WHERE id=5;

MAKE SURE NOT TO SET THEM AS STRINGS AS THESE WILL BE POPULATED AS SUCH.

DELETE Statement:

DELETE FROM customer WHERE id = 4;
SELECT * FROM customer;
  • This deletes from the customer TABLE the entry with ID = 4 and then SELECTS everything to see if this has been deleted by the user.

CREATING A TABLE:

CREATE TABLE test (
	a INTEGER,
	b TEXT
);
  • The part between the () is the SCHEMA

  • Syntax: COULMN NAME = A and the TYPE of the COLUM = INTEGER

  • THE LAST ROWN WITHIN THE () CANNOT HAVE A COMMA (,) - This will generate a syntax error.

TO DELETE A TABLE we use the DROP TABLE Statement:

DROP TABLE test;
  • This deletes the table

DROP TABLE IF EXISTS test; 
  • This does not return an error if the table does not exist.

Inserting Rows:

INSERT INTO test ( b, c) VALUES ( ‘One’, ‘Two’); 
  • Inserts values only in Column B and C leaving Column A with the NULL value.

If you want to insert a table with no values in it use:

INSERT INTO test DEFAULT VALUES;
  • This creates a empty row with the NULL values

TO ADD VALUES FROM A DIFFERENT TABLE YOU CAN DO:

INSERT INTO test ( a, b, c, ) SELECT id, name, description from item 
  • This selects the data from the ITEM TABLE to place it in each column a = id b = name c = description THIS ADDS ALL ROWS FROM THE TABLE SPECIFIED.

DELETING ROWS:

DELETE FROM test WHERE a = 3; 
  • This will delete ROW where the INTEGER value = 3 on the A COLUMN.

DELETING ROWS IS DESTRUCTIVE SO IT IS GOOD TO AUDITION THIS BEFORE WITH:

SELECT * FROM test WHERE a = 3; 

The NULL value – Is not a value, is the absence of a value. To test for NULL you have to use

SELECT * FROM test WHERE a IS NULL; 

The opposite of NULL is:

SELECT * FROM test WHERE a IS NOT NULL; 

To CREATE a TABLE that does not accept NULL values use:

CREAT TABLE test (
a INTEGER NOT NULL,
b TEXT NOT NULL,
c TEXT
); 

If you do:

INSERT INTO test (a, c) VALUES (‘one’, ‘two’); 

It will result in a ERROR:

Error while executing SQL query on database ‘test’: NOT NULL constraint failed test.b.
  • This is because we delimited the B COLUMN to not accept NULL and we are not inserting a value in it with the INSERT above

CONSTRAINING COLUMNS:

To add constraints when creating a TABLE you can do:

CREATE TABLE test (a TEXT, b TEXT, c TEXT NOT NULL);
INSERT INTO test (a, b) VALUES (‘one’, ‘two’);
SELECT * FROM test;
  • THIS WILL FAIL. It fails because we have set a constraint for the C COLUMN to be any value except NULL.

  • And then we are trying to insert values in A & B but NOT C and the C Column does not accept to be NULL.

DEFAULT VALUE:

CREATE TABLE test (a TEXT, b TEXT, c DEFAULT ‘panda’);
INSERT INTO test (a, b) VALUES (‘one’, ‘two’);
SELECT * FROM test;
  • NOW with this when we fail to add data to C it will set the DEFAULT value of the entry to ‘panda’.

UNIQUE VALUE:

CREATE TABLE test (a TEXT UNIQUE, b TEXT, c DEFAULT ‘panda’);
INSERT INTO test (a, b) VALUES (‘one’, ‘two’);
INSERT INTO test (a, b) VALUES (‘one’, ‘two’);
SELECT * FROM test;
  • THIS WILL FAIL because we have set the A COLUMN to accept only UNIQUE values and then we are trying to insert the same values 2 times. Fails with: UNIQUE constraint failed test.a

IF WE CHANGE THE VALUE FOR A IT WILL WORK:

CREATE TABLE test (a TEXT UNIQUE, b TEXT, c DEFAULT ‘panda’);
INSERT INTO test (a, b) VALUES (‘one’, ‘two’);
INSERT INTO test (a, b) VALUES (‘uno’, ‘two’);
SELECT * FROM test;
  • NULL is Exempted from the UNIQUE constraint.

You can also combine CONSTRAINTS:

CREATE TABLE test (a TEXT UNIQUE NOT NULL, b TEXT, c DEFAULT ‘panda’);

CHANGING A SCHEMA:

If you need to change the schema for example add a new COLUM you can do:

ALTER TABLE test ADD d TEXT;

ID COLUMNS:

When creating a table:

CREAT TABLE test (
	id INTEGER PRIMARY KEY,
	a INTEGER,
	b TEXT
); 

The ID COLUMN will be used as a KEY and it will give SEQUENCIAL UNIQUE NUMBERS to then field. It does this whether you have it or not, these are very common in RELATIONAL DATABASES. It makes it easier to create database RELATIONS between tables and rows.

FILTERING DATA:

SELECT Name, Continent, Population FROM Country
	WHERE Population < 100000 ORDER BY Population DESC;

THE WHERE CLAUSE ALLOWS YOU TO FILTER DATA: KIND OF LIKE PIPE IN LINUX:

ls -al | grep something
  • The SELECT STATEMENT will bring DATA from the COLUMNS Name, Continent, Population from the COUNTRY TABLE

  • WHERE Population is less then 100 000 and it will ORDER it BY DESCENDING order of the POPULATION COLUM

SELECT Name, Continent, Population FROM Country
	WHERE Population < 100000 OR Population IS NULL ORDER BY Population DESC;
  • This will do the same as above but it will also include the POPULATION COLUMN where the NULL STATE is found.

  • OR is a powerful BOOLEAN operator that allows you to combine MULTIPLE EXPRESSIONS such as:

WHERE Population < 100000 OR Population IS NULL ORDER BY Population DESC;
  • This looks for Population that is less the 100.000 OR the STATE in NULL

The other powerful operator is AND This is like piping a pipe in Linux:

ls -al | grep something | grep somethingelse
WHERE Population < 100000 AND  Continent = ‘Oceania’ ORDER BY Population DESC;
  • This statement will check that both conditions are met. The Population has to be less then 100.000 AND the Continent has to be Oceania

THE LIKE OPERATIOR

SELECT Name, Continent, Population FROM Country
	WHERE Name LIKE ‘%island%’

% is a wildcard quivalant to * in Linux

  • Basically what it means * island* Anything before and after as long as it contains the STRIG ISLAND

You can also do:

%island = *island
island% = island*

Another wildcard is _ which is the equivalent of . In Linux

_a% = .a*
  • A is the second character followed by any other letter STRINGS.

The IN operator:

SELECT Name, Continent, Population FROM Country
	WHERE Continent IN (‘Europe’, ‘Asia’); 
  • This will select the COLUMNS specified after SELECT from the Country Table WHERE the Continents are Europe or Asia

REMOVING DUPLICATES:

In order to check for Entries that are not duplicates you can use the DISTINCT statement:

SELECT DISTINCT Continent FROM Country;

ORDERING OUTPUT:

You can use the ORDER BY Statement to order things more specifically:

SELECT Name FROM Country ORDER BY Name; - Sorts stuff Ascii Alphabetical
SELECT Name FROM Country ORDER BY Name DESC;
  • This sorts Alphabetically but Descendent (Last in First Out)

SELECT Name FROM Country ORDER BY Name ASC; – This is the Default
  • This sorts Alphabetically but Ascendent (First in Frist Out)

You can also order by continent first and then by name with

SELECT Name, Continent FROM Country ORDER BY Continent, Name;
SELECT Name, Continent, Region FROM Contry ORDER BY Contient DESC, Region, Name;
  • This orders by Continent first in Descending order, then Region and Name ASC

CONDITIONAL EXPRESSIONS:

In standard SQL 0 is considered FALSE and anything that IS NOT 0 is Considered TRUE

SELECT 
	CASE WHEN a THEN ‘true’ ELSE ‘false’ END AS boolA,
	CASE WHEN b THEN ‘true’ ELSE ‘false’ END AS boolB
FROM booltest;
  • CASE is usefull to check for values. For example the above tests if the A COLUMN is Anything but 0 and then you will get the THEN clause = True

  • If the value is 0 then you will get the ELSE clause = False

UNDERSTANDING JOIN:

The JOIN command is useful for executing queries from multiple tables that have RELATIONS:

  • Most Common JOIN is the INNER JOIN that only takes data/values that are in both tables:

  • Less Common but still useful is OUTER JOIN (which can be left or right) This takes the values that are common and the values that are in the table specified (LEFT or RIGHT)

  • FULL OUTER JOIN combines the effects of a LEFT AND RIGHT OUTER JOIN:

SELECT l.description AS left, r.description AS right
	FROM left AS l
	JOIN right AS r on l.id = r.id
;
SELECT l.description ← This selects the description column AS left, r.description AS right
	FROM left AS l ←This creates alias for LEFT as L
	JOIN right AS r ON l.id = r.id ← This then joins the RIGHT table as R onto the LEFT table where the condition that ID from the LEFT Table matches the ID from the RIGHT Table. 
;
  • Basically what it does is SELECTS the DESCRIPTION COLUMN from the RIGHT TABLE with an alias of L and then merges it VIA JOIN with the RIGHT table and then DISPLAYS THE ID VALUES THAT MATCH.

To make this an OUTER JOIN you have to specify LEFT JOIN:

SELECT l.description AS left, r.description AS right
FROM left AS l
	LEFT JOIN right AS r on l.id = r.id
;
  • This brings the values of the INNER JOIN above but also adds the values that do not match from the LEFT table.

STRINGS: If you need to use single Quotes in a string you will have to use 2 of them like this: SELECT ‘Here’’s a single quote mark’;

Length:

SELECT LENGTH (‘string’) – Tells us how long the string is I.e length of 6. 
SELECT SUBSTR (‘this string’, 6); - This selects a value from the string starting with the 6th position. 

We can also specify the number of characters to retruns for example:

 SELECT SUBSTR (‘this string’, 6, 3);

TRIM: Trims text:

SELECT TRIM (‘    string     ‘)
SELECT LTRIM – Removes Left spaces but not Right
SELECT RTRIM – Removes Right spaces but not Left

You can also capitalize or lower case strings by using the LOWER or UPPER arguments:

SELECT LOWER (‘StRIng’) = LOWER(‘string’)
SELECT UPPER (‘StRing’) = UPPER (‘string’)

INTEGER TYPES:

  • INTEGER (precision)

  • DECIMAL (precision, scale)

  • MONEY (precision, scale)

REAL TYPES:

  • REAL (precision)

  • FLOAT (precision)

  • PRECISION vs SCALE:

PreviousDatabase introductionNextSQL Cheatsheet

Last updated 3 years ago