Show Menu
Cheatography

SQL Cheat Sheet (DRAFT) by

I'm starting a new job and need to remember the basics. :)

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Very basic introd­uction

Databases are organized collec­tions of inform­ation or data. They can be non-re­lai­tonal (MongoDB, Oracle NoSQL) or relational (MySQL, Microsoft SQL Server, Oracle Database).

Non-re­lat­ional databases store data in a non-ta­bular form and tend do be more flexibnle than the tradit­ional relational databases. They are often used when large quantities of complex and diverse data neds to be organized. There are 4 major types of NoSQL databases: document databases, key-value databases, wide-c­olumn stores, graph databases.

Relational databases is a structure databa­sethat contians tables related to each other through keys.
-Primary keys: unique identi­fiers therefore cannot have duplicates or null values.
-Foreign keys: column in a table that it's the primary key in another table.

This document will focus on relational DB.

Query is a request for data. Nearly all relational databases rely on a version of SQL to query data.

Types of queries:
- DDL (data definition language)
- DQL (data query language)
- DML (data manipu­lation language)
- DCL (data control language)
- TCL (trans­action control language)

Relational Algebra symbols

null
reunion
inters­ection
*
cartesian product
Π
projection
σ
selection
junction
semi-j­unction
∪ reunion --> all; ∩ inters­ection --> middle ones; Π projection --> cuts columns; σ selection --> filters lines; ⋈ junction --> joins tables

Eg:
ΠBI, sigla [σQuota>­20^­Sigla <>’KB’ (Pratica)] --> The BI and Siglas of all the sports (table Prativa) that cost more than 20, except KB.
ΠNome[σsigla = ‘KB’ (Sócios ⋈ Pratica)] --> name of all the people who do KB.

https:­//d­ocs.go­ogl­e.c­om/­doc­ume­nt/­d/1­_70­Gyk­fmT­wcu­9TJ­6Ji­5um­-Ix­g2A­7_V­T2/edit

DQL Joining tables

Tables are joined by a commun column (SELECT columns, FROM table1 INNER JOIN table 2 ON table1.co­lum­n=t­abl­e2.c­olumn)

For reunion: (SELECT columnname FROM tablename) UNION (SELECT columname FROM table2­name)

For inters­ection (SELECT columname FROM tablename) INTERSECT (SELECT columname FROM table2­name)

On access: - use NATURAL JOIN (for inner join);

Image source: https:­//w­ww.r­ed­dit.co­m/r­/SQ­L/c­omm­ent­s/2­zb1­i0/­sql­_se­rve­r_j­oin­_ty­pes­_po­ste­r_v­ers­ion_2/

BD Example

DDL

CREATE TABLE tablename (colum­nname type column­res­tri­ction, columnmae2 type column­res­tri­ction, ...);
creates a table
CREATE INDEX name ON tablen­ame­(column asc, column desc,...);
explicit creation of index (for efficiency for ex). Unique and primary keys will automa­tically create indexes!
DROP TABLE tablename
deletes tables if there are no references to thi table ou if these specify ON DELETE CASCADE. In this case, it deletes the table and all the reference lines on the other tables that refer to the deleted table
CREATE VIEW
creates a view that can be used as a table
Types:varch­ar2(n) = string of n characters variable size 1<4000, char(n) = string of n characters fixed size 1<255, number­(p,s), date, timest­amp...
Column restri­ctions: none, primary key, not null,u­nique, refere­nces, check. Table restri­ctions: primary key(col, col...), foreign key(co­l,c­ol..), check, refere­nces. All these depend on the db.

DML

Insertion
INSERT INTO tablename VALUES­(val, val, val...)
adds a line with all the values in the specified order
 
INSERT INTO tablen­am(­col­,co­l...) VALUES­(va­l,v­al...)
adds a line only with the values for the specificed columns
Modifi­cation
UPDTAE tablename SET col1=e­xpr1, col2=e­xprs2 WHERE cond
all the lines that meet the cond have the col1 and col2 updated ccroding to the exr1 and expr2
Deletition
DELETE FROM tablename WHERE cond
deletes all the line in the table that meet the cond
The changes stay in a temporary state. To commit them perman­ently execut COMMIT. To undo the changes after the last commit do ROLLBACK.

It's possible to create sequences to automa­tically create values.Eg­:create sequence num_socio start with 1000 increment by 10;insert into sócios values( num_so­cio.ne­xtval, 'Quim' );select num_so­cio.cu­rrval from dual; --> Crie uma sequência para gerar automa­tic­amente números de sócios
 

UML to SQL

Operators, Patterns & Symbols

+
plus
-
minus
*
times
/
divided
||
concat­enation
=
equal to
<>
different
!=
different
>
greater than
<
less than
>=
greater than or equal to
<=
less than or equal to
[not] in
belongs [doesn't belong]]
[not] between x and y
x <= value <= y [not]
x [not] like y
compares x to y
is [not] null
is[n't] null
not
not
and
and
or
or
*
everyt­hin­g/all
_
any letter (only 1)
%
any sequence of characters
( )
fits queries inside other queries
distinct
eliminates duplicate rows
' ' - use for words

'M%' = Marina, M...

'M_r%' = Mar, Mari, Moreira...

'a__' = ant, add, alc....

On Microsoft Access use * (instead of %) and ? (instead of _)

Order of precedence:
1. Arithmetic operators (+ and - > * and / > ||)
2. Compar­asion operators
3. Logic operators (not > and > or)

( ) --> SELEC by, salario FROM orienta WHERE salario = (SELECT max(sa­lario) FROM orienta);

DQL Basics

SELECT rowname(s) FROM table name
displays all the info from the table on the row(s)
SELECT x FROM y WHERE anycri­teria
displays all the x info, from table y, that meets the criteria
SELECT x FROM y WHERE criteria1 AND criteria2
diplays all the x info from table y, that meets the criteria 1 and 2
SELECT x, j FROM y ORDER BY j
displays all the x and j row's info, from y table, ordered by j
SELECT x, i FROM y GROUP BY x
displays the x and i info from table y, organized by x groups
SELECT x, i FROM y GROUP BY x HAVING criteria
displays the x and i info from table y that fits the criteria, organized by the x.
ORDER BY applies to strings (alpha­bet­ically) and numbers (asc), and applies for more than one rows. Use desc to order backwards (SELECT x, j, i FROM y ORDER BY i, j desc).
GROUP BY organizes rows by a specific column.
Example: SELECT id, avg(cl­ass­ifi­cation) as grade FROM students GROUP BY id --> will calculate the average classi­fic­ation by id, taking that into account for the result on the grades column for ids that appear more than once.

DQL Simple calcul­ations

SELECT avg(co­lum­nname) as newcol­umnname FROM tablename
displays the average result of the numbers in the column of the table chosen in a new columns called newcol­umnname
SELECT count
displays the number of rows on columname
SELECT sum
displays the addition of the numbers on the row
SELECT max
displays the higher number on the column
SELECT min
displays the smaller number
All of these can be used together (SELECT avg(x) as newname1, max(x) as newname2 FROM tablen­ame;).

These are useful for as an example finding the average (avg) of a column, to count the total of rows of a column (count), the total of the values (sum) and the max and min numbers.

DQL - others

rownum
n. of the row for the resulting table
rowid
internal ddress for the row/line on the db
case --- when --- else --- end as
turns quanti­tative results into qualit­ative
nvl(va­luex, valueI­fNule)
returns 'valuex' if it's not null and valueI­fNule if valuex is null
eg:SELECT rownum, rowid, column1, column3 FROM table; and "­SELECT column­name, column­2name, CASE column­3name WHEN n. THEN 'expre­ssion' WHEN othern. THEN 'other­exp­res­sion' ELSE 'anoth­ere­xpr­ession' END AS newcol­umnname FROM table; Rownum limits results to the first n lines for extensive outputs, while rowid allows quick access but is affected by import­/export operat­ions. NVL is also used as NVL(t, s, n), returning S if T is positive, otherwise N.

DCL

GRANT privil­egetype (col1, col2) ON tablename TO username WITH granto­ption
Types of privilege: alter, delete, execute, index, insert, read, refere­nces, select, update, create session, alter sesson, drop any table. Thrse apply to tables, viws, sequences, functions, packages, system and/or users.

Tehcnical support position

What type of queries are the most common on a technical support role? In this role, the most commonly used queries often involve retrieving and updating inform­ation related to users, tickets, issues, and system logs; data retrieval and correc­tion; account manage­ment; config­uration changes; audit trail analysis; perfor­mance tunign; report genera­tion; data import­/export issues. Egs:

1- Retrieve ticket inform­ation: SELECT * FROM tickets WHERE ticket_id = 'XYZ'
2- Updtate ticket status: UPDATE tickets SET status = 'closed' WHERE ticket_id = 'XYZ'
3. Review system logs to identify patterns or isues affecting multiple users. SELECT * FROM system­_logs WHERE log_type = 'Error' ORDER BY timestamp DESC LIMIT 10
4. Track user activity and intera­ctions withthe system for troubl­esh­ooting purposes. SELECT * FROM user_a­ctivity WHERE user_id = 'ABC' ORDER BY timestamp DESC LIMIT 10
5. Update user inform­ation. UPDATE users SET email = 'new_e­mai­l@e­xam­ple.com' WHERE user_id = 'ABC'
6. Check the status of a service. SELECT * FROM servic­e_s­ttaus WHERE status = 'Down';
7. Retrieve FAQ inform­ation from a knowledge base or faq database to provide quick solutions to common issues. SELECT * FROM faq WHERE category ='Triu­ble­sho­oting'.
8. User authen­tic­ation issues: check if user's creden­tials are valid. SELECT * FROM users WHERE username ='user123' AND password= ' hashed­_pa­ssword'
9. Reset user passwords. UPDATE users SET password = 'new_h­she­d_p­ass­word' WHERE username = 'user123'
10. Check system resource usage: monitor resource usage to identify potencial perfor­mance issues. SELECT * FROM system­_re­sources WHERE resour­ce_type = 'cpu' AND usage_­per­centage > 90;
11. Check recent system updates. SELECT * FROM system­_up­dates ORDER BY update­_date DESC LIMIT 10