Browse Source

automated terminal push

production
Software Shinobi 3 months ago
parent
commit
749454d815
  1. 15
      .dockerignore
  2. 713
      .gitignore
  3. 3
      Dockerfile
  4. 75
      Jenkinsfile
  5. 19
      compose.bash
  6. 72
      compose.yaml
  7. 320
      datasets/local-real-estate.sql
  8. 1236
      datasets/mega-mart-grocery.sql
  9. 381
      datasets/monaco-motors-dealership.sql
  10. 4
      datasets/user-readonly-create.sql
  11. 4
      datasets/user-shinobi-create.sql
  12. 15
      docs/Dockerfile
  13. 19
      docs/compose.bash
  14. 18
      docs/compose.yaml
  15. 419
      docs/docs/.recycle/.gemini.md
  16. 40
      docs/docs/.recycle/sql-101.md
  17. 145
      docs/docs/Introduction-To-Databases/004-basic-syntax.md
  18. 359
      docs/docs/Introduction-To-Databases/005-select.md
  19. 225
      docs/docs/Introduction-To-Databases/006-where.md
  20. 143
      docs/docs/Introduction-To-Databases/007-order-and-group-by.md
  21. 86
      docs/docs/Introduction-To-Databases/008-insert.md
  22. 106
      docs/docs/Introduction-To-Databases/009-update.md
  23. 41
      docs/docs/Introduction-To-Databases/010-delete.md
  24. 370
      docs/docs/Introduction-To-Databases/011-join.md
  25. 121
      docs/docs/Introduction-To-Databases/012-sql-commnad-categories.md
  26. 112
      docs/docs/Introduction-To-Databases/013-sub-queries.md
  27. 124
      docs/docs/Introduction-To-Databases/014-unions.md
  28. 51
      docs/docs/Introduction-To-Databases/015-Keys-in-a-Relational Database.md
  29. 17
      docs/docs/Introduction-To-Databases/016-Logical-operator-keywords.md
  30. 186
      docs/docs/Introduction-To-Databases/017-having-clause_aggregate-functions.md
  31. 191
      docs/docs/Introduction-To-Databases/018-essential-mysql-functions.md
  32. 154
      docs/docs/Introduction-To-Databases/020-TCL-commands.md
  33. 39
      docs/docs/Introduction-To-Databases/index.md
  34. BIN
      docs/docs/cover.png
  35. 77
      docs/docs/index.md
  36. 138
      docs/docs/schema.md
  37. 49
      docs/docs/styling.css
  38. 21
      docs/mkdocs.bash
  39. 41
      docs/mkdocs.yml
  40. 21
      docs/provision.bash
  41. 0
      license.md
  42. 77
      readme.md

15
.dockerignore

@ -0,0 +1,15 @@
*.md
*.log
LICENSE
.dockerignore
.git*
.recycle
.trash

713
.gitignore vendored

@ -0,0 +1,713 @@
# ---> Java
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
replay_pid*
# ---> Node
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
# ---> Windows
# Windows thumbnail cache files
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
# ---> Linux
*~
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
# ---> macOS
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
# ---> Eclipse
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# PyDev specific (Python IDE for Eclipse)
*.pydevproject
# CDT-specific (C/C++ Development Tooling)
.cproject
# CDT- autotools
.autotools
# Java annotation processor (APT)
.factorypath
# PDT-specific (PHP Development Tools)
.buildpath
# sbteclipse plugin
.target
# Tern plugin
.tern-project
# TeXlipse plugin
.texlipse
# STS (Spring Tool Suite)
.springBeans
# Code Recommenders
.recommenders/
# Annotation Processing
.apt_generated/
.apt_generated_test/
# Scala IDE specific (Scala & Java development for Eclipse)
.cache-main
.scala_dependencies
.worksheet
# Uncomment this line if you wish to ignore the project description file.
# Typically, this file would be tracked if it contains build/dependency configurations:
#.project
# ---> NetBeans
**/nbproject/private/
**/nbproject/Makefile-*.mk
**/nbproject/Package-*.bash
build/
nbbuild/
dist/
nbdist/
.nb-gradle/
# ---> VisualStudio
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
*.ncb
*.aps
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml
# ---> VisualStudioCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets
# Local History for Visual Studio Code
.history/
# Built Visual Studio Code Extensions
*.vsix

3
Dockerfile

@ -0,0 +1,3 @@
FROM mariadb
ADD datasets/ /docker-entrypoint-initdb.d

75
Jenkinsfile vendored

@ -0,0 +1,75 @@
pipeline {
agent none
options {
disableConcurrentBuilds(abortPrevious: true)
buildDiscarder(logRotator(numToKeepStr: '1'))
}
stages {
stage('docker compose build') {
agent {
label "aventador"
}
steps {
dir('.') {
sh 'docker compose build'
}
}
}
stage('docker compose push') {
agent {
label "aventador"
}
steps {
dir('.') {
sh 'docker compose push'
}
}
}
stage('prune') {
agent {
label "aventador"
}
steps {
dir('.') {
sh 'docker system prune -a -f'
}
}
}
}}

19
compose.bash

@ -0,0 +1,19 @@
#!/bin/bash
##
reset;
clear;
##
set -e;
set -x;
##
docker compose down --remove-orphans
docker compose up --build -d

72
compose.yaml

@ -0,0 +1,72 @@
services:
shinobi-academy-database-server:
container_name: shinobi-academy-database-server
image: softwareshinobi/shinobi-academy-database-server
build:
context: .
dockerfile: Dockerfile
restart: unless-stopped
ports:
- 3306:3306
volumes:
- /tmp/volumes/academy/database:/var/lib/mysql
environment:
MYSQL_ROOT_PASSWORD: aggiepride
MYSQL_DATABASE: sandbox
MYSQL_USER: sandbox
MYSQL_PASSWORD: sandbox
shinobi-academy-database-admin:
container_name: shinobi-academy-database-admin
image: beeyev/phpmyadmin-lightweight
restart: unless-stopped
depends_on:
- shinobi-academy-database-server
ports:
- 3380:80
environment:
PMA_HOST: shinobi-academy-database-server
MYSQL_ROOT_PASSWORD: aggiepride
shinobi-academy-database-docs:
container_name: shinobi-academy-database-docs
image: softwareshinobi/shinobi-academy-database-docs
build:
context: docs
dockerfile: Dockerfile
ports:
- 3388:80

320
datasets/local-real-estate.sql

@ -0,0 +1,320 @@
CREATE DATABASE `LOCAL_REAL_ESTATE` DEFAULT CHARACTER SET utf8mb4;
USE `LOCAL_REAL_ESTATE`;
/* create tables of attributes */
CREATE TABLE Property(
address VARCHAR(50) NOT NULL,
ownerName VARCHAR(30),
price INT,
PRIMARY KEY(address)
);
CREATE TABLE House(
address VARCHAR(50) NOT NULL,
ownerName VARCHAR(30),
price INT,
bedrooms INT,
bathrooms INT,
size INT,
FOREIGN KEY(address) REFERENCES Property(address)
);
CREATE TABLE BusinessProperty(
address VARCHAR(50) NOT NULL,
ownerName VARCHAR(30),
price INT,
type CHAR(20),
size INT,
FOREIGN KEY(address) REFERENCES Property(address)
);
CREATE TABLE Firm(
id INT NOT NULL,
name VARCHAR(30),
address VARCHAR(50),
PRIMARY KEY(id)
);
CREATE TABLE Agent(
agentId INT NOT NULL,
name VARCHAR(30),
phone CHAR(12),
firmId INT NOT NULL,
dateStarted DATE,
PRIMARY KEY(agentId),
FOREIGN KEY(firmId) REFERENCES Firm(id)
);
CREATE TABLE Listing(
address VARCHAR(50),
agentId INT,
mlsNumber INT PRIMARY KEY,
dataListed DATE,
FOREIGN KEY(agentId) REFERENCES Agent(agentId),
FOREIGN KEY(address) REFERENCES Property(address)
);
CREATE TABLE Buyer(
id INT NOT NULL,
name VARCHAR(30),
phone CHAR(12),
propertyType CHAR(20),
bedrooms INT,
bathrooms INT,
businessPropertyType CHAR(20),
minimumPreferredPrice INT,
maximumPreferredPrice INT,
PRIMARY KEY(id)
);
CREATE TABLE Work_With(
buyerId INT,
agentId INT,
FOREIGN KEY(buyerId) REFERENCES Buyer(id),
FOREIGN KEY(agentId) REFERENCES Agent(agentId)
);
/* create an assertion */
/*
CREATE ASSERTION PROPERTY_AGENT_PROJECTION CHECK
(NOT EXISTS
(SELECT L1.address
FROM Listings L1, Listings L2
WHERE L1.address = L2.address AND L1.agentId != L2.agentId
)
);
*/
/* insert records to each tables, each table has at least 5 records */
/* 10 records into Property */
INSERT INTO Property
VALUES('2350 Gibson Road', 'John Smith', 235000);
INSERT INTO Property
VALUES('197 Watson Street', 'Raymond Chou', 789000);
INSERT INTO Property
VALUES('2525 Pottsdamer Street', 'Jim Lee', 100500);
INSERT INTO Property
VALUES('193 Love BLVD', 'Kim Abudal', 930000);
INSERT INTO Property
VALUES('647 Maston Road', 'Robert Clue', 135000);
INSERT INTO Property
VALUES('1350 Navada Street', 'Jack Green', 674090);
INSERT INTO Property
VALUES('256 Florida Street', 'Michael Kohen', 179280);
INSERT INTO Property
VALUES('1717 Kansas Street', 'Leah Mars', 345000);
INSERT INTO Property
VALUES('2613 Academic Way', 'Marry Song', 997050);
INSERT INTO Property
VALUES('179 Tinker Road', 'Leon Kant', 90000);
/* 5 records into House */
INSERT INTO House
VALUES('2350 Gibson Road', 'John Smith', 235000, 3, 2, 196);
INSERT INTO House
VALUES('197 Watson Street', 'Raymond Chou', 789000, 2, 4, 203);
INSERT INTO House
VALUES('2525 Pottsdamer Street', 'Jim Lee', 100500, 2, 3, 180);
INSERT INTO House
VALUES('193 Love BLVD', 'Kim Abudal', 930000, 3, 2, 401);
INSERT INTO House
VALUES('647 Maston Road', 'Robert Clue', 135000, 3, 2, 102);
/* 5 records into BusinessProperty */
INSERT INTO BusinessProperty
VALUES('1350 Navada Street', 'Jack Green', 674090, 'office space', 467);
INSERT INTO BusinessProperty
VALUES('256 Florida Street', 'Michael Kohen', 179280, 'gas station', 245);
INSERT INTO BusinessProperty
VALUES('1717 Kansas Street', 'Leah Mars', 345000, 'office space', 356);
INSERT INTO BusinessProperty
VALUES('2613 Academic Way', 'Marry Song', 997050, 'office space', 670);
INSERT INTO BusinessProperty
VALUES('179 Tinker Road', 'Leon Kant', 90000, 'store front', 128);
/* 5 records into Firm */
INSERT INTO Firm
VALUES(135210, 'Goldman Sash', '799 Georgia Way');
INSERT INTO Firm
VALUES(146277, 'Holloway', '124 Texas Street');
INSERT INTO Firm
VALUES(165034, 'Good Target', '135 California Street');
INSERT INTO Firm
VALUES(230754, 'Cozy Home', '277 Beach Road');
INSERT INTO Firm
VALUES(210211, 'Fast Searcher', '1010 Alas Road');
/* 10 records into Agent */
INSERT INTO Agent
VALUES(100, 'Leet Kim', '135145636', 210211, '2012-01-23');
INSERT INTO Agent
VALUES(112, 'Jim Alpha', '171135636', 210211, '2012-03-26');
INSERT INTO Agent
VALUES(123, 'George Grey', '176321636', 135210, '2015-02-23');
INSERT INTO Agent
VALUES(145, 'Sarah Core', '135145909', 135210, '2016-07-03');
INSERT INTO Agent
VALUES(168, 'Livia Watson', '137145638', 146277, '2014-01-17');
INSERT INTO Agent
VALUES(189, 'Nik Ray', '135873630', 146277, '2014-01-28');
INSERT INTO Agent
VALUES(201, 'Cris Paul', '136141236', 165034, '2016-05-23');
INSERT INTO Agent
VALUES(223, 'Lena Clay', '137145123', 165034, '2014-08-19');
INSERT INTO Agent
VALUES(267, 'Kevin Nil', '190145636', 230754, '2011-07-20');
INSERT INTO Agent
VALUES(310, 'Hugh Grant', '132145639', 230754, '2012-12-31');
/* 10 records into Listing */
INSERT INTO Listing
VALUES('2350 Gibson Road', 100, 1212, '2013-02-04');
INSERT INTO Listing
VALUES('197 Watson Street', 112, 1500, '2013-05-06');
INSERT INTO Listing
VALUES('2525 Pottsdamer Street', 123, 1617, '2016-12-04');
INSERT INTO Listing
VALUES('193 Love BLVD', 145, 1718, '2016-02-09');
INSERT INTO Listing
VALUES('647 Maston Road', 168, 1900, '2014-12-19');
INSERT INTO Listing
VALUES('1350 Navada Street', 189, 2101, '2015-06-06');
INSERT INTO Listing
VALUES('256 Florida Street', 201, 2305, '2017-05-25');
INSERT INTO Listing
VALUES('1717 Kansas Street', 223, 2500, '2014-12-04');
INSERT INTO Listing
VALUES('2613 Academic Way', 267, 2790, '2013-10-01');
INSERT INTO Listing
VALUES('179 Tinker Road', 310, 3001, '2015-09-05');
/* 6 records into Buyer */
INSERT INTO Buyer
VALUES(799, 'John Nay', '125345790', 'house', 3, 2, 'not applied', 100000, 635000);
INSERT INTO Buyer
VALUES(801, 'Retina Grey', '146345790', 'house', 3, 2, 'not applied', 100000, 400000);
INSERT INTO Buyer
VALUES(813, 'Reg Neal', '189345791', 'house', 2, 3, 'not applied', 300000, 635000);
INSERT INTO Buyer
VALUES(845, 'Gena Sarah', '789345790', 'house', 3, 2, 'not applied', 200000, 960000);
INSERT INTO Buyer
VALUES(875, 'Bill Clay', '888345798', 'not applied', 0, 0, 'office space', 100000, 900000);
INSERT INTO Buyer
VALUES(999, 'Hilton Clag', '999345792', 'not applied', 0, 0, 'office space', 300000, 790000);
/* 6 records into Works_With */
INSERT INTO Work_With
VALUES(799, 100);
INSERT INTO Work_With
VALUES(801, 145);
INSERT INTO Work_With
VALUES(813, 123);
INSERT INTO Work_With
VALUES(845, 168);
INSERT INTO Work_With
VALUES(875, 189);
INSERT INTO Work_With
VALUES(999, 223);
/* queries */
/* 1st query */
SELECT Listing.address
FROM Listing, House
WHERE Listing.address = House.address;
/* 2nd query */
SELECT Listing.address, Listing.mlsNumber
FROM Listing, House
WHERE Listing.address = House.address;
/* 3rd query */
SELECT Listing.address
FROM Listing, House
WHERE Listing.address = House.address AND House.bedrooms = 3 AND House.bathrooms = 2;
/* 4th query */
SELECT address, price
FROM House
WHERE bedrooms = 3 AND bathrooms = 2 AND price >= 100000 AND price <= 250000
ORDER BY price DESC;
/* 5th query */
SELECT address, price
FROM BusinessProperty
WHERE type = 'office space'
ORDER BY price DESC;
/* 6th query */
SELECT agentId, Agent.name, phone, Firm.name, dateStarted
FROM Agent, Firm
WHERE Agent.firmId = Firm.id;
/* 7th query, agentId is indicated as 201 here */
SELECT Property.*
FROM Property, Listing
WHERE Property.address = Listing.address AND Listing.agentId = 201;
/* 8th query */
SELECT Agent.name AS Agent_Name, Buyer.name AS Buyer_Name
FROM Agent, Buyer, Work_With
WHERE Agent.agentId = Work_With.agentId AND Buyer.id = Work_With.buyerId;
/* 9th query, suppose the buyer's Id is 799 in our case */
SELECT House.*
FROM House, Buyer
WHERE Buyer.id = 799 AND
Buyer.bedrooms = House.bedrooms AND
Buyer.bathrooms = House.bathrooms AND
Buyer.minimumPreferredPrice <= House.price AND
Buyer.maximumPreferredPrice >= House.price;
/* the end of program */

1236
datasets/mega-mart-grocery.sql

File diff suppressed because it is too large Load Diff

381
datasets/monaco-motors-dealership.sql

@ -0,0 +1,381 @@
--
-- Database: `MONACO_MOTORS`
--
CREATE DATABASE IF NOT EXISTS `MONACO_MOTORS` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_uca1400_ai_ci;
USE `MONACO_MOTORS`;
-- --------------------------------------------------------
--
-- Table structure for table `Customer`
--
CREATE TABLE `Customer` (
`CustomerID` char(8) NOT NULL,
`AgentID` char(8) NOT NULL,
`CustFirstName` varchar(15) NOT NULL,
`CustLastName` varchar(15) NOT NULL,
`PhoneNumber` varchar(12) NOT NULL,
`Email` varchar(40) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
--
-- Dumping data for table `Customer`
--
INSERT INTO `Customer` (`CustomerID`, `AgentID`, `CustFirstName`, `CustLastName`, `PhoneNumber`, `Email`) VALUES
('24863197', '89324037', 'Mark', 'Hunt', '3347852143', 'markymark@gmail.com'),
('25463157', '85476932', 'Carly', 'Myers', '7897896325', 'carlyy478@gmail.com'),
('45682178', '85264532', 'John', 'Miller', '3568421479', 'johnboy@hotmail.com'),
('46525896', '32433468', 'Madison', 'Hart', '7892553001', 'lilmaddy@gmail.com'),
('52147932', '78932145', 'Megan', 'Sellers', '3345893321', 'megmeg@hotmail.com'),
('53247962', '85693248', 'Shelly', 'Jones', '4568423698', 'shellyjones@gmail.com'),
('63222478', '45879632', 'Connor', 'Kirk', '3346953214', 'kirkkconnor@yahoo.com'),
('64786233', '89324037', 'Logan', 'Hutchinson', '3345896789', 'loganhutch@yahoo.com'),
('74859612', '45879632', 'Barbara', 'Brown', '3348529654', 'bigbarb400@hotmail.com'),
('78527962', '54279634', 'Andrew', 'Jackson', '3345301438', 'andyjack@gmail.com'),
('78962583', '85693248', 'Morgan', 'Stanley', '4562314862', 'morgstan78@yahoo.com'),
('86321478', '85476932', 'Bill', 'Clark', '7892256541', 'bclrk@hotmail.com'),
('88895214', '74125852', 'William', 'Martin', '6502287512', 'willmart@gmail.com');
-- --------------------------------------------------------
--
-- Table structure for table `Deal`
--
CREATE TABLE `Deal` (
`DealID` char(5) NOT NULL,
`VehicleID` char(3) NOT NULL,
`AgentID` char(8) NOT NULL,
`CustomerID` char(8) NOT NULL,
`InsuranceID` char(5) DEFAULT NULL,
`DealDate` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
--
-- Dumping data for table `Deal`
--
INSERT INTO `Deal` (`DealID`, `VehicleID`, `AgentID`, `CustomerID`, `InsuranceID`, `DealDate`) VALUES
('21115', '123', '32433468', '46525896', '78222', '2023-03-27'),
('25839', '328', '78932145', '52147932', '21444', '2024-04-18'),
('33658', '216', '74125852', '88895214', '26687', '2023-04-24'),
('45523', '377', '45879632', '63222478', '11478', '2023-04-01'),
('48624', '486', '54279634', '78527962', NULL, '2023-11-08'),
('48876', '729', '85693248', '53247962', NULL, '2024-04-16'),
('55896', '554', '45879632', '74859612', '44589', '2024-02-01'),
('58221', '456', '85264532', '45682178', '22268', '2023-02-11'),
('77885', '416', '85476932', '86321478', NULL, '2024-02-21'),
('95632', '265', '89324037', '24863197', '56482', '2023-01-17');
-- --------------------------------------------------------
--
-- Table structure for table `Dealership`
--
CREATE TABLE `Dealership` (
`DealershipID` char(5) NOT NULL,
`DistributorID` char(8) NOT NULL,
`RegionID` char(3) NOT NULL,
`RegionZIP` char(5) NOT NULL,
`DealershipName` varchar(40) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
--
-- Dumping data for table `Dealership`
--
INSERT INTO `Dealership` (`DealershipID`, `DistributorID`, `RegionID`, `RegionZIP`, `DealershipName`) VALUES
('32569', '45632479', '578', '58203', 'Winged Lion Motors'),
('47823', '12347896', '334', '36081', 'Scuderia Speed'),
('59823', '45324895', '578', '58203', 'Velocity Auto Haus'),
('78962', '36589217', '334', '36081', 'Tridente Motors'),
('85632', '36521789', '356', '36079', 'Galleria Motors'),
('96523', '25863217', '356', '36079', 'Royal Stallion Motors');
-- --------------------------------------------------------
--
-- Table structure for table `Distributor`
--
CREATE TABLE `Distributor` (
`DistributorID` char(8) NOT NULL,
`DistributorName` varchar(40) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
--
-- Dumping data for table `Distributor`
--
INSERT INTO `Distributor` (`DistributorID`, `DistributorName`) VALUES
('12347896', 'Pfaff Reserve'),
('25863217', 'EuroCar'),
('36521789', 'Redline European'),
('36589217', 'Romans International'),
('45324895', 'European Exotic Center'),
('45632479', 'James Edition');
-- --------------------------------------------------------
--
-- Table structure for table `Insurance`
--
CREATE TABLE `Insurance` (
`InsuranceID` char(5) NOT NULL,
`PolicyType` varchar(15) NOT NULL,
`RenewalDate` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
--
-- Dumping data for table `Insurance`
--
INSERT INTO `Insurance` (`InsuranceID`, `PolicyType`, `RenewalDate`) VALUES
('11478', 'Full Coverage', '2024-04-01'),
('21444', 'Full Coverage', '2020-04-18'),
('22268', 'Liability', '2024-02-11'),
('26687', 'Liability', '2024-04-24'),
('44589', 'Full Coverage', '2020-02-01'),
('56482', 'Full Coverage', '2024-01-17'),
('78222', 'Full Coverage', '2024-03-27');
-- --------------------------------------------------------
--
-- Table structure for table `Manager`
--
CREATE TABLE `Manager` (
`ManagerID` char(8) NOT NULL,
`DealershipID` char(5) NOT NULL,
`DistributorID` char(8) NOT NULL,
`MngrFirstName` varchar(15) NOT NULL,
`MngrLastName` varchar(15) NOT NULL,
`MngrSalary` decimal(8,2) NOT NULL,
`MngrBonus` decimal(8,2) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
--
-- Dumping data for table `Manager`
--
INSERT INTO `Manager` (`ManagerID`, `DealershipID`, `DistributorID`, `MngrFirstName`, `MngrLastName`, `MngrSalary`, `MngrBonus`) VALUES
('12345678', '59823', '45324895', 'John', 'Boling', 87900.00, 5100.23),
('14458973', '96523', '25863217', 'Henry', 'Miller', 79025.99, 5200.60),
('32556978', '78962', '36589217', 'Rachel', 'Smith', 81500.10, 2400.00),
('45896324', '32569', '45632479', 'Sally', 'Mae', 75000.99, 4250.50),
('52689974', '85632', '36521789', 'Lamar', 'Jackson', 91250.10, NULL),
('58894123', '47823', '12347896', 'Kevin', 'Rogers', 71250.00, 8450.00);
-- --------------------------------------------------------
--
-- Table structure for table `Region`
--
CREATE TABLE `Region` (
`RegionID` char(3) NOT NULL,
`RegionZIP` char(5) NOT NULL,
`RegionName` varchar(15) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
--
-- Dumping data for table `Region`
--
INSERT INTO `Region` (`RegionID`, `RegionZIP`, `RegionName`) VALUES
('334', '36081', 'EMEA'),
('356', '36079', 'APJ'),
('578', '58203', 'AMS');
-- --------------------------------------------------------
--
-- Table structure for table `Sales_Agent`
--
CREATE TABLE `Sales_Agent` (
`AgentID` char(8) NOT NULL,
`ManagerID` char(8) NOT NULL,
`DealershipID` char(5) NOT NULL,
`AgentFirstName` varchar(15) NOT NULL,
`AgentLastName` varchar(15) NOT NULL,
`AgentSalary` decimal(9,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
--
-- Dumping data for table `Sales_Agent`
--
INSERT INTO `Sales_Agent` (`AgentID`, `ManagerID`, `DealershipID`, `AgentFirstName`, `AgentLastName`, `AgentSalary`) VALUES
('28547962', '52689974', '85632', 'Jack', 'Hublot', 61258.00),
('32433468', '52689974', '85632', 'Jennifer', 'Martin', 57950.99),
('45698234', '12345678', '59823', 'Jordan', 'Myers', 43450.00),
('45879632', '32556978', '78962', 'Stacy', 'Diaz', 47600.50),
('54279634', '32556978', '78962', 'Marshall', 'Reese', 57180.00),
('74125852', '58894123', '47823', 'Allison', 'Garner', 54800.00),
('78932145', '14458973', '96523', 'Jasper', 'Sparks', 48650.99),
('79621463', '45896324', '32569', 'Hubert', 'Davis', 52081.32),
('85264532', '58894123', '47823', 'Paul', 'Werner', 51850.50),
('85476932', '14458973', '96523', 'Mitchell', 'Fields', 42600.00),
('85693248', '12345678', '59823', 'Alex', 'Smith', 47520.59),
('89324037', '45896324', '32569', 'Benjamin', 'Gonzales', 49250.90);
-- --------------------------------------------------------
--
-- Table structure for table `Vehicle`
--
CREATE TABLE `Vehicle` (
`VehicleID` char(3) NOT NULL,
`DealershipID` char(5) NOT NULL,
`DistributorID` char(8) NOT NULL,
`Make` varchar(40) NOT NULL,
`Model` varchar(40) NOT NULL,
`BodyType` varchar(40) NOT NULL,
`ModelYear` int(11) NOT NULL,
`Price` decimal(9,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
--
-- Dumping data for table `Vehicle`
--
INSERT INTO `Vehicle` (`VehicleID`, `DealershipID`, `DistributorID`, `Make`, `Model`, `BodyType`, `ModelYear`, `Price`) VALUES
('123', '85632', '36521789', 'Lamborghini', 'Aventador', 'Coupe', 2024, 421145.00),
('216', '47823', '12347896', 'Ferrari', 'Roma', 'Coupe', 2024, 220340.00),
('265', '32569', '45632479', 'Pagani', 'Huayra BC', 'Coupe', 2024, 2800000.00),
('328', '96523', '25863217', 'Bugatti', 'Chiron Super Sport 300+', 'Coupe', 2024, 5790000.00),
('349', '85632', '36521789', 'Lamborghini', 'Huracan STO', 'Coupe', 2024, 327835.00),
('377', '78962', '36589217', 'Maserati', 'MC20 Cielo', 'Spyder', 2024, 281000.00),
('416', '96523', '25863217', 'Rolls-Royce', 'Cullinan Black Badge', 'SUV', 2024, 388000.00),
('456', '47823', '12347896', 'Ferrari', 'SF90 Stradale', 'Coupe', 2024, 516000.00),
('486', '78962', '36589217', 'McLaren', 'Artura', 'Coupe', 2024, 185500.00),
('532', '59823', '45324895', 'Aston Martin', 'DBS', 'Coupe', 2024, 336000.00),
('554', '78962', '36589217', 'McLaren', 'GT', 'Coupe', 2024, 210000.00),
('729', '59823', '45324895', 'Bentley', 'Continental GT Speed', 'Coupe', 2024, 335000.00);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `Customer`
--
ALTER TABLE `Customer`
ADD PRIMARY KEY (`CustomerID`),
ADD KEY `AgentID` (`AgentID`);
--
-- Indexes for table `Deal`
--
ALTER TABLE `Deal`
ADD PRIMARY KEY (`DealID`),
ADD KEY `VehicleID` (`VehicleID`),
ADD KEY `AgentID` (`AgentID`),
ADD KEY `CustomerID` (`CustomerID`),
ADD KEY `InsuranceID` (`InsuranceID`);
--
-- Indexes for table `Dealership`
--
ALTER TABLE `Dealership`
ADD PRIMARY KEY (`DealershipID`),
ADD KEY `DistributorID` (`DistributorID`),
ADD KEY `RegionID` (`RegionID`,`RegionZIP`);
--
-- Indexes for table `Distributor`
--
ALTER TABLE `Distributor`
ADD PRIMARY KEY (`DistributorID`);
--
-- Indexes for table `Insurance`
--
ALTER TABLE `Insurance`
ADD PRIMARY KEY (`InsuranceID`);
--
-- Indexes for table `Manager`
--
ALTER TABLE `Manager`
ADD PRIMARY KEY (`ManagerID`),
ADD KEY `DealershipID` (`DealershipID`),
ADD KEY `DistributorID` (`DistributorID`);
--
-- Indexes for table `Region`
--
ALTER TABLE `Region`
ADD PRIMARY KEY (`RegionID`,`RegionZIP`);
--
-- Indexes for table `Sales_Agent`
--
ALTER TABLE `Sales_Agent`
ADD PRIMARY KEY (`AgentID`),
ADD KEY `ManagerID` (`ManagerID`),
ADD KEY `DealershipID` (`DealershipID`);
--
-- Indexes for table `Vehicle`
--
ALTER TABLE `Vehicle`
ADD PRIMARY KEY (`VehicleID`),
ADD KEY `DealershipID` (`DealershipID`),
ADD KEY `DistributorID` (`DistributorID`);
--
-- Constraints for dumped tables
--
--
-- Constraints for table `Customer`
--
ALTER TABLE `Customer`
ADD CONSTRAINT `Customer_ibfk_1` FOREIGN KEY (`AgentID`) REFERENCES `Sales_Agent` (`AgentID`);
--
-- Constraints for table `Deal`
--
ALTER TABLE `Deal`
ADD CONSTRAINT `Deal_ibfk_1` FOREIGN KEY (`VehicleID`) REFERENCES `Vehicle` (`VehicleID`),
ADD CONSTRAINT `Deal_ibfk_2` FOREIGN KEY (`AgentID`) REFERENCES `Sales_Agent` (`AgentID`),
ADD CONSTRAINT `Deal_ibfk_3` FOREIGN KEY (`CustomerID`) REFERENCES `Customer` (`CustomerID`),
ADD CONSTRAINT `Deal_ibfk_4` FOREIGN KEY (`InsuranceID`) REFERENCES `Insurance` (`InsuranceID`);
--
-- Constraints for table `Dealership`
--
ALTER TABLE `Dealership`
ADD CONSTRAINT `Dealership_ibfk_1` FOREIGN KEY (`DistributorID`) REFERENCES `Distributor` (`DistributorID`),
ADD CONSTRAINT `Dealership_ibfk_2` FOREIGN KEY (`RegionID`,`RegionZIP`) REFERENCES `Region` (`RegionID`, `RegionZIP`);
--
-- Constraints for table `Manager`
--
ALTER TABLE `Manager`
ADD CONSTRAINT `Manager_ibfk_1` FOREIGN KEY (`DealershipID`) REFERENCES `Dealership` (`DealershipID`),
ADD CONSTRAINT `Manager_ibfk_2` FOREIGN KEY (`DistributorID`) REFERENCES `Distributor` (`DistributorID`);
--
-- Constraints for table `Sales_Agent`
--
ALTER TABLE `Sales_Agent`
ADD CONSTRAINT `Sales_Agent_ibfk_1` FOREIGN KEY (`ManagerID`) REFERENCES `Manager` (`ManagerID`),
ADD CONSTRAINT `Sales_Agent_ibfk_2` FOREIGN KEY (`DealershipID`) REFERENCES `Dealership` (`DealershipID`);
--
-- Constraints for table `Vehicle`
--
ALTER TABLE `Vehicle`
ADD CONSTRAINT `Vehicle_ibfk_1` FOREIGN KEY (`DealershipID`) REFERENCES `Dealership` (`DealershipID`),
ADD CONSTRAINT `Vehicle_ibfk_2` FOREIGN KEY (`DistributorID`) REFERENCES `Distributor` (`DistributorID`);

4
datasets/user-readonly-create.sql

@ -0,0 +1,4 @@
CREATE USER 'readonly'@'%' IDENTIFIED BY 'readonly';
GRANT SELECT, SHOW VIEW ON *.* TO 'readonly'@'%' REQUIRE NONE WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;

4
datasets/user-shinobi-create.sql

@ -0,0 +1,4 @@
CREATE USER 'shinobi'@'%' IDENTIFIED BY 'shinobi';
GRANT SELECT ON MONACO_MOTORS.* TO 'shinobi'@'%' IDENTIFIED BY 'shinobi';

15
docs/Dockerfile

@ -0,0 +1,15 @@
FROM titom73/mkdocs AS MKDOCS_BUILD
RUN pip install markupsafe==2.0.1
RUN pip install mkdocs-blog-plugin
WORKDIR /docs
COPY . .
RUN mkdocs build
FROM mengzyou/bbhttpd:1.35
COPY --from=MKDOCS_BUILD --chown=www:www /docs/site /home/www/html

19
docs/compose.bash

@ -0,0 +1,19 @@
#!/bin/bash
##
reset;
clear;
##
set -e;
set -x;
##
docker compose down --remove-orphans
docker compose up --build -d

18
docs/compose.yaml

@ -0,0 +1,18 @@
services:
shinobi-academy-database-docs:
container_name: shinobi-academy-database-docs
image: softwareshinobi/shinobi-academy-database-docs
build:
context: .
dockerfile: Dockerfile
ports:
- 8080:80

419
docs/docs/.recycle/.gemini.md

@ -0,0 +1,419 @@
## Monaco Motors Schema
The schema defines the structure of the database, including tables, columns, data types, and relationships between tables. Here's a breakdown of the tables and their relationships:
* **Customer:** Primary table for customer information. It has a foreign key referencing the Sales_Agent table (AgentID).
* **Deal:** Stores information about vehicle sales. It has foreign keys referencing Customer, Sales_Agent, Vehicle, and Insurance tables (CustomerID, AgentID, VehicleID, InsuranceID).
* **Dealership:** Information about dealerships. It has foreign keys referencing Distributor and Region tables (DistributorID, RegionID, RegionZIP).
* **Distributor:** Information about car distributors.
* **Insurance:** Details about insurance policies offered.
* **Manager:** Information about dealership managers. It has foreign keys referencing
Dealership and Distributor tables (DealershipID, DistributorID).
* **Region:** Geographic regions where dealerships are located. It's a composite primary key with RegionID and RegionZIP.
* **Sales_Agent:** Information about sales agents employed by dealerships. It has foreign keys referencing Manager and Dealership tables (ManagerID, DealershipID).
* **Vehicle:** Information about vehicles in the dealership's inventory. It has foreign keys referencing Dealership and Distributor tables (DealershipID, DistributorID).
# gemini
server / databases.softwareshinobi.digital
user / shinobi
user / shinobi
schema / monaco-motors-dealership
--
-- Database: `MONACO_MOTORS`
--
CREATE DATABASE IF NOT EXISTS `MONACO_MOTORS` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_uca1400_ai_ci;
USE `MONACO_MOTORS`;
-- --------------------------------------------------------
--
-- Table structure for table `Customer`
--
CREATE TABLE `Customer` (
`CustomerID` char(8) NOT NULL,
`AgentID` char(8) NOT NULL,
`CustFirstName` varchar(15) NOT NULL,
`CustLastName` varchar(15) NOT NULL,
`PhoneNumber` varchar(12) NOT NULL,
`Email` varchar(40) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
--
-- Dumping data for table `Customer`
--
INSERT INTO `Customer` (`CustomerID`, `AgentID`, `CustFirstName`, `CustLastName`, `PhoneNumber`, `Email`) VALUES
('24863197', '89324037', 'Mark', 'Hunt', '3347852143', 'markymark@gmail.com'),
('25463157', '85476932', 'Carly', 'Myers', '7897896325', 'carlyy478@gmail.com'),
('45682178', '85264532', 'John', 'Miller', '3568421479', 'johnboy@hotmail.com'),
('46525896', '32433468', 'Madison', 'Hart', '7892553001', 'lilmaddy@gmail.com'),
('52147932', '78932145', 'Megan', 'Sellers', '3345893321', 'megmeg@hotmail.com'),
('53247962', '85693248', 'Shelly', 'Jones', '4568423698', 'shellyjones@gmail.com'),
('63222478', '45879632', 'Connor', 'Kirk', '3346953214', 'kirkkconnor@yahoo.com'),
('64786233', '89324037', 'Logan', 'Hutchinson', '3345896789', 'loganhutch@yahoo.com'),
('74859612', '45879632', 'Barbara', 'Brown', '3348529654', 'bigbarb400@hotmail.com'),
('78527962', '54279634', 'Andrew', 'Jackson', '3345301438', 'andyjack@gmail.com'),
('78962583', '85693248', 'Morgan', 'Stanley', '4562314862', 'morgstan78@yahoo.com'),
('86321478', '85476932', 'Bill', 'Clark', '7892256541', 'bclrk@hotmail.com'),
('88895214', '74125852', 'William', 'Martin', '6502287512', 'willmart@gmail.com');
-- --------------------------------------------------------
--
-- Table structure for table `Deal`
--
CREATE TABLE `Deal` (
`DealID` char(5) NOT NULL,
`VehicleID` char(3) NOT NULL,
`AgentID` char(8) NOT NULL,
`CustomerID` char(8) NOT NULL,
`InsuranceID` char(5) DEFAULT NULL,
`DealDate` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
--
-- Dumping data for table `Deal`
--
INSERT INTO `Deal` (`DealID`, `VehicleID`, `AgentID`, `CustomerID`, `InsuranceID`, `DealDate`) VALUES
('21115', '123', '32433468', '46525896', '78222', '2023-03-27'),
('25839', '328', '78932145', '52147932', '21444', '2024-04-18'),
('33658', '216', '74125852', '88895214', '26687', '2023-04-24'),
('45523', '377', '45879632', '63222478', '11478', '2023-04-01'),
('48624', '486', '54279634', '78527962', NULL, '2023-11-08'),
('48876', '729', '85693248', '53247962', NULL, '2024-04-16'),
('55896', '554', '45879632', '74859612', '44589', '2024-02-01'),
('58221', '456', '85264532', '45682178', '22268', '2023-02-11'),
('77885', '416', '85476932', '86321478', NULL, '2024-02-21'),
('95632', '265', '89324037', '24863197', '56482', '2023-01-17');
-- --------------------------------------------------------
--
-- Table structure for table `Dealership`
--
CREATE TABLE `Dealership` (
`DealershipID` char(5) NOT NULL,
`DistributorID` char(8) NOT NULL,
`RegionID` char(3) NOT NULL,
`RegionZIP` char(5) NOT NULL,
`DealershipName` varchar(40) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
--
-- Dumping data for table `Dealership`
--
INSERT INTO `Dealership` (`DealershipID`, `DistributorID`, `RegionID`, `RegionZIP`, `DealershipName`) VALUES
('32569', '45632479', '578', '58203', 'Winged Lion Motors'),
('47823', '12347896', '334', '36081', 'Scuderia Speed'),
('59823', '45324895', '578', '58203', 'Velocity Auto Haus'),
('78962', '36589217', '334', '36081', 'Tridente Motors'),
('85632', '36521789', '356', '36079', 'Galleria Motors'),
('96523', '25863217', '356', '36079', 'Royal Stallion Motors');
-- --------------------------------------------------------
--
-- Table structure for table `Distributor`
--
CREATE TABLE `Distributor` (
`DistributorID` char(8) NOT NULL,
`DistributorName` varchar(40) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
--
-- Dumping data for table `Distributor`
--
INSERT INTO `Distributor` (`DistributorID`, `DistributorName`) VALUES
('12347896', 'Pfaff Reserve'),
('25863217', 'EuroCar'),
('36521789', 'Redline European'),
('36589217', 'Romans International'),
('45324895', 'European Exotic Center'),
('45632479', 'James Edition');
-- --------------------------------------------------------
--
-- Table structure for table `Insurance`
--
CREATE TABLE `Insurance` (
`InsuranceID` char(5) NOT NULL,
`PolicyType` varchar(15) NOT NULL,
`RenewalDate` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
--
-- Dumping data for table `Insurance`
--
INSERT INTO `Insurance` (`InsuranceID`, `PolicyType`, `RenewalDate`) VALUES
('11478', 'Full Coverage', '2024-04-01'),
('21444', 'Full Coverage', '2020-04-18'),
('22268', 'Liability', '2024-02-11'),
('26687', 'Liability', '2024-04-24'),
('44589', 'Full Coverage', '2020-02-01'),
('56482', 'Full Coverage', '2024-01-17'),
('78222', 'Full Coverage', '2024-03-27');
-- --------------------------------------------------------
--
-- Table structure for table `Manager`
--
CREATE TABLE `Manager` (
`ManagerID` char(8) NOT NULL,
`DealershipID` char(5) NOT NULL,
`DistributorID` char(8) NOT NULL,
`MngrFirstName` varchar(15) NOT NULL,
`MngrLastName` varchar(15) NOT NULL,
`MngrSalary` decimal(8,2) NOT NULL,
`MngrBonus` decimal(8,2) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
--
-- Dumping data for table `Manager`
--
INSERT INTO `Manager` (`ManagerID`, `DealershipID`, `DistributorID`, `MngrFirstName`, `MngrLastName`, `MngrSalary`, `MngrBonus`) VALUES
('12345678', '59823', '45324895', 'John', 'Boling', 87900.00, 5100.23),
('14458973', '96523', '25863217', 'Henry', 'Miller', 79025.99, 5200.60),
('32556978', '78962', '36589217', 'Rachel', 'Smith', 81500.10, 2400.00),
('45896324', '32569', '45632479', 'Sally', 'Mae', 75000.99, 4250.50),
('52689974', '85632', '36521789', 'Lamar', 'Jackson', 91250.10, NULL),
('58894123', '47823', '12347896', 'Kevin', 'Rogers', 71250.00, 8450.00);
-- --------------------------------------------------------
--
-- Table structure for table `Region`
--
CREATE TABLE `Region` (
`RegionID` char(3) NOT NULL,
`RegionZIP` char(5) NOT NULL,
`RegionName` varchar(15) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
--
-- Dumping data for table `Region`
--
INSERT INTO `Region` (`RegionID`, `RegionZIP`, `RegionName`) VALUES
('334', '36081', 'EMEA'),
('356', '36079', 'APJ'),
('578', '58203', 'AMS');
-- --------------------------------------------------------
--
-- Table structure for table `Sales_Agent`
--
CREATE TABLE `Sales_Agent` (
`AgentID` char(8) NOT NULL,
`ManagerID` char(8) NOT NULL,
`DealershipID` char(5) NOT NULL,
`AgentFirstName` varchar(15) NOT NULL,
`AgentLastName` varchar(15) NOT NULL,
`AgentSalary` decimal(9,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
--
-- Dumping data for table `Sales_Agent`
--
INSERT INTO `Sales_Agent` (`AgentID`, `ManagerID`, `DealershipID`, `AgentFirstName`, `AgentLastName`, `AgentSalary`) VALUES
('28547962', '52689974', '85632', 'Jack', 'Hublot', 61258.00),
('32433468', '52689974', '85632', 'Jennifer', 'Martin', 57950.99),
('45698234', '12345678', '59823', 'Jordan', 'Myers', 43450.00),
('45879632', '32556978', '78962', 'Stacy', 'Diaz', 47600.50),
('54279634', '32556978', '78962', 'Marshall', 'Reese', 57180.00),
('74125852', '58894123', '47823', 'Allison', 'Garner', 54800.00),
('78932145', '14458973', '96523', 'Jasper', 'Sparks', 48650.99),
('79621463', '45896324', '32569', 'Hubert', 'Davis', 52081.32),
('85264532', '58894123', '47823', 'Paul', 'Werner', 51850.50),
('85476932', '14458973', '96523', 'Mitchell', 'Fields', 42600.00),
('85693248', '12345678', '59823', 'Alex', 'Smith', 47520.59),
('89324037', '45896324', '32569', 'Benjamin', 'Gonzales', 49250.90);
-- --------------------------------------------------------
--
-- Table structure for table `Vehicle`
--
CREATE TABLE `Vehicle` (
`VehicleID` char(3) NOT NULL,
`DealershipID` char(5) NOT NULL,
`DistributorID` char(8) NOT NULL,
`Make` varchar(40) NOT NULL,
`Model` varchar(40) NOT NULL,
`BodyType` varchar(40) NOT NULL,
`ModelYear` int(11) NOT NULL,
`Price` decimal(9,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
--
-- Dumping data for table `Vehicle`
--
INSERT INTO `Vehicle` (`VehicleID`, `DealershipID`, `DistributorID`, `Make`, `Model`, `BodyType`, `ModelYear`, `Price`) VALUES
('123', '85632', '36521789', 'Lamborghini', 'Aventador', 'Coupe', 2024, 421145.00),
('216', '47823', '12347896', 'Ferrari', 'Roma', 'Coupe', 2024, 220340.00),
('265', '32569', '45632479', 'Pagani', 'Huayra BC', 'Coupe', 2024, 2800000.00),
('328', '96523', '25863217', 'Bugatti', 'Chiron Super Sport 300+', 'Coupe', 2024, 5790000.00),
('349', '85632', '36521789', 'Lamborghini', 'Huracan STO', 'Coupe', 2024, 327835.00),
('377', '78962', '36589217', 'Maserati', 'MC20 Cielo', 'Spyder', 2024, 281000.00),
('416', '96523', '25863217', 'Rolls-Royce', 'Cullinan Black Badge', 'SUV', 2024, 388000.00),
('456', '47823', '12347896', 'Ferrari', 'SF90 Stradale', 'Coupe', 2024, 516000.00),
('486', '78962', '36589217', 'McLaren', 'Artura', 'Coupe', 2024, 185500.00),
('532', '59823', '45324895', 'Aston Martin', 'DBS', 'Coupe', 2024, 336000.00),
('554', '78962', '36589217', 'McLaren', 'GT', 'Coupe', 2024, 210000.00),
('729', '59823', '45324895', 'Bentley', 'Continental GT Speed', 'Coupe', 2024, 335000.00);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `Customer`
--
ALTER TABLE `Customer`
ADD PRIMARY KEY (`CustomerID`),
ADD KEY `AgentID` (`AgentID`);
--
-- Indexes for table `Deal`
--
ALTER TABLE `Deal`
ADD PRIMARY KEY (`DealID`),
ADD KEY `VehicleID` (`VehicleID`),
ADD KEY `AgentID` (`AgentID`),
ADD KEY `CustomerID` (`CustomerID`),
ADD KEY `InsuranceID` (`InsuranceID`);
--
-- Indexes for table `Dealership`
--
ALTER TABLE `Dealership`
ADD PRIMARY KEY (`DealershipID`),
ADD KEY `DistributorID` (`DistributorID`),
ADD KEY `RegionID` (`RegionID`,`RegionZIP`);
--
-- Indexes for table `Distributor`
--
ALTER TABLE `Distributor`
ADD PRIMARY KEY (`DistributorID`);
--
-- Indexes for table `Insurance`
--
ALTER TABLE `Insurance`
ADD PRIMARY KEY (`InsuranceID`);
--
-- Indexes for table `Manager`
--
ALTER TABLE `Manager`
ADD PRIMARY KEY (`ManagerID`),
ADD KEY `DealershipID` (`DealershipID`),
ADD KEY `DistributorID` (`DistributorID`);
--
-- Indexes for table `Region`
--
ALTER TABLE `Region`
ADD PRIMARY KEY (`RegionID`,`RegionZIP`);
--
-- Indexes for table `Sales_Agent`
--
ALTER TABLE `Sales_Agent`
ADD PRIMARY KEY (`AgentID`),
ADD KEY `ManagerID` (`ManagerID`),
ADD KEY `DealershipID` (`DealershipID`);
--
-- Indexes for table `Vehicle`
--
ALTER TABLE `Vehicle`
ADD PRIMARY KEY (`VehicleID`),
ADD KEY `DealershipID` (`DealershipID`),
ADD KEY `DistributorID` (`DistributorID`);
--
-- Constraints for dumped tables
--
--
-- Constraints for table `Customer`
--
ALTER TABLE `Customer`
ADD CONSTRAINT `Customer_ibfk_1` FOREIGN KEY (`AgentID`) REFERENCES `Sales_Agent` (`AgentID`);
--
-- Constraints for table `Deal`
--
ALTER TABLE `Deal`
ADD CONSTRAINT `Deal_ibfk_1` FOREIGN KEY (`VehicleID`) REFERENCES `Vehicle` (`VehicleID`),
ADD CONSTRAINT `Deal_ibfk_2` FOREIGN KEY (`AgentID`) REFERENCES `Sales_Agent` (`AgentID`),
ADD CONSTRAINT `Deal_ibfk_3` FOREIGN KEY (`CustomerID`) REFERENCES `Customer` (`CustomerID`),
ADD CONSTRAINT `Deal_ibfk_4` FOREIGN KEY (`InsuranceID`) REFERENCES `Insurance` (`InsuranceID`);
--
-- Constraints for table `Dealership`
--
ALTER TABLE `Dealership`
ADD CONSTRAINT `Dealership_ibfk_1` FOREIGN KEY (`DistributorID`) REFERENCES `Distributor` (`DistributorID`),
ADD CONSTRAINT `Dealership_ibfk_2` FOREIGN KEY (`RegionID`,`RegionZIP`) REFERENCES `Region` (`RegionID`, `RegionZIP`);
--
-- Constraints for table `Manager`
--
ALTER TABLE `Manager`
ADD CONSTRAINT `Manager_ibfk_1` FOREIGN KEY (`DealershipID`) REFERENCES `Dealership` (`DealershipID`),
ADD CONSTRAINT `Manager_ibfk_2` FOREIGN KEY (`DistributorID`) REFERENCES `Distributor` (`DistributorID`);
--
-- Constraints for table `Sales_Agent`
--
ALTER TABLE `Sales_Agent`
ADD CONSTRAINT `Sales_Agent_ibfk_1` FOREIGN KEY (`ManagerID`) REFERENCES `Manager` (`ManagerID`),
ADD CONSTRAINT `Sales_Agent_ibfk_2` FOREIGN KEY (`DealershipID`) REFERENCES `Dealership` (`DealershipID`);
--
-- Constraints for table `Vehicle`
--
ALTER TABLE `Vehicle`
ADD CONSTRAINT `Vehicle_ibfk_1` FOREIGN KEY (`DealershipID`) REFERENCES `Dealership` (`DealershipID`),
ADD CONSTRAINT `Vehicle_ibfk_2` FOREIGN KEY (`DistributorID`) REFERENCES `Distributor` (`DistributorID`);
this is a public mariadb database. practice your SQL skills and data analysis skills on my data. explain the database. and the schema. and the data tht th students. explain how to connect using your favorite browser.

40
docs/docs/.recycle/sql-101.md

@ -0,0 +1,40 @@
# SQL 101
**Dive into the World of Exotic Cars: A Data Analyst's Playground**
**Unleash the Power of SQL**
Imagine having a database filled with data on high-end luxury cars, from sleek sports cars to opulent SUVs. This Monaco Motors Dealership database is your playground to practice SQL queries and data analysis techniques.
**What Can You Do with This Data?**
As a budding data analyst, you can:
* **Extract Insights:** Use SQL to query the database and extract valuable insights. For example, you could identify the top-selling car models, analyze customer demographics, or track sales trends over time.
* **Build Data Models:** Create data models to represent the relationships between different entities in the database. This will help you visualize the data and understand its structure.
* **Data Visualization:** Use data visualization tools like Tableau or Power BI to create stunning charts and graphs that bring your data to life. You could visualize sales figures, customer preferences, or inventory levels.
* **Predictive Analytics:** Explore predictive modeling techniques to forecast future sales, identify potential customers, or optimize inventory management.
**Practical SQL Examples:**
Here are some practical SQL queries to get you started:
* **Find all Ferrari models:**
```sql
SELECT * FROM Vehicle WHERE Make = 'Ferrari';
```
* **Calculate the average price of Lamborghini cars:**
```sql
SELECT AVG(Price) FROM Vehicle WHERE Make = 'Lamborghini';
```
* **Identify the top 5 best-selling car models:**
```sql
SELECT TOP 5 VehicleID, COUNT(*) AS SalesCount
FROM Deal
GROUP BY VehicleID
ORDER BY SalesCount DESC;
```
**Start Your Data Analysis Journey Today**
By working with this real-world dataset, you can develop your SQL skills, learn data analysis techniques, and gain valuable experience. So, dive into the data and unlock the secrets of the Monaco Motors Dealership!

145
docs/docs/Introduction-To-Databases/004-basic-syntax.md

@ -0,0 +1,145 @@
# Basic Syntax
In this chapter, we will go over the basic SQL syntax.
SQL statements are basically the 'commands' that you run against a specific database. Through the SQL statements, you are telling MySQL what you want it to do, for example, if you wanted to get the `username` of all of your users stored in the `users` table, you would run the following SQL statement:
```sql
SELECT username FROM users;
```
Rundown of the statement:
* `SELECT`: First, we specify the `SELECT` keyword, which indicates that we want to select some data from the database. Other popular keywords are: `INSERT`, `UPDATE` and `DELETE`.
* `username`: Then we specify which column we want to select.
* `FROM users`: After that, we specify the table that we want to select the data from using the `FROM` keyword.
* The semicolon `;` is highly recommended to put at the end. Standard SQL syntax requires it, but some "Database Management Systems' (DBMS)" are tolerant about it, but it's not worth the risk.
If you run the above statement, you will get no results as the new `users` table that we've just created is empty.
> As a good practice, all SQL keywords should be with uppercase, however, it would work just fine if you use lower case as well.
Let's go ahead and cover the basic operations next.
## INSERT
To add data to your database, you would use the `INSERT` statement.
Let's use the table that we created in the last chapter and insert 1 user into our `users` table:
```sql
INSERT INTO users (username, email, active)
VALUES ('bobby', 'bobby@bobbyiliev.com', true);
```
Rundown of the insert statement:
* `INSERT INTO`: first, we specify the `INSERT INTO` keyword, which tells MySQL that we want to insert data a table.
* `users (username, email, active)`: then, we specify the table name `users` and the columns that we want to insert data into.
* `VALUES`: then, we specify the values that we want to insert in. The order of attributes is the same as in `users (...)`.
## SELECT
Once we've inserted that user, let's go ahead and retrieve the information.
To retrieve information from your database, you could use the `SELECT` statement:
```sql
SELECT * FROM users;
```
Output:
```
+----+----------+-------+----------+--------+---------------+
| id | username | about | birthday | active | email |
+----+----------+-------+----------+--------+---------------+
| 1 | bobby | NULL | NULL | 1 | bobby@b...com |
+----+----------+-------+----------+--------+---------------+
```
We specify `*` right after the `SELECT` keyword, this means that we want to get all of the columns from the `users` table.
If we wanted to retrieve only the `username` and the `email` columns instead, we would change the statement to:
```sql
SELECT username, email FROM users;
```
This will return all of the users, but as of the time being we have only 1:
```
+----------+----------------------+
| username | email |
+----------+----------------------+
| bobby | bobby@bobbyiliev.com |
+----------+----------------------+
```
## UPDATE
In order to modify data in your database, you could use the `UPDATE` statement.
The syntax would look like this:
```sql
UPDATE users SET username='bobbyiliev' WHERE id=1;
```
Rundown of the statement:
* `UPDATE users`: First, we specify the `UPDATE` keyword followed by the table that we want to update.
* `SET username='bobbyiliev'`: Then we specify the columns that we want to update and the new value that we want to set.
* `WHERE id=1`: Finally, by using the `WHERE` clause, we specify which user should be updated. In our case it is the user with ID 1.
> NOTE: If we don't specify a `WHERE` clause, all of the entries inside the `users` table would be updated, and all users would have the `username` set to `bobbyiliev`. You need to be careful when you use the `UPDATE` statement without a `WHERE` clause, as every single row will be updated.
We are going to cover `WHERE` more in-depth in the next few chapters.
## DELETE
As the name suggests, the `DELETE` statement would remove data from your database.
The syntax is as follows:
```sql
DELETE FROM users WHERE id=1;
```
Similar to the `UPDATE` statement, if you don't specify a `WHERE` clause, all of the entries from the table will be affected, meaning that all of your users will be deleted.
## Comments
In case that you are writing a larger SQL script, it might be helpful to add some comments so that later on, when you come back to the script, you would know what each line does.
As with all programming languages, you can add comments in SQL as well.
There are two types of comments:
* Inline comments:
To do so, you just need to add `--` before the text that you want to comment out:
```sql
SELECT * FROM users; -- Get all users
```
* Multiple-line comments:
Similar to some other programming languages in order to comment multiple lines, you could wrap the text in `/*` `*/` as follows:
```sql
/*
Get all of the users
from your database
*/
SELECT * FROM users;
```
You could write that in a `.sql` file and then run it later on, or execute the few lines directly.
## Conclusion
Those were some of the most common basic SQL statements.
In the next chapters, we are going to go over each of the above statements more in-depth.

359
docs/docs/Introduction-To-Databases/005-select.md

@ -0,0 +1,359 @@
# SELECT
As we briefly covered in the previous chapter, the `SELECT` statement allows us to retrieve data from single or multiple tables on the database. In this chapter, we will be performing the query on a single table.
It corresponds to the projection operation of Relational Algebra.
You can use `SELECT` to get all of your users or a list of users that match a certain criteria.
Before we dive into the `SELECT` statement let's quickly create a database:
```sql
CREATE DATABASE sql_demo;
```
Switch to that database:
```sql
USE sql_demo;
```
Create a new users table:
```sql
CREATE TABLE users
(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(255) NOT NULL,
about TEXT,
email VARCHAR(255),
birthday DATE,
active BOOL
);
```
Insert some data that we could work with:
```sql
INSERT INTO users
( username, email, active )
VALUES
('bobby', 'b@devdojo.com', true),
('devdojo', 'd@devdojo.com', false),
('tony', 't@devdojo.com', true);
```
Output:
```
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
```
We are going to learn more about the `INSERT` statement in the following chapters.
## SELECT all columns
Now that we've got some data in the `users` table, let's go ahead and retrieve all of the entries from that table:
```sql
SELECT * FROM users;
```
Rundown of the statement:
* `SELECT`: First, we specify the action that we want to execute, in our case, we want to select or get some data from the database.
* `*`: The star here indicates that we want to get all of the columns associated with the table that we are selecting from.
* `FROM`: The from statement tells MySQL which table we want to select the data from. You need to keep in mind that you can select from multiple tables, but this is a bit more advanced, and we are going to cover this in the next few chapters.
* `users`: This is the table name that we want to select the data from.
This will return all of the entries in the `users` table along with all of the columns:
```
+----+----------+-------+----------+--------+---------------+
| id | username | about | birthday | active | email |
+----+----------+-------+----------+--------+---------------+
| 1 | bobby | NULL | NULL | 1 | b@devdojo.com |
| 2 | devdojo | NULL | NULL | 0 | d@devdojo.com |
| 3 | tony | NULL | NULL | 1 | t@devdojo.com |
+----+----------+-------+----------+--------+---------------+
3 rows in set (0.00 sec)
```
As you can see, we get a list of the 3 users that we've just created, including all of the columns in that table. In some cases, the table might have a lot of columns, and you might not want to see all of them. For example, we have the `about` and `birthday` columns that are all `NULL` at the moment. So let's see how we could limit that and get only a list of specific columns.
## Pattern matching
SQL pattern matching let's you to search for patterns if you don't know the exact word or phrase you are looking for. To do this, we use so-called wildcard characters to match a pattern together with LIKE and ILIKE operators.
Two of the most common wildcard characters are `_` and `%`.
`_` matches any single character and `%` matches an arbitrary number of characters.
Let's see an example how you would look for a `username` ending with `y`:
```sql
SELECT * FROM users WHERE username LIKE '%y';
```
Output:
```
+----+----------+-------+----------+--------+---------------+
| id | username | about | birthday | active | email |
+----+----------+-------+----------+--------+---------------+
| 1 | bobby | NULL | NULL | 1 | b@devdojo.com |
| 3 | tony | NULL | NULL | 1 | t@devdojo.com |
+----+----------+-------+----------+--------+---------------+
```
As you can see above, we used `%` to match any number of characters preceding the character `y`.
If we know the exact number of characters we want to match, we can use `_`. Each `_` represents a single character.
So, if we want to look up an username that has `e` as its second character, we would do something like this:
```sql
SELECT * FROM users WHERE username LIKE '_e%';
```
Output:
```
+----+----------+-------+----------+--------+---------------+
| id | username | about | birthday | active | email |
+----+----------+-------+----------+--------+---------------+
| 2 | devdojo | NULL | NULL | 0 | d@devdojo.com |
+----+----------+-------+----------+--------+---------------+
```
Please, keep in mind that `LIKE` operator is case sensitive, meaning it won't mach capital letters with lowercase letters and vice versa. If you wish to ignore capitalization, use `ILIKE` operator instead.
## Formatting
As we mentioned in the previous chapters, each SQL statement needs to end with a semi-colon: `;`. Alternatively, rather than using a semi-colon, you could use the `\G` characters which would format the output in a list rather than a table.
The syntax is absolutely the same but you just change the `;` with `\G`:
```sql
SELECT * FROM users \G
```
The output will be formatted like this:
```
*************************** 1. row ***************************
id: 1
username: bobby
about: NULL
birthday: NULL
active: 1
email: b@devdojo.com
*************************** 2. row ***************************
id: 2
username: devdojo
about: NULL
birthday: NULL
active: 0
email: d@devdojo.com
...
```
This is very handy whenever your table consists of a large number of columns and they can't fit on the screen, which makes it very hard to read the result set.
## SELECT specific columns only
You could limit this to a specific set of columns. Let's say that you only needed the `username` and the `active` columns. In this case, you would change the `*` symbol with the columns that you want to select divided by a comma:
```sql
SELECT username,active FROM users;
```
Output:
```
+----------+--------+
| username | active |
+----------+--------+
| bobby | 1 |
| devdojo | 0 |
| tony | 1 |
+----------+--------+
```
As you can see, we are getting back only the 2 columns that we've specified in the `SELECT` statement.
> **NOTE:** _SQL names are case insensitive. For example, username ≡ USERNAME ≡ userName._
## SELECT with no FROM Clause
In a SQL statement, a column can be a literal with no `FROM` clause.
```sql
SELECT 'Sunil' as username;
```
Output:
```
+----------+
| username |
+----------+
| Sunil |
+----------+
```
## SELECT with Arithmetic Operations
The select clause can contain arithmetic expressions involving the operation +, –, *, and /.
```sql
SELECT username, active*5 as new_active FROM users;
```
Output:
```
+----------+------------+
| username | new_active |
+----------+------------+
| bobby | 5 |
| devdojo | 0 |
| tony | 5 |
+----------+------------+
```
## LIMIT
The `LIMIT` clause is very handy in case that you want to limit the number of results that you get back. For example, at the moment, we have 3 users in our database, but let's say that you only wanted to get 1 entry back when you run the `SELECT` statement.
This can be achieved by adding the `LIMIT` clause at the end of your statement, followed by the number of entries that you want to get. For example, let's say that we wanted to get only 1 entry back. We would run the following query:
```sql
SELECT * FROM users LIMIT 1;
```
Output:
```
+----+----------+-------+----------+--------+---------------+
| id | username | about | birthday | active | email |
+----+----------+-------+----------+--------+---------------+
| 2 | bobby | NULL | NULL | 1 | b@devdojo.com |
+----+----------+-------+----------+--------+---------------+
```
If you wanted to get 2 entries, you would change `LIMIT 2` and so on.
## COUNT
In case that you wanted to get only the number of entries in a specific column, you could use the `COUNT` function. This is a function that I personally use very often.
The syntax is the following:
```sql
SELECT COUNT(*) FROM users;
```
Output:
```
+----------+
| COUNT(*) |
+----------+
| 3 |
+----------+
```
## MIN, MAX, AVG, and SUM
Another useful set of functions similar to `COUNT` that would make your life easier are:
* `MIN`: This would give you the smallest value of a specific column. For example, if you had an online shop and you wanted to get the lowest price, you would use the `MIN` function. In our case, if we wanted to get the lowest user ID, we would run the following:
```sql
SELECT MIN(id) FROM users;
```
This would return `1` as the lowest user ID that we have is 1.
* `MAX`: Just like `MIN`, but it would return the highest value:
```sql
SELECT MAX(id) FROM users;
```
In our case, this would be `3` as we have only 3 users, and the highest value of the `id` column is 3.
* `AVG`: As the name suggests, it would sum up all of the values of a specific column and return the average value. As we have 3 users with ids 1, 2, and 3, the average would be 6 divided by 3 users which is 2.
```sql
SELECT AVG(id) FROM users;
```
* `SUM`: This function takes all of the values from the specified column and sums them up:
```sql
SELECT SUM(id) FROM users;
```
## DISTINCT
In some cases, you might have duplicate entries in a table, and in order to get only the unique values, you could use `DISTINCT`.
To better demonstrate this, let's run the insert statement one more time so that we could duplicate the existing users and have 6 users in the users table:
```sql
INSERT INTO users
( username, email, active )
VALUES
('bobby', 'b@devdojo.com', true),
('devdojo', 'd@devdojo.com', false),
('tony', 't@devdojo.com', true);
```
Now, if you run `SELECT COUNT(*) FROM users;` you would get `6` back.
Let's also select all users and show only the `username` column:
```sql
SELECT username FROM users;
```
Output:
```
+----------+
| username |
+----------+
| bobby |
| devdojo |
| tony |
| bobby |
| devdojo |
| tony |
+----------+
```
As you can see, each name is present multiple times in the list. We have `bobby`, `devdjo` and `tony` showing up twice.
If we wanted to show only the unique `usernames`, we could add the `DISTINCT` keyword to our select statement:
```sql
SELECT DISTINCT username FROM users;
```
Output:
```
+----------+
| username |
+----------+
| bobby |
| devdojo |
| tony |
+----------+
```
As you can see, the duplicate entries have been removed from the output.
## Conclusion
The `SELECT` statement is essential whenever working with SQL. In the next chapter, we are going to learn how to use the `WHERE` clause and take the `SELECT` statements to the next level.

225
docs/docs/Introduction-To-Databases/006-where.md

@ -0,0 +1,225 @@
# WHERE
The `WHERE` clause allows you to specify different conditions so that you could filter out the data and get a specific result set.
You would add the `WHERE` clause after the `FROM` clause.
The syntax would look like this:
```sql
SELECT column_name FROM table_name WHERE column=some_value;
```
## WHERE Clause example
If we take the example `users` table from the last chapter, let's say that we wanted to get only the active users. The SQL statement would look like this:
```sql
SELECT DISTINCT username, email, activem FROM users WHERE active=true;
```
Output:
```
+----------+---------------+--------+
| username | email | active |
+----------+---------------+--------+
| bobby | b@devdojo.com | 1 |
| tony | t@devdojo.com | 1 |
+----------+---------------+--------+
```
As you can see, we are only getting `tony` and `bobby` back as their `active` column is `true` or `1`. If we wanted to get the inactive users, we would have to change the `WHERE` clause and set the `active` to `false`:
```
+----------+---------------+--------+
| username | email | active |
+----------+---------------+--------+
| devdojo | d@devdojo.com | 0 |
+----------+---------------+--------+
```
As another example, let's say that we wanted to select all users with the username `bobby`. The query, in this case, would be:
```sql
SELECT username, email, active FROM users WHERE username='bobby';
```
The output would look like this:
```
+----------+---------------+--------+
| username | email | active |
+----------+---------------+--------+
| bobby | b@devdojo.com | 1 |
| bobby | b@devdojo.com | 1 |
+----------+---------------+--------+
```
We are getting 2 entries back as we have 2 users in our database with the username `bobby`.
## Operators
In the example, we used the `=` operator, which checks if the result set matches the value that we are looking for.
A list of popular operators are:
* `!=` : Not equal operator
* `>` : Greater than
* `>=` : Greater than or equal operator
* `<` : Less than operator
* `<=` : Less than or equal operator
For more information about other available operators, make sure to check the official documentation [here](https://dev.mysql.com/doc/refman/8.0/en/non-typed-operators.html).
## AND keyword
In some cases, you might want to specify multiple criteria. For example, you might want to get all users that are active, and the username matches a specific value. This could be achieved with the `AND` keyword.
Syntax:
```sql
SELECT * FROM users WHERE username='bobby' AND active=true;
```
The result set would contain the data that matches both conditions. In our case, the output would be:
```
+----+----------+-------+----------+--------+---------------+
| id | username | about | birthday | active | email |
+----+----------+-------+----------+--------+---------------+
| 2 | bobby | NULL | NULL | 1 | b@devdojo.com |
| 5 | bobby | NULL | NULL | 1 | b@devdojo.com |
+----+----------+-------+----------+--------+---------------+
```
If we were to change the `AND` statement to `active=false`, we would not get any results back as none of the entries in our database match that condition:
```sql
SELECT * FROM users WHERE username='bobby' AND active=false;
```
```
-- Output:
Empty set (0.01 sec)
```
## OR keyword
In some cases, you might want to specify multiple criteria. For example, you might want to get all users that are active, or their username matches a specific value. This could be achieved with the `OR` keyword.
As with any other programming language, the main difference between `AND` and `OR` is that with `AND`, the result would only return the values that match the two conditions, and with `OR`, you would get a result that matches either of the conditions.
For example, if we were to run the same query as above but change the `AND` to `OR`, we would get all users that have the username `bobby` and also all users that are not active:
```sql
SELECT * FROM users WHERE username='bobby' OR active=false;
```
Output:
```
+----+----------+-------+----------+--------+---------------+
| id | username | about | birthday | active | email |
+----+----------+-------+----------+--------+---------------+
| 2 | bobby | NULL | NULL | 1 | b@devdojo.com |
| 3 | devdojo | NULL | NULL | 0 | d@devdojo.com |
| 5 | bobby | NULL | NULL | 1 | b@devdojo.com |
| 6 | devdojo | NULL | NULL | 0 | d@devdojo.com |
+----+----------+-------+----------+--------+---------------+
```
## LIKE operator
Unlike the `=` operator, the `LIKE` operator allows you to do wildcard matching similar to the `*` symbol in Linux.
For example, if you wanted to get all users that have the `y` letter in them, you would run the following:
```sql
SELECT * FROM users WHERE username LIKE '%y%';
```
Output
```
+----+----------+-------+----------+--------+---------------+
| id | username | about | birthday | active | email |
+----+----------+-------+----------+--------+---------------+
| 2 | bobby | NULL | NULL | 1 | b@devdojo.com |
| 4 | tony | NULL | NULL | 1 | t@devdojo.com |
+----+----------+-------+----------+--------+---------------+
```
As you can see, we are getting only `tony` and `bobby` but not `devdojo` as there is no `y` in `devdojo`.
This is quite handy when you are building some search functionality for your application.
# IN operator
The `IN` operator allows you to provide a list expression and would return the results that match that list of values.
For example, if you wanted to get all users that have the username `bobby` and `devdojo`, you could use the following:
```sql
SELECT * FROM users WHERE username IN ('bobby', 'devdojo');
```
Output:
```
+----+----------+-------+----------+--------+---------------+
| id | username | about | birthday | active | email |
+----+----------+-------+----------+--------+---------------+
| 2 | bobby | NULL | NULL | 1 | b@devdojo.com |
| 3 | devdojo | NULL | NULL | 0 | d@devdojo.com |
| 5 | bobby | NULL | NULL | 1 | b@devdojo.com |
| 6 | devdojo | NULL | NULL | 0 | d@devdojo.com |
+----+----------+-------+----------+--------+---------------+
```
This allows you to simplify your `WHERE` expression so that you don't have to add numerous `OR` statements.
## IS operator
If you were to run `SELECT * FROM users WHERE about=NULL;` you would get an empty result set as the `=` operator can't be used to check for NULL values. Instead, you would need to use the `IS` operator instead.
The `IS` operator is only used to check `NULL` values, and the syntax is the following:
```sql
SELECT * FROM users WHERE about IS NULL;
```
If you wanted to get the results where the value is not NULL, you just need to change `IS` to `IS NOT`:
```sql
SELECT * FROM users WHERE about IS NOT NULL;
```
## BETWEEN operator
The `BETWEEN` operator allows to select value with a given range.The values can be numbers, text, or dates.
BETWEEN operator is inclusive: begin and end values are included.
For Example if you want to select those user which have id between 3 and 6.
```sql
SELECT * FROM users WHERE id BETWEEN 3 AND 6;
```
Output:
```
+----+----------+-------+----------+--------+---------------+
| id | username | about | birthday | active | email |
+----+----------+-------+----------+--------+---------------+
| 3 | devdojo | NULL | NULL | 0 | d@devdojo.com |
| 5 | bobby | NULL | NULL | 1 | b@devdojo.com |
| 6 | devdojo | NULL | NULL | 0 | d@devdojo.com |
+----+----------+-------+----------+--------+---------------+
```
## Conclusion
In this chapter, you've learned how to use the `WHERE` clause with different operators to get different type of results based on the parameters that you provide.
In the next chapter, we will learn how to order the result set.

143
docs/docs/Introduction-To-Databases/007-order-and-group-by.md

@ -0,0 +1,143 @@
# Sorting with ORDER and GROUP BY
In the last chapter, you've learned how to use the `SELECT` statement with the `WHERE` clause and filter the result set based on some conditions.
More often than not, you would want to order the results in a specific way based on a particular column. For example, you might want to order the users alphabetically based on their username.
In this chapter, you will learn how to use the `ORDER BY` and `GROUP BY` clauses.
## ORDER BY
The main thing that you need to keep in mind when using `ORDER BY` is to specify the column or columns you want to order by. In case you want to specify multiple columns to order by, you need to separate each column with a comma.
If we were to run the following statement without providing an `ORDER BY` clause:
```sql
SELECT id, username FROM users;
```
We will get the following output:
```
+----+----------+
| id | username |
+----+----------+
| 2 | bobby |
| 3 | devdojo |
| 4 | tony |
| 5 | bobby |
| 6 | devdojo |
| 7 | tony |
+----+----------+
```
As you can see, the result set is sorted by the primary key, which, in our case, is each user's id. If we wanted to sort the output by `username`, we would run the following query:
```sql
SELECT id, username FROM users ORDER BY username;
```
> Note: The `ORDER BY` statement is followed by the column's name that we want to order by.
The output, in this case, will be:
```
+----+----------+
| id | username |
+----+----------+
| 2 | bobby |
| 5 | bobby |
| 3 | devdojo |
| 6 | devdojo |
| 4 | tony |
| 7 | tony |
+----+----------+
```
> Note: You can use `ORDER BY` with and without specifying a `WHERE` clause. If you've used a `WHERE` clause, you must put the `ORDER BY` clause after the `WHERE` clause.
The default sorting is ascending and is specified with the `ASC` keyword, and you don't need to add it explicitly, but if you want to sort by descending order, you need to use the `DESC` keyword.
If we use the query above and add `DESC` at the end as follows:
```sql
SELECT id, username FROM users ORDER BY username DESC;
```
We will see the following output:
```
+----+----------+
| id | username |
+----+----------+
| 4 | tony |
| 7 | tony |
| 3 | devdojo |
| 6 | devdojo |
| 2 | bobby |
| 5 | bobby |
+----+----------+
```
As you can see, we've got the same list of users sorted alphabetically but in reverse order.
## GROUP BY
The `GROUP BY` statement allows you to use a function like `COUNT`, `MIN`, `MAX` etc., with multiple columns.
For example, let's say that we wanted to get all user counts grouped by username.
In our case, we have two users with the username `bobby`, two users with the username `tony`, and two users with the username `devdojo`. This represented in an SQL statement would look like this:
```sql
SELECT COUNT(username), username FROM users GROUP BY username;
```
The output, in this case, would be:
```
+-----------------+----------+
| COUNT(username) | username |
+-----------------+----------+
| 2 | bobby |
| 2 | devdojo |
| 2 | tony |
+-----------------+----------+
```
The `GROUP BY` statement grouped the identical usernames. Then it ran a `COUNT` on each of `bobby`, `tony` and `devdojo`.
The main thing to remember here is that the `GROUP BY` should be added after the `FROM` clause and after the `WHERE` clause.
## HAVING Clause
The `HAVING` clause allows you to filter out the results on the groups formed by the `GROUP BY` clause.
For example, let's say that we wanted to get all usernames that are duplicates, i.e., all the usernames present in more than one table record.
In our case, we have two users with the username `bobby`, two users with the username `tony`, and two users with username `devdojo`. This represented in an SQL statement would look like this:
```sql
SELECT COUNT(username), username
FROM users
GROUP BY username
HAVING COUNT(username) > 1;
```
The output, in this case, would be:
```
+-----------------+----------+
| COUNT(username) | username |
+-----------------+----------+
| 2 | bobby |
| 2 | devdojo |
| 2 | tony |
+-----------------+----------+
```
The `GROUP BY` clause grouped the identical usernames, calculated their counts and filtered out the groups using the `HAVING` clause.
> **NOTE**:- _The WHERE clause places conditions on the selected columns, whereas the HAVING clause places conditions on groups created by the GROUP BY clause._

86
docs/docs/Introduction-To-Databases/008-insert.md

@ -0,0 +1,86 @@
# INSERT
To add data to your database, you would use the `INSERT` statement. You can insert data into one table at a time only.
The syntax is the following:
```sql
INSERT INTO table_name
(column_name_1,column_name_2,column_name_n)
VALUES
('value_1', 'value_2', 'value_3');
```
You would start with the `INSERT INTO` statement, followed by the table that you want to insert the data into. Then you would specify the list of the columns that you want to insert the data into. Finally, with the `VALUES` statement, you specify the data that you want to insert.
> The important part is that you need to keep the order of the values based on the order of the columns that you've specified.
In the above example the `value_1` would go into `column_name_1`, the `value_2` would go into `column_name_2` and the `value_3` would go into `column_name_x`.
Let's use the table that we created in the last chapter and insert 1 user into our `users` table:
```sql
INSERT INTO users
(username, email, active)
VALUES
('greisi', 'g@devdojo.com', true);
```
Rundown of the insert statement:
* `INSERT INTO users`: First, we specify the `INSERT INTO` keywords which tells MySQL that we want to insert data into the `users` table.
* `users (username, email, active)`: Then, we specify the table name `users` and the columns that we want to insert data into.
* `VALUES`: Then, we specify the values that we want to insert in.
## Inserting multiple records
We've briefly covered this in one of the previous chapters, but in some cases, you might want to add multiple records in a specific table.
Let's say that we wanted to create 5 new users, rather than running 5 different queries like this:
```sql
INSERT INTO users (username, email, active) VALUES ('user1', 'user1@devdojo.com', true);
INSERT INTO users (username, email, active) VALUES ('user1', 'user2@devdojo.com', true);
INSERT INTO users (username, email, active) VALUES ('user1', 'user3@devdojo.com', true);
INSERT INTO users (username, email, active) VALUES ('user1', 'user4@devdojo.com', true);
INSERT INTO users (username, email, active) VALUES ('user1', 'user5@devdojo.com', true);
```
What you could do is to combine this into one `INSERT` statement by providing a list of the values that you want to insert as follows:
```sql
INSERT INTO users
(username, email, active)
VALUES
('user1', 'user1@devdojo.com', true),
('user2', 'user2@devdojo.com', true),
('user3', 'user3@devdojo.com', true),
('user4', 'user4@devdojo.com', true),
('user5', 'user5@devdojo.com', true);
```
That way, you will add 5 new entries in your `users` table with a single `INSERT` statement. This is going to be much more efficient.
## Inserting multiple records using another table
In the previous section, we have discussed how we can insert multiple records using a single INSERT query.
But sometimes there are cases where we need to insert multiple records which are residing in some other table.
In this section, we are going to learn how we can insert multiple records at once using a single INSERT query.
Consider a table, say `prospect_users`, which stores the information of the people who want to become the users of our service, but they are not yet actual users.
In order to add them to our user database, we have to insert there entries into our `users` table.
We can achieve the same by writing an `INSERT` query with multiple `VALUES` listed in them (as discussed in previous section).
But there is an easier way where we achieve the same by querying the `prospect_users` table.
```sql
INSERT INTO users (username, email, active)
SELECT username, email, active
FROM prospect_users
WHERE active=true;
```
Using the above statement, an entry for each active prospect users will be made in our `users` table.

106
docs/docs/Introduction-To-Databases/009-update.md

@ -0,0 +1,106 @@
# UPDATE
As the name suggests, whenever you have to update some data in your database, you would use the `UPDATE` statement.
You can use the `UPDATE` statement to update multiple columns in a single table.
The syntax would look like this:
```sql
UPDATE users SET username='bobbyiliev' WHERE id=1;
```
Rundown of the statement:
* `UPDATE users`: First, we specify the `UPDATE` keyword followed by the table that we want to update.
* `username='bobbyiliev'`: Then we specify the columns that we want to update and the new value that we want to set.
* `WHERE id=1`: Finally, by using the `WHERE` clause, we specify which user should be updated. In our case, it is the user with ID 1.
The most important thing that you need to keep in mind is that if you don't specify a `WHERE` clause, all of the entries inside the `users` table would be updated, and all users would have the `username` set to `bobbyiliev`.
> Important: You need to be careful when you use the `UPDATE` statement without a `WHERE` clause as every single row will be updated.
If you have been following along all of the user entries in our `users` table, it currently have no data in the `about` column:
```
+----+----------+-------+
| id | username | about |
+----+----------+-------+
| 2 | bobby | NULL |
| 3 | devdojo | NULL |
| 4 | tony | NULL |
| 5 | bobby | NULL |
| 6 | devdojo | NULL |
| 7 | tony | NULL |
+----+----------+-------+
```
Let's go ahead and update this for all users and set the column value to `404 bio not found`, For example:
```sql
UPDATE users SET about='404 bio not found';
```
The output would let you know how many rows have been affected by the query:
```
Query OK, 6 rows affected (0.02 sec)
Rows matched: 6 Changed: 6 Warnings: 0
```
Now, if you were to run a select for all `users`, you would get the following result:
```
+----+----------+-------------------+
| id | username | about |
+----+----------+-------------------+
| 2 | bobby | 404 bio not found |
| 3 | devdojo | 404 bio not found |
| 4 | tony | 404 bio not found |
| 5 | bobby | 404 bio not found |
| 6 | devdojo | 404 bio not found |
| 7 | tony | 404 bio not found |
+----+----------+-------------------+
```
Let's now say that we wanted to update the `about` column for the user with an id of 2. In this case, we need to specify a `WHERE` clause followed by the ID of the user that we want to update as follows:
```sql
UPDATE users SET about='Hello World :)' WHERE id=2;
```
The output here should indicate that only 1 row was updated:
```
Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0
```
Now, if you again run the `SELECT id, username, about FROM users` query, you would see that the user with `id` of 2 now has an updated `about` column data:
```
+----+----------+-------------------+
| id | username | about |
+----+----------+-------------------+
| 2 | bobby | Hello World :) |
| 3 | devdojo | 404 bio not found |
| 4 | tony | 404 bio not found |
| 5 | bobby | 404 bio not found |
| 6 | devdojo | 404 bio not found |
| 7 | tony | 404 bio not found |
+----+----------+-------------------+
```
## Updating records using another table
As we've seen in the previous section, you can insert multiple rows in your table using another table. You can use the same principle for the update command.
To do that you simply have to list all needed table in the `update` section, then you have to explain which action you want to perform on the table, and then you need to link the table together.
For example, if you want to update the `about` field in the `users` table using the content of the `about` field in the `prospect_users` table, you would do something like this:
```sql
update users, prospect_users
set users.about = prospect_users.about
where prospect_users.username = users.username;
```

41
docs/docs/Introduction-To-Databases/010-delete.md

@ -0,0 +1,41 @@
# DELETE
As the name suggests, the `DELETE` statement would remove data from your database.
The syntax is as follows:
```sql
DELETE FROM users WHERE id=5;
```
The output should indicate that 1 row was affected:
```
Query OK, 1 row affected (0.01 sec)
```
> Important: Just like the `UPDATE` statement, if you don't specify a `WHERE` clause, all of the entries from the table will be affected, meaning that all of your users will be deleted. So, it is critical to always add a `WHERE` clause when executing a `DELETE` statement.
```sql
DELETE FROM users;
```
The output should indicate (where x is the number of tuples in the table):
```
Query OK, x row(s) affected (0.047 sec)
```
Similar to the Linux `rm` command, when you use the `DELETE` statement, the data would be gone permanently, and the only way to recover your data would be by restoring a backup.
## Delete from another table
As we saw in the two precedents sections you can `INSERT` or `UPDPATE` tables rows based on other table data. You can do the same for the `DELETE`.
For example, if you want to delete the records from the `users` table if the corresponding prospect has been disabled, you could do it this way:
```sql
delete users
from users, prospect_users
where users.username = prospect_users.username
and NOT prospect_users.active
```

370
docs/docs/Introduction-To-Databases/011-join.md

@ -0,0 +1,370 @@
# JOIN
The `JOIN` clause allows you to combine the data from 2 or more tables into one result set.
As we will be selecting from multiple columns, we need to include the list of the columns we want to choose data from after the `FROM` clause is separated by a comma.
In this chapter, we will go over the following `JOIN` types:
* `CROSS` Join
* `INNER` Join
* `LEFT` Join
* `RIGHT` Join
Before we get started, let's create a new database and two tables that we are going to work with:
* We are going to call the database `demo_joins`:
```sql
CREATE DATABASE demo_joins;
```
* Then, switch to the new database:
```sql
USE demo_joins;
```
* Then, the first table will be called `users`, and it will only have two columns: `id` and `username`:
```sql
CREATE TABLE users
(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(255) NOT NULL
);
```
* Then, let's create a second table called `posts`, and to keep things simple, we will have three two columns: `id`, `user_id` and `title`:
```sql
CREATE TABLE posts
(
id INT PRIMARY KEY AUTO_INCREMENT,
user_id INT,
title VARCHAR(255) NOT NULL
);
```
> The `user_id` column would be used to reference the user's ID that the post belongs to. It is going to be a one to many relations, e.g. one user could have many posts:
![One to many relation](https://imgur.com/ipIjCaL.png)
* Now, let's add some data into the two tables first by creating a few users:
```sql
INSERT INTO users
( username )
VALUES
('bobby'),
('devdojo'),
('tony'),
('greisi');
```
* And finally add some posts:
```sql
INSERT INTO posts
( user_id, title )
VALUES
('1', 'Hello World!'),
('2', 'Getting started with SQL'),
('3', 'SQL is awesome'),
('2', 'MySQL is up!'),
('1', 'SQL - structured query language');
```
Now that we've got our tables and demo data ready, let's go ahead and learn how to use joins.
## CROSS JOIN
The `CROSS` join allows you to put the result of two tables next to each other without specifying any `WHERE` conditions. This makes the `CROSS` join the simplest one, but it is also not of much use in a real-life scenario.
So if we were to select all of the users and all of the posts side by side, we would use the following query:
```sql
SELECT * FROM users CROSS JOIN posts;
```
The output will be all of your users and all of the posts side by side:
```
+----+----------+----+--------+-----------------+
| id | username | id |user_id | title |
+----+----------+----+--------+-----------------+
| 4 | greisi | 1 | 1 | Hello World! |
| 3 | tony | 1 | 1 | Hello World! |
| 2 | devdojo | 1 | 1 | Hello World! |
| 1 | bobby | 1 | 1 | Hello World! |
| 4 | greisi | 2 | 2 | Getting started |
| 3 | tony | 2 | 2 | Getting started |
| 2 | devdojo | 2 | 2 | Getting started |
| 1 | bobby | 2 | 2 | Getting started |
| 4 | greisi | 3 | 3 | SQL is awesome |
| 3 | tony | 3 | 3 | SQL is awesome |
| 2 | devdojo | 3 | 3 | SQL is awesome |
| 1 | bobby | 3 | 3 | SQL is awesome |
| 4 | greisi | 4 | 2 | MySQL is up! |
| 3 | tony | 4 | 2 | MySQL is up! |
| 2 | devdojo | 4 | 2 | MySQL is up! |
| 1 | bobby | 4 | 2 | MySQL is up! |
| 4 | greisi | 5 | 1 | SQL |
| 3 | tony | 5 | 1 | SQL |
| 2 | devdojo | 5 | 1 | SQL |
| 1 | bobby | 5 | 1 | SQL |
+----+----------+----+--------+-----------------+
```
As mentioned above, you will highly unlikely run a `CROSS` join for two whole tables in a real-life scenario. If the tables have tens of thousands of rows, an unqualified CROSS JOIN can take minutes to complete.
You would most likely use one of the following with a specific condition.
In MySQL, CROSS JOIN and INNER JOIN are equivalent to JOIN.
## INNER JOIN
The `INNER` join is used to join two tables. However, unlike the `CROSS` join, by convention, it is based on a condition. By using an `INNER` join, you can match the first table to the second one.
As we have a one-to-many relationship, a best practice would be to use a primary key for the posts `id` column and a foreign key for the `user_id`; that way, we can 'link' or relate the users table to the posts table. However, this is beyond the scope of this SQL basics eBook, though I might extend it in the future and add more chapters.
As an example and to make things a bit clearer, let's say that you wanted to get all of your users and the posts associated with each user. The query that we would use will look like this:
```sql
SELECT *
FROM users
INNER JOIN posts
ON users.id = posts.user_id;
```
Rundown of the query:
* `SELECT * FROM users`: This is a standard select we've covered many times in the previous chapters.
* `INNER JOIN posts`: Then, we specify the second table and which table we want to join the result set.
* `ON users.id = posts.user_id`: Finally, we specify how we want the data in these two tables to be merged. The `user.id` is the `id` column of the `user` table, which is also the primary ID, and `posts.user_id` is the foreign key in the email address table referring to the ID column in the users table.
The output will be the following, associating each user with their post based on the `user_id` column:
```
+----+----------+----+---------+-----------------+
| id | username | id | user_id | title |
+----+----------+----+---------+-----------------+
| 1 | bobby | 1 | 1 | Hello World! |
| 2 | devdojo | 2 | 2 | Getting started |
| 3 | tony | 3 | 3 | SQL is awesome |
| 2 | devdojo | 4 | 2 | MySQL is up! |
| 1 | bobby | 5 | 1 | SQL |
+----+----------+----+---------+-----------------+
```
Note that the INNER JOIN could (in MySQL) equivalently be written merely as JOIN, but that can vary for other SQL dialects:
```sql
SELECT *
FROM users
JOIN posts
ON users.id = posts.user_id;
```
The main things that you need to keep in mind here are the `INNER JOIN` and `ON` clauses.
With the inner join, the `NULL` values are discarded. For example, if you have a user who does not have a post associated with it, the user with NULL posts will not be displayed when running the above `INNER` join query.
To get the null values as well, you would need to use an outer join.
### Types of INNER JOIN
1. **Theta Join ( θ )** :- Theta join combines rows from different tables provided they satisfy the theta condition.
The join condition is denoted by the symbol `θ`. \
Here the comparison operators `(≤, ≥, ˂, ˃, =, ̚ )` come into picture. \
**Notation** :- R<sub>1</sub><sub>θ</sub> R<sub>2</sub>. \
\
For example, suppose we want to buy a mobile and a laptop, based on our budget we have thought of buying both such that mobile price should be less than that of laptop. \
\
`SELECT mobile.model, laptop.model
FROM mobile, laptop
WHERE mobile.price < laptop.price;`
2. **Equijoin** :- When Theta join uses only equality (=) comparison operator, it is said to be equijoin. \
For example, suppose we want to buy a mobile and a laptop, based on our budget we have thought of buying both of the same prices. \
\
`SELECT mobile.model, laptop.model
FROM mobile, laptop
WHERE mobile.price = laptop.price;`
3. **Natural Join ( ⋈ )** :- Natural join does not use any comparison operator. It does not concatenate the way a Cartesian product does. \
We can perform a Natural Join only if at least one standard column exists between two tables. In addition, the column must have the same name and domain. \
\
`SELECT * FROM mobile NATURAL JOIN laptop;`
## LEFT JOIN
Using the `LEFT OUTER` join, you would get all rows from the first table that you've specified, and if there are no associated records within the second table, you will get a `NULL` value.
In our case, we have a user called `graisi`, which is not associated with a specific post. As you can see from the output from the previous query, the `graisi` user was not present there. To show that user, even though it does not have an associated post with it, you could use a `LEFT OUTER` join:
```sql
SELECT *
FROM users
LEFT JOIN posts
ON users.id = posts.user_id;
```
The output will look like this:
```
+----+----------+------+---------+-----------------+
| id | username | id | user_id | title |
+----+----------+------+---------+-----------------+
| 1 | bobby | 1 | 1 | Hello World! |
| 2 | devdojo | 2 | 2 | Getting started |
| 3 | tony | 3 | 3 | SQL is awesome |
| 2 | devdojo | 4 | 2 | MySQL is up! |
| 1 | bobby | 5 | 1 | SQL |
| 4 | greisi | NULL | NULL | NULL |
+----+----------+------+---------+-----------------+
```
## RIGHT JOIN
The `RIGHT OUTER` join is the exact opposite of the `LEFT OUTER` join. It will display all of the rows from the second table and give you a `NULL` value in case that it does not match with an entry from the first table.
Let's create a post that does not have a matching user id:
```sql
INSERT INTO posts
( user_id, title )
VALUES
('123', 'No user post!');
```
We specify `123` as the user ID, but we don't have such a user in our `users` table.
Now, if you were to run the `LEFT` outer join, you would not see the post as it has a null value for the corresponding `users` table.
But if you were to run a `RIGHT` outer join, you would see the post but not the `greisi` user as it does not have any posts:
```sql
SELECT *
FROM users
RIGHT JOIN posts
ON users.id = posts.user_id;
```
Output:
```
+------+----------+----+---------+-----------------+
| id | username | id | user_id | title |
+------+----------+----+---------+-----------------+
| 1 | bobby | 1 | 1 | Hello World! |
| 2 | devdojo | 2 | 2 | Getting started |
| 3 | tony | 3 | 3 | SQL is awesome |
| 2 | devdojo | 4 | 2 | MySQL is up! |
| 1 | bobby | 5 | 1 | SQL |
| NULL | NULL | 6 | 123 | No user post! |
+------+----------+----+---------+-----------------+
```
Joins can also be limited with WHERE conditions. For instance, in the preceding example, if we wanted to join the tables and then restrict to only username `bobby`.
```sql
SELECT *
FROM users
RIGHT JOIN posts
ON users.id = posts.user_id
WHERE username = 'bobby';
```
Output:
```
+------+----------+----+---------+-----------------+
| id | username | id | user_id | title |
+------+----------+----+---------+-----------------+
| 1 | bobby | 1 | 1 | Hello World! |
| 1 | bobby | 5 | 1 | SQL |
+------+----------+----+---------+-----------------+
```
## The Impact of Conditions in JOIN vs. WHERE Clauses
The placement of conditions within a SQL query, specifically in the `JOIN` vs. the `WHERE` clause, can yield different results.
Take a look at the following example, which retrieves `POSTS` containing the word "SQL" along with their associated user data:
```sql
SELECT users.*, posts.*
FROM users
LEFT JOIN posts
ON posts.user_id = users.id
WHERE posts.title LIKE '%SQL%';
```
Output:
```sql
+--+--------+--+-------+-------------------------------+
|id|username|id|user_id|title |
+--+--------+--+-------+-------------------------------+
|2 |devdojo |2 |2 |Getting started with SQL |
|3 |tony |3 |3 |SQL is awesome |
|2 |devdojo |4 |2 |MySQL is up! |
|1 |bobby |5 |1 |SQL - structured query language|
+--+--------+--+-------+-------------------------------+
```
However, by shifting the condition to the `JOIN` clause, all users are displayed, but only posts with titles containing "SQL" are included:
```sql
SELECT users.*, posts.*
FROM users
LEFT JOIN posts
ON posts.user_id = users.id
AND posts.title LIKE '%SQL%';
```
Output:
```sql
+--+--------+----+-------+-------------------------------+
|id|username|id |user_id|title |
+--+--------+----+-------+-------------------------------+
|1 |bobby |5 |1 |SQL - structured query language|
|2 |devdojo |4 |2 |MySQL is up! |
|2 |devdojo |2 |2 |Getting started with SQL |
|3 |tony |3 |3 |SQL is awesome |
|4 |greisi |null|null |null |
+--+--------+----+-------+-------------------------------+
```
## Equivalence of RIGHT and LEFT JOINs
The `RIGHT JOIN` and `LEFT JOIN` operations in SQL are fundamentally equivalent. They can be interchanged by simply swapping the tables involved. Here's an illustration:
The following `LEFT JOIN`:
```sql
SELECT users.*, posts.*
FROM posts
LEFT JOIN users
ON posts.user_id = users.id;
```
Can be equivalently written using `RIGHT JOIN` as:
```sql
SELECT users.*, posts.*
FROM users
RIGHT JOIN posts
ON posts.user_id = users.id;
```
## Conclusion
Joins are fundamental to using SQL with data. The whole concept of joins might be very confusing initially but would make a lot of sense once you get used to it.
The best way to wrap your head around it is to write some queries, play around with each type of `JOIN`, and see how the result set changes.
For more information, you could take a look at the official documentation [here](https://dev.mysql.com/doc/refman/8.0/en/join.html).

121
docs/docs/Introduction-To-Databases/012-sql-commnad-categories.md

@ -0,0 +1,121 @@
# SQL | DDL, DQL, DML, DCL and TCL Commands
Structured Query Language(SQL), as we all know, is the database language by which we can perform certain operations on the existing database. Also, we can use this language to create a database. SQL uses specific commands like Create, Drop, Insert, etc., to carry out the required tasks.
1. **DDL** – Data Definition Language
2. **DQL** – Data Query Language
3. **DML** – Data Manipulation Language
4. **DCL** – Data Control Language
#### Though many resources claim there to be another category of SQL clauses TCL – Transaction Control Language, so we will see in detail about TCL as well.
![img.png](../assets/sql-commnad.png)
### DDL (Data Definition Language):
DDL or Data Definition Language consists of the SQL commands used to define the database schema. It simply deals with descriptions of the database schema and is used to create and modify the structure of database objects in the database. These commands usually are not used by a general user, who should be accessing the database via an application.
#### List of DDL commands:
- `CREATE`: This command is used to create the database or its objects (like table, index, function, views, store procedure, and triggers).
```sql
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
```
- `DROP`: This command is used to delete objects from the database.
```sql
DROP TABLE table_name;
```
- `ALTER`: This is used to alter the structure of the database.
```sql
ALTER TABLE Persons
ADD Age int;
```
- `TRUNCATE`: This is used to remove all records from a table, including all spaces allocated for the records.
```sql
TRUNCATE TABLE Persons;
```
- `COMMENT`: This is used to add comments to the data dictionary.
```sql
--SELECT * FROM Customers;
SELECT * FROM Persons;
```
-` RENAME`: This is used to rename an object existing in the database.
```sql
ALTER TABLE Persons
RENAME COLUMN Age TO Year;
```
#### DQL (Data Query Language):
**DQL** statements are used for performing queries on the data within schema objects. The purpose of the DQL Command is to get some schema relation based on the query passed to it. We can define DQL as follows. It is a component of the SQL statement that allows getting data from the database and imposing order upon it. It includes the SELECT statement. This command allows getting the data out of the database to perform operations with it. When a SELECT is fired against a table(s), the result is compiled into a different temporary table, which is displayed or perhaps received by the program, i.e. a front-end.
#### List of DQL:
`SELECT`: It is used to retrieve data from the database.
```sql
SELECT * FROM table_name;
```
```
+--------+--------------+------------+--------+---------+
| emp_id | emp_name | hire_date | salary | dept_id |
+--------+--------------+------------+--------+---------+
| 1 | Ethan Hunt | 2001-05-01 | 5000 | 4 |
| 2 | Tony Montana | 2002-07-15 | 6500 | 1 |
| 3 | Sarah Connor | 2005-10-18 | 8000 | 5 |
| 4 | Rick Deckard | 2007-01-03 | 7200 | 3 |
| 5 | Martin Blank | 2008-06-24 | 5600 | NULL |
+--------+--------------+------------+--------+---------+
```
The SQL commands that deal with the manipulation of data present in the database belong to DML or Data Manipulation Language, including most of the SQL statements. It is the component of the SQL statement that controls access to data and the database. DCL statements are grouped with DML statements.
#### List of DML commands:
- `INSERT `: It is used to insert data into a table.
```sql
INSERT INTO Customers
(CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES
('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');
```
- `UPDATE`: It is used to update existing data within a table.
```sql
UPDATE Customers
SET ContactName='Alfred Schmidt', City='Frankfurt'
WHERE CustomerID = 1;
```
- `DELETE `: It is used to delete records from a database table.
```sql
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
```
- `LOCK`: Table control concurrency.
```sql
LOCK TABLES table_name [READ | WRITE]
--------------------------------------
UNLOCK TABLES;
```
- `CALL`: Call a PL/SQL or JAVA subprogram.
```sql
CREATE PROCEDURE procedure_name
AS sql_statement
GO;
```
#### Execute a Stored Procedure
```sql
EXEC procedure_name;
```
- `EXPLAIN PLAN`: It describes the access path to data.
#### DCL (Data Control Language):
DCL includes commands such as GRANT and REVOKE, which mainly deal with the database system's rights, permissions, and other controls.
##### List of DCL commands:
- `GRANT`: This command gives users access privileges to the database.
- `REVOKE`: This command withdraws the user’s access privileges given by using the GRANT command.
Though many resources claim there to be another category of SQL clauses TCL – Transaction Control Language, we will see in detail about TCL. TCL commands deal with the transaction within the database.
##### List of TCL commands:
- `COMMIT`: Commits a Transaction.
- `ROLLBACK`: Rollbacks a transaction in case of any error occurs.
- `SAVEPOINT`:Sets a savepoint within a transaction.
- `SET TRANSACTION`: Specify characteristics for the transaction.

112
docs/docs/Introduction-To-Databases/013-sub-queries.md

@ -0,0 +1,112 @@
# SQL Sub Queries
### A subquery is a SQL query nested inside a larger query.
- A subquery may occur in
- A SELECT clause
- A FROM clause
- A WHERE clause
- The subquery can be nested inside a SELECT, INSERT, UPDATE, or DELETE statement or inside another subquery.
- A subquery is usually added within the WHERE Clause of another SQL SELECT statement.
- The inner query executes first before its parent query so that the results of an inner query can be passed to the outer query.
#### You can use a subquery in a SELECT, INSERT, DELETE, or UPDATE statement to perform the following tasks:
- Compare an expression to the result of the query.
- Determine if an expression is included in the results of the query.
- Check whether the query selects any rows.
**_Subqueries with the `SELECT` Statement_**:
Consider the CUSTOMERS table having the following records
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | Kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Now, let us check the following subquery with a SELECT statement.
_**Example**_:
```sql
SELECT *
FROM CUSTOMERS
WHERE ID IN (
SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500
);
```
This would produce the following result.
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+
**_Subqueries with the `UPDATE` Statement_**:
The subquery can be used in conjunction with the UPDATE statement. Either single or multiple columns in a table can be updated when using a subquery with the UPDATE statement.
**_Example_**:
Assuming, we have CUSTOMERS_BKP table available which is backup of CUSTOMERS table. The following example updates SALARY by 0.25 times in the CUSTOMERS table for all the customers whose AGE is greater than or equal to 27.
```sql
UPDATE CUSTOMERS
SET SALARY = SALARY * 0.25
WHERE AGE IN (
SELECT AGE
FROM CUSTOMERS_BKP
WHERE AGE >= 27
);
```
This would impact two rows and finally CUSTOMERS table would have the following records.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 125.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | Kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 2125.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
**_Subqueries with the `DELETE` Statement_**:
The subquery can be used in conjunction with the DELETE statement like with any other statements mentioned above.
**_Example_**:
Assuming, we have a CUSTOMERS_BKP table available which is a backup of the CUSTOMERS table. The following example deletes the records from the CUSTOMERS table for all the customers whose AGE is greater than or equal to 27.
```sql
DELETE FROM CUSTOMERS
WHERE AGE IN (
SELECT AGE
FROM CUSTOMERS_BKP
WHERE AGE >= 27
);
```
This would impact two rows and finally the CUSTOMERS table would have the following records.
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | Kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+

124
docs/docs/Introduction-To-Databases/014-unions.md

@ -0,0 +1,124 @@
# SQL - UNIONS CLAUSE
The SQL UNION clause/operator is used to combine the results of two or more SELECT statements without returning any duplicate rows.
- While using this UNION clause, each SELECT statement must have:
- The same number of columns selected
- The same number of column expressions
- The same data type and
- Have them in the same order
But they need not have to be in the same length.
_Example_
Consider the following two tables.
Table 1 − customers table is as follows:
+----+----------+-----+-----------+----------+
| id | name | age | address | salary |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Table 2 − orders table is as follows:
+-----+---------------------+-------------+--------+
| oid | date | customer_id | amount |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables in our SELECT statement as follows:
```sql
SELECT id, name, amount, date
FROM customer
LEFT JOIN orders
ON customers.id = orders.customer_id
UNION
SELECT id, name, amount, date
FROM customer
RIGHT JOIN orders
ON customers.id = orders.customer_id
```
This would produce the following result:
### The UNION ALL Clause
The UNION ALL operator is used to combine the results of two SELECT statements including duplicate rows.
The same rules that apply to the UNION clause will apply to the UNION ALL operator.
_Example_ -
Consider the following two tables:
* Table 1 − customers table is as follows:
+----+----------+-----+-----------+----------+
| id | name | age | address | salary |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
* Table 2 − orders table is as follows:
+-----+---------------------+-------------+--------+
| oid | date | customer_id | amount |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables in our SELECT statement as follows :
```sql
SELECT id, name, amount, date
FROM customers
LEFT JOIN orders
ON customers.id = order.customer_id
UNION ALL
SELECT id, name, amount, date
FROM customers
RIGHT JOIN orders
ON customers.id = orders.customer_id;
```
This would produce the following result:
+------+----------+--------+---------------------+
| id | name | amount | date |
+------+----------+--------+---------------------+
| 1 | Ramesh | NULL | NULL |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
| 5 | Hardik | NULL | NULL |
| 6 | Komal | NULL | NULL |
| 7 | Muffy | NULL | NULL |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
+------+----------+--------+---------------------+
Note : **There are two other clauses (i.e., operators), which are like the UNION clause.**

51
docs/docs/Introduction-To-Databases/015-Keys-in-a-Relational Database.md

@ -0,0 +1,51 @@
# Relational Keys- Keys in a Relational Database
A database must be able to inhibit inconsistency occurring due to incorrect data. It must have certain identified attributes in relations to uniquely distinguish the tuples. No two tuples in a relation should have same value for all attributes since it will lead to duplicity of data. duplicity of data leads to inconsistency . Relational database systems have the concept of Relational Keys to distinguish between different records.
## Types of Relational Keys
### *Super Keys*
A relation’s tuples can be uniquely identified by various combinations of attributes. Super Keys is defined as a set of one attribute or combinations of two or more attributes that help in distinguishing between tuples in a relation.
For example, the Customer ID attribute of the relation Customer is unique for all customers. The Customer ID can be used to identify each customer tuple in the relation. Customer ID is a Super Key for relation Customer.
Customer Name attribute of Customer cannot be considered as Super Key because many customers for the organization can have same name. However when combined with Customer ID it becomes a Super Key {CustomerID, CustomerName}. It means that Super Key can have additional attributes. Consider any key K which is identified as a super key. Any superset of key K is also a super key. For example the possible Super Keys for Customer Relation are
- [ CustomerID, CustomerName, Customer Address ]
- [ CustomerID, CustomerName, Customer Contact Number ]
- [ CustomerID, Customer Contact Number ]
### *Candidate Keys*
If we take a key from the set of super keys for which we don’t have any proper subset defined as a superkey, it is called a candidate key. In other words the minimal attribute super keys are termed as candidate keys.
If we can identify some distinct sets of attributes which identify the tuples uniquely they fall in the category of candidate keys. For example the possible Candidate Keys for Customer Relation are
- [ CustomerID ]
- [ CustomerName, Customer Address ]
- [ CustomerName, Customer Contact Number ]
- [ Customer Address, Customer Contact Number ]
### *Primary Key*
Out of all possible candidate keys only one is chosen by the database designer as the key to identify the records in a relation in a database. This selected candidate key is called the Primary Key. It is the property of the relation and not of tuples. The primary key attribute(s) does not allow any duplicate values. It also inhibits leaving the primary key attribute without any value (NOT NULL).
**A relation can have only one primary key.**
In the Customer Database example {Customer ID} is the attribute taken as the primary key of customer relation. While picking up a candidate key as primary key the designer should ensure that it is an attribute or group of attributes that do not change or may change extremely rarely.
### *Alternate Keys*
After selecting one key among candidate keys as primary key, the rest of candidate keys are called the alternate keys. In the customer Database these candidate keys are the alternate keys.
- [ CustomerName, Customer Address ]
- [ CustomerName, Customer Contact Number ]
- [ Customer Address, Customer Contact Number ]
### *Foreign Key*
A foreign key is used to reference values from one relation into another relation. This is possible when the attribute or combination of attributes is primary key in the referenced relation. The relation in which the primary key of a relation is referenced is called the referencing table. The foreign key constraint implements the referential integrity in a database. The referencing relation attribute can have only those values which exist in the primary key attribute(s) of the referenced relation
**A relation can have multiple foreign key**
For example in the customer database the orders' relation (referencing relation) has the structure (Order ID, Customer ID, Order Date, Order Status, Total Billing Amount). The attribute Customer ID is the foreign key referencing Customer ID from customer relation (referenced relation). It means that orders can be placed only for the customers whose customer details are already available in the customer relation.

17
docs/docs/Introduction-To-Databases/016-Logical-operator-keywords.md

@ -0,0 +1,17 @@
# Logical Operator Keywords
Here are the most important Logical Operators summarized in a table.
Logical Operators can be used for conditions as they show a result in form of a `boolean` (True/False) or Unknown.
So, e.g. if an exact value is `True` for a value, a Logical Operator can proof that it's True.
| Logical Operator | Explanation |
|------------------|-------------|
| ALL | If all comparisons are True: return True |
| ANY | If any comparison is True: return True |
| AND | If both expressions are True: return True |
| EXISTS | If a subquery contains rows: return True |
| IN | If compared value is equal to at least one value: return True |
| BETWEEN | If there are values in given range: return True |
| NOT | Reverses the value of any boolean |
| OR | If either expression is True: return True |

186
docs/docs/Introduction-To-Databases/017-having-clause_aggregate-functions.md

@ -0,0 +1,186 @@
# `HAVING` Clause
Unlike where clause which imposes conditions on columns `Having` clause enables you to specify conditions that filter which group results appear in the results.
## Syntax
```sql
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
```
## Description
- Used with `aggregate functions`
- Must follow `GROUP BY` clause in the query
## Aggregate Functions
- SQL aggregation is the task of collecting a set of values to return a single value.
- An aggregate function is a function where the values of multiple rows are grouped together as input on certain criteria to form a single value of more significant meaning.
## Aggregate Functions Examples
Suppose this are the table given to us
|Students | table||
|--------|-----------|--------|
| rollno | name | class |
| 1 | Sanskriti | TE |
| 1 | Shree | BE |
| 2 | Harry | TE |
| 3 | John | TE |
| 3 | Shivani | TE |
|purchase | table||
|------------|-------|---------------|
| item | price | customer_name |
| Pen | 10 | Sanskriti |
| Bag | 1000 | Sanskriti |
| Vegetables | 500 | Sanskriti |
| Shoes | 5000 | Sanskriti |
| Water Bottle | 800 | XYZ |
| Mouse | 120 | ABC |
| Sun Glasses | 1350 | ABC |
### AVG function
Calculates `average` of the given column of values
```sql
SELECT AVG(price) AS Avg_Purchase, customer_name
FROM purchase
GROUP BY customer_name;
```
| Avg_Purchase | customer_name |
|--------------|---------------|
| 1627.5000 | Sanskriti |
### SUM function
Calculates `sum` of values of given column.
```sql
SELECT SUM(price) AS Total_Bill, customer_name
FROM purchase
GROUP BY customer_name;
```
| Total_Bill | customer_name |
|------------|---------------|
| 6510 | Sanskriti |
### COUNT function
Gives `count` of entries/ values in given column.
```sql
SELECT COUNT(item) AS Total_Items, customer_name
FROM purchase
GROUP BY customer_name;
```
| Total_Items | customer_name |
|-------------|---------------|
| 4 | Sanskriti |
### MAX function
Return `maximum` value from the number of values in the column.
```sql
SELECT MAX(price) AS Highest_Purchase, customer_name
FROM purchase
GROUP BY customer_name;
```
| Highest_Purchase | customer_name |
|-----------------|---------------|
| 5000 | Sanskriti |
### MIN function
Return `minimum` value from the number of values in the column.
```sql
SELECT MIN(price) AS Lowest_Purchase, customer_name
FROM purchase
GROUP BY customer_name;
```
| Lowest_Purchase | customer_name |
|-----------------|---------------|
| 10 | Sanskriti |
## Having clause Examples
### Example 1
```sql
SELECT COUNT(class) AS strength, class
FROM Students
GROUP BY class
HAVING COUNT(class) > 2;
```
Above query gives number of students in a class `having` number of students > 2
| strength | class |
|----------|-------|
| 4 | TE |
### Example 2
```sql
SELECT customer_name, MIN(price) AS MIN_PURCHASE
FROM purchase
GROUP BY customer_name
HAVING MIN(price) > 10;
```
Above query finds `minimum` price which is > 10
| customer_name | MIN_PURCHASE |
|---------------|------------|
| XYZ | 800 |
| ABC | 120 |
### Example 3
```sql
SELECT customer_name, AVG(price) AS Average_Purchase
FROM purchase
GROUP BY customer_name
HAVING AVG(price) > 550
ORDER BY customer_name DESC;
```
Above query calculates `average` of price and prints customer name and average price which is greater than 550 with descending `order` of customer names.
| customer_name | Average_Purchase |
|---------------|------------------|
| XYZ | 800.0000 |
| Sanskriti | 1627.5000 |
| ABC | 735.0000 |
### Example 4
```sql
SELECT customer_name, SUM(price) AS Total_Purchase
FROM purchase
WHERE customer_name
LIKE "S%"
GROUP BY customer_name
HAVING SUM(price) > 1000;
```
Calculates `SUM` of price and returns customer name and sum > 1000.
| customer_name | Total_Purchase |
|---------------|----------------|
| Sanskriti | 6510 |

191
docs/docs/Introduction-To-Databases/018-essential-mysql-functions.md

@ -0,0 +1,191 @@
# Essential MySQL Functions
MySQL has many built-in functions. We will covering some important most used built-in functions; for a complete list refer to the online MySQL Reference Manual (http://dev.mysql.com/doc/).
> NOTE: As of now we will be going through only function and their output, as they would be self explanatory.
## Numeric Functions
```sql
SELECT ROUND(5.73)
```
6
```sql
SELECT ROUND(5.73, 1)
```
5.7
```sql
SELECT TRUNCATE(5.7582, 2)
```
5.75
```sql
SELECT CEILING(5.2)
```
6
```sql
SELECT FLOOR(5.7)
```
5
```sql
SELECT ABS(-5.2)
```
5.2
```sql
SELECT RAND() -- Generates a random floating point number b/w 0 & 1
```
## STRING Functions
```sql
SELECT LENGTH('sky')
```
3
```sql
SELECT UPPER('sky')
```
SKY
```sql
SELECT LOWER('sky)
```
sky
```sql
SELECT LTRIM(' sky')
```
sky
```sql
SELECT RTRIM('sky ')
```
sky
```sql
SELECT TRIM(' sky ')
```
sky
```sql
SELECT LEFT('Kindergarten', 4)
```
Kind
```sql
SELECT RIGHT('Kindergarten', 6)
```
garten
```sql
SELECT SUBSTRING('Kindergarten', 3, 5)
```
nderg
```sql
SELECT LOCATE('n','Kindergarten') -- LOCATE returns the first occurrence of a character or character string, if found, otherwise it returns 0
```
3
```sql
SELECT REPLACE('Kindergarten', 'garten', 'garden')
```
Kindergarden
```sql
SELECT CONCAT('first', 'last')
```
firstlast
## DATE Functions
```sql
SELECT NOW()
```
2021-10-21 19:59:47
```sql
SELECT CURDATE()
```
2021-10-21
```sql
SELECT CURTIME()
```
20:01:12
```sql
SELECT MONTH(NOW())
```
10
```sql
SELECT YEAR(NOW())
```
2021
```sql
SELECT HOUR(NOW())
```
13
```sql
SELECT DAYTIME(NOW())
```
Thursday
## Formatting Dates and Times
> In MySQL, the default date format is "YYYY-MM-DD", ex: "2025-05-12", MySQL allows developers to format it the way they want. We will discuss some of them.
```sql
SELECT DATE_FORMAT(NOW(), '%M %D %Y')
```
October 22nd 2021
```sql
SELECT DATE_FORMAT(NOW(), '%m %d %y')
```
10 22 21
```sql
SELECT DATE_FORMAT(NOW(), '%m %D %y')
```
10 22nd 21
```sql
SELECT TIME_FORMAT(NOW(), '%H %i %p')
```
14:11 PM
## Calculating Dates and Times
```sql
SELECT DATE_ADD(NOW(), INTERVAL 1 DAY) --return tomorrows date and time
```
2021-10-23 14:26:17
```sql
SELECT DATE_ADD(NOW(), INTERVAL -1 YEAR)
```
or
```sql
SELECT DATE_SUB(NOW(), INTERVAL 1 YEAR)
```
> Both the queries will return the same output
2020-10-22 14:29:47
```sql
SELECT DATEDIFF('2021-09-08 09:00', '2021-07-07 17:00') -- It will return the difference in number of days, time won't be considered
```
63
```sql
SELECT TIME_TO_SEC('09:00') - TIME_TO_SEC('09:02')
```
-120

154
docs/docs/Introduction-To-Databases/020-TCL-commands.md

@ -0,0 +1,154 @@
# `Transaction Control Language`
- `Transaction Control Language` can be defined as the portion of a database language used for `maintaining consistency` of the database and `managing transactions` in the database.
- A set of `SQL statements` that are `co-related logically and executed on the data stored in the table` is known as a `transaction`.
## `TCL` Commands
- `COMMIT` Command
- `ROLLBACK` Command
- `SAVEPOINT` Command
## `COMMIT`
The main use of `COMMIT` command is to `make the transaction permanent`. If there is a need for any transaction to be done in the database that transaction permanent through commit command.
### Syntax
```sql
COMMIT;
```
## `ROLLBACK`
Using this command, the database can be `restored to the last committed state`. Additionally, it is also used with savepoint command for jumping to a savepoint in a transaction.
### Syntax
```sql
ROLLBACK TO savepoint-name;
```
## `SAVEPOINT`
The main use of the Savepoint command is to save a transaction temporarily. This way users can rollback to the point whenever it is needed.
### Syntax
```sql
SAVEPOINT savepoint-name;
```
## Examples
#### This is purchase table that we are going to use through this tutorial
| item | price | customer_name |
|--------------|-------|---------------|
| Pen | 10 | Sanskriti |
| Bag | 1000 | Sanskriti |
| Vegetables | 500 | Sanskriti |
| Shoes | 5000 | Sanskriti |
| Water Bottle | 800 | XYZ |
| Mouse | 120 | ABC |
| Sun Glasses | 1350 | ABC |
```sql
UPDATE purchase SET price = 20 WHERE item = "Pen";
```
##### O/P : Query OK, 1 row affected (3.02 sec) (Update the price of Pen set it from 10 to 20)
```sql
SELECT * FROM purchase;
```
##### O/P
| item | price | customer_name |
|--------------|-------|---------------|
| Pen | 20 | Sanskriti |
| Bag | 1000 | Sanskriti |
| Vegetables | 500 | Sanskriti |
| Shoes | 5000 | Sanskriti |
| Water Bottle | 800 | XYZ |
| Mouse | 120 | ABC |
| Sun Glasses | 1350 | ABC |
```sql
START TRANSACTION;
```
##### Start transaction
```sql
COMMIT;
```
##### Saved/ Confirmed the transactions till this point
```sql
ROLLBACK;
```
##### Lets consider we tried to rollback above transaction
```sql
SELECT * FROM purchase;
```
#### O/P:
| item | price | customer_name |
|--------------|-------|---------------|
| Pen | 20 | Sanskriti |
| Bag | 1000 | Sanskriti |
| Vegetables | 500 | Sanskriti |
| Shoes | 5000 | Sanskriti |
| Water Bottle | 800 | XYZ |
| Mouse | 120 | ABC |
| Sun Glasses | 1350 | ABC |
##### As we have committed the transactions the `rollback` will not affect anything
```sql
SAVEPOINT sv_update;
```
##### Create the `savepoint` the transactions above this will not be rollbacked
```sql
UPDATE purchase SET price = 30 WHERE item = "Pen";
```
#### O/P : Query OK, 1 row affected (0.57 sec)
#### Rows matched: 1 Changed: 1 Warnings: 0
```sql
SELECT * FROM purchase;
```
| item | price | customer_name |
|--------------|-------|---------------|
| Pen | 30 | Sanskriti |
| Bag | 1000 | Sanskriti |
| Vegetables | 500 | Sanskriti |
| Shoes | 5000 | Sanskriti |
| Water Bottle | 800 | XYZ |
| Mouse | 120 | ABC |
| Sun Glasses | 1350 | ABC |
##### price of pen is changed to 30 using the `update` command
```sql
ROLLBACK to sv_update;
```
##### Now if we `rollback` to the `savepoint` price should be 20 after `rollback` lets see
```sql
SELECT * FROM purchase;
```
| item | price | customer_name |
|--------------|-------|---------------|
| Pen | 20 | Sanskriti |
| Bag | 1000 | Sanskriti |
| Vegetables | 500 | Sanskriti |
| Shoes | 5000 | Sanskriti |
| Water Bottle | 800 | XYZ |
| Mouse | 120 | ABC |
| Sun Glasses | 1350 | ABC |
| Torch | 850 | ABC |
##### As expected we can see `update` query is rollbacked to sv_update.
## Conclusion
With this short tutorial we have learnt TCL commands.

39
docs/docs/Introduction-To-Databases/index.md

@ -0,0 +1,39 @@
# Databases
Before we dive deep into SQL, let's quickly define what a database is.
The definition of databases from Wikipedia is:
> A database is an organized collection of data, generally stored and accessed electronically from a computer system.
In other words, a database is a collection of data stored and structured in different database tables.
## Tables and columns
You've most likely worked with spreadsheet systems like Excel or Google Sheets. At the very basic, database tables are quite similar to spreadsheets.
Each table has different **columns** which could contain different types of data.
For example, if you have a todo list app, you would have a database, and in your database, you would have different tables storing different information like:
* Users - In the users table, you would have some data for your users like: `username`, `name`, and `active`, for example.
* Tasks - The tasks table would store all of the tasks that you are planning to do. The columns of the tasks table would be for example, `task_name`, `status`, `due_date` and `priority`.
The Users table will look like this:
```
+----+----------+---------------+--------+
| id | username | name | active |
+----+----------+---------------+--------+
| 1 | bobby | Bobby Iliev | true |
| 2 | grisi | Greisi I. | true |
| 3 | devdojo | Dev Dojo | false |
+----+----------+---------------+--------+
```
Rundown of the table structure:
* We have 4 columns: `id`, `username`, `name` and `active`.
* We also have 3 entries/users.
* The `id` column is a unique identifier of each user and is auto-incremented.
In the next chapter, we will learn how to install MySQL and create our first database.

BIN
docs/docs/cover.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 156 KiB

77
docs/docs/index.md

@ -0,0 +1,77 @@
# Home
SQL is like a secret code for databases. SQL helps you find hidden treasures in big data piles.
With the Monaco Motors database, you can practice your SQL ninja skills and become a SQL superstar.
Go on a luxury data adventure with the Monaco Motors Schema!
![SQL Query Tool](cover.png)
This is a free and public MariaDB database schema for a fictional Monaco Motors dealership that sells high-end European cars. The Monaco Motors schema was made so that the "kode kiddies" learning SQL and databases have somewhere to play.
## Monaco Motors Overview
The Monaco Motors schema data provides details about customers, sales agents, deals, vehicles, distributors, insurance, managers, and regions.
You can use this data to analyze sales trends, identify top-performing agents, track inventory, and understand customer preferences.
It's a SQL learning growth for those who desire.
## Monaco Motors Tables
This is a database for a fictional Monaco Motors dealership that sells high-end European cars. The data covers various aspects of the dealership's operations, including:
* **Customers:** Customer information like ID, agent ID, name, phone number, and email.
* **Sales Agents:** Agent information like ID, manager ID, dealership ID, names, and salary.
* **Deals:** Deal information like ID, vehicle ID, agent ID, customer ID, insurance ID, and deal date.
* **Vehicles:** Vehicle information like ID, dealership ID, distributor ID, make, model, body type, model year, and price.
* **Distributors:** Distributor information like ID and name.
* **Insurance:** Insurance policy information like ID, type, and renewal date.
* **Managers:** Manager information like ID, dealership ID, distributor ID, names, salary, and bonus (optional).
* **Regions:** Region information like ID, zip code, and name.
Learn more about the Monaco Motors schema [here](schema.md).
## Access Monaco Motors Schema (Web Browser)
You can access the databases using only your web browser.
### Server URL
navigate your browser to the following url or [click here](https://databases.softwareshinobi.com).
```
https://databases.softwareshinobi.com
```
Enter the username and password:
### Username
```
user: shinobi
```
### Password
```
user : shinobi
```
## Sharpen Your SQL Skills
Ready to level up your SQL skills and gain hands-on experience?
Dive into free resources to practice with the Monaco Motors database.
Get sharp. Stay sharp. Dominate.
[Databases & SQL 101](/Introduction-To-Databases).

138
docs/docs/schema.md

@ -0,0 +1,138 @@
# Monaco Motors Schema
This document describes the schema of the MONACO_MOTORS database, which appears to be a system for managing a high-end car dealership.
![Monaco Motors Schema](cover.png)
The data includes information about customers, sales agents, managers, distributors, vehicles, deals, insurances, and regions.
### Overview
The Monaco Motors schema consists of the following tables:
1. **Customer:** Stores customer information, including their ID, agent ID, first name, last name, phone number, and email.
2. **Deal:** Stores information about deals made, including the deal ID, vehicle ID, agent ID, customer ID, insurance ID (optional), and deal date.
3. **Dealership:** Stores information about dealerships, including their ID, distributor ID, region ID, region zip code, and dealership name.
4. **Distributor:** Stores information about distributors, including their ID and name.
5. **Insurance:** Stores information about insurance policies, including the ID, policy type, and renewal date.
6. **Manager:** Stores information about managers, including their ID, dealership ID, distributor ID, first name, last name, salary, and bonus (optional).
7. **Region:** Stores information about regions, including the ID, zip code, and name.
8. **Sales_Agent:** Stores information about sales agents, including their ID, manager ID, dealership ID, first name, last name, and salary.
9. **Vehicle:** Stores information about vehicles, including the ID, dealership ID, distributor ID, make, model, body type, model year, and price.
## Customer Table
Stores customer information, including their ID, agent ID, first name, last name, phone number, and email.
| Column Name | Data Type | Description |
|-------------------|-----------|----------------------------------------------|
| CustomerID | char(8) | Unique identifier for the customer |
| AgentID | char(8) | Foreign key referencing Sales_Agent.AgentID |
| CustFirstName | varchar(15)| Customer's first name |
| CustLastName | varchar(15)| Customer's last name |
| PhoneNumber | varchar(12)| Customer's phone number |
| Email | varchar(40)| Customer's email address |
## Deal Table
Stores information about deals made, including the deal ID, vehicle ID, agent ID, customer ID, insurance ID (optional), and deal date.
| Column Name | Data Type | Description |
|--------------|--------------------|---------------------------------------------------------|
| DealID | char(5) | Unique identifier for the deal |
| VehicleID | char(3) | Foreign key referencing Vehicle.VehicleID |
| AgentID | char(8) | Foreign key referencing Sales_Agent.AgentID |
| CustomerID | char(8) | Foreign key referencing Customer.CustomerID |
| InsuranceID | char(5) (optional) | Foreign key referencing Insurance.InsuranceID (optional) |
| DealDate | date | Date the deal was made |
## Dealership Table
Stores information about dealerships, including their ID, distributor ID, region ID, region zip code, and dealership name.
| Column Name | Data Type | Description |
|----------------|--------------------|-----------------------------------------------------------|
| DealershipID | char(5) | Unique identifier for the dealership |
| DistributorID | char(8) | Foreign key referencing Distributor.DistributorID |
| RegionID | char(3) | Foreign key referencing Region.RegionID |
| RegionZIP | char(5) | Zip code of the region |
| DealershipName | varchar(40) | Name of the dealership |
## Distributor Table
Stores information about distributors, including their ID and name.
| Column Name | Data Type | Description |
|----------------|--------------------|-------------------------------------------------|
| DistributorID | char(8) | Unique identifier for the distributor |
| DistributorName | varchar(40) | Name of the distributor |
## Insurance Table
Stores information about insurance policies, including the ID, policy type, and renewal date.
| Column Name | Data Type | Description |
|----------------|--------------------|---------------------------------------------------------|
| InsuranceID | char(5) | Unique identifier for the insurance policy |
| PolicyType | varchar(15) | Type of insurance policy (e.g., Full Coverage, Liability) |
| RenewalDate | date | Date the insurance policy needs to be renewed |
## Manager Table
Stores information about managers, including their ID, dealership ID, distributor ID, first name, last name, salary, and bonus (optional).
| Column Name | Data Type | Description |
|----------------|--------------------|-------------------------------------------------------------|
| ManagerID | char(8) | Unique identifier for the manager |
| DealershipID | char(5) | Foreign key referencing Dealership.DealershipID |
| DistributorID | char(8) | Foreign key referencing Distributor.DistributorID |
| MngrFirstName | varchar(15) | Manager's first name |
| MngrLastName | varchar(15) | Manager's last name |
| MngrSalary | decimal(8,2) | Manager's annual salary |
| MngrBonus | decimal(8,2) (optional) | Manager's annual bonus (optional) |
## Region Table
Stores information about regions, including the ID, zip code, and name.
| Column Name | Data Type | Description |
|----------------|--------------------|-------------------------------------------------|
| RegionID | char(3) | Unique identifier for the region |
| RegionZIP | char(5) | Zip code of the region |
| RegionName | varchar(15) | Name of the region |
## Sales_Agent Table
Stores information about sales agents, including their ID, manager ID, dealership ID, first name, last name, and salary.
| Column Name | Data Type | Description |
|----------------|--------------------|-------------------------------------------------------------|
| AgentID | char(8) | Unique identifier for the sales agent |
| ManagerID | char(8) | Foreign key referencing Manager.ManagerID |
| DealershipID | char(5) | Foreign key referencing Dealership.DealershipID |
| AgentFirstName | varchar(15) | Sales agent's first name |
| AgentLastName | varchar(15) | Sales agent's last name |
| AgentSalary | decimal(9,2) | Sales agent's annual salary |
## Vehicle Table
Stores information about vehicles, including the ID, dealership ID, distributor ID, make, model, body type, model year, and price.
| Column Name | Data Type | Description |
|----------------|--------------------|-----------------------------------------------------------|
| VehicleID | char(3) | Unique identifier for the vehicle |
| DealershipID | char(5) | Foreign key referencing Dealership.DealershipID |
| DistributorID | char(8) | Foreign key referencing Distributor.DistributorID |
| Make | varchar(40) | Make of the vehicle |
| Model | varchar(40) | Model of the vehicle |
| BodyType | varchar(40) | Body type of the vehicle |
| ModelYear | int(11) | Model year of the vehicle |
| Price | decimal(9,2) | Price of the vehicle |

49
docs/docs/styling.css

@ -0,0 +1,49 @@
ul.nav.navbar-nav.ml-auto {
background: purple;
display: none;
}
div p a {
background: #FF4742;
border: 1px solid #FF4742;
border-radius: 6px;
box-shadow: rgba(0, 0, 0, 0.1) 1px 2px 4px;
box-sizing: border-box;
color: #FFFFFF;
cursor: pointer;
display: inline-block;
font-family: nunito,roboto,proxima-nova,"proxima nova",sans-serif;
font-size: 16px;
font-weight: 800;
line-height: 16px;
min-height: 40px;
outline: 0;
padding: 12px 14px;
text-align: center;
text-rendering: geometricprecision;
text-transform: none;
user-select: none;
-webkit-user-select: none;
touch-action: manipulation;
vertical-align: middle;
}
p a:hover,
p a:active {
background-color: initial;
background-position: 0 0;
color: #FF4742;
}
p a:active {
opacity: .5;
}

21
docs/mkdocs.bash

@ -0,0 +1,21 @@
#!/bin/bash
##
reset;
clear;
##
set -e;
set -x;
##
#pkill mkdocs
#sleep 10
mkdocs serve

41
docs/mkdocs.yml

@ -0,0 +1,41 @@
docs_dir: docs
site_name: Shinobi Academy Database
##
## Find More Themes Here:
##
## https://mkdocs.github.io/mkdocs-bootswatch/
##
## List of theme values:
##
## mkdocs, readthedocs, material, cerulean, cosmo,
## cyborg, darkly, flatly, journal, litera, lumen, lux,
## materia, minty, pulse, sandstone, simplex, slate, solar,
## spacelab, superhero, united, yeti
##
theme:
name: material
features:
- navigation.top
- navigation.tabs
- navigation.sections
- toc.integrate
- toc.follow
- search.highlight
# Disable search and sidebars
palette:
primary: 'indigo'
accent: 'indigo'
features:
- navigation.tabs
- toc.integrate
- toc.follow
extra_css: [styling.css]

21
docs/provision.bash

@ -0,0 +1,21 @@
#!/bin/bash
##
reset;
clear;
##
set -e;
set -x;
##
pip install mkdocs-blog-plugin
pip install mkdocs-material
pip install mkdocs-bootswatch

0
LICENSE → license.md

77
readme.md

@ -0,0 +1,77 @@
# Home
SQL is like a secret code for databases. SQL helps you find hidden treasures in big data piles.
With the Monaco Motors database, you can practice your SQL ninja skills and become a SQL superstar.
Go on a luxury data adventure with the Monaco Motors Schema!
![SQL Query Tool](/docs/docs/cover.png)
This is a free and public MariaDB database schema for a fictional Monaco Motors dealership that sells high-end European cars. The Monaco Motors schema was made so that the "kode kiddies" learning SQL and databases have somewhere to play.
## Monaco Motors Overview
The Monaco Motors schema data provides details about customers, sales agents, deals, vehicles, distributors, insurance, managers, and regions.
You can use this data to analyze sales trends, identify top-performing agents, track inventory, and understand customer preferences.
It's a SQL learning growth for those who desire.
## Monaco Motors Tables
This is a database for a fictional Monaco Motors dealership that sells high-end European cars. The data covers various aspects of the dealership's operations, including:
* **Customers:** Customer information like ID, agent ID, name, phone number, and email.
* **Sales Agents:** Agent information like ID, manager ID, dealership ID, names, and salary.
* **Deals:** Deal information like ID, vehicle ID, agent ID, customer ID, insurance ID, and deal date.
* **Vehicles:** Vehicle information like ID, dealership ID, distributor ID, make, model, body type, model year, and price.
* **Distributors:** Distributor information like ID and name.
* **Insurance:** Insurance policy information like ID, type, and renewal date.
* **Managers:** Manager information like ID, dealership ID, distributor ID, names, salary, and bonus (optional).
* **Regions:** Region information like ID, zip code, and name.
Learn more about the Monaco Motors schema [here](/docs/docs/schema.md).
## Access Monaco Motors Schema (Web Browser)
You can access the databases using only your web browser.
### Server URL
navigate your browser to the following url or [click here](https://databases.softwareshinobi.digital).
```
https://databases.softwareshinobi.digital
```
Enter the username and password:
### Username
```
user: shinobi
```
### Password
```
user : shinobi
```
## Sharpen Your SQL Skills
Ready to level up your SQL skills and gain hands-on experience?
Dive into free resources to practice with the Monaco Motors database.
Get sharp. Stay sharp. Dominate.
[Databases & SQL 101](/docs/docs/Introduction-To-Databases/)
Loading…
Cancel
Save