SlideShare a Scribd company logo
SQL cheat sheet
Basic Queries
Views
-- filter your columns
SELECT col1, col2, col3, ... FROM table1
-- filter the rows
WHERE col4 = 1 AND col5 = 2
-- aggregate the data
GROUP by …
-- limit aggregated data
HAVING count(*) > 1
-- order of the results
ORDER BY col2
Useful keywords for SELECTS:
DISTINCT - return unique results
BETWEEN a AND b - limit the range, the values can be
numbers, text, or dates
LIKE - pattern search within the column text
IN (a, b, c) - check if the value is contained among given.
Data Modification
-- update specific data with the WHERE clause
UPDATE table1 SET col1 = 1 WHERE col2 = 2
-- insert values manually
INSERT INTO table1 (ID, FIRST_NAME, LAST_NAME)
VALUES (1, ‘Rebel’, ‘Labs’);
-- or by using the results of a query
INSERT INTO table1 (ID, FIRST_NAME, LAST_NAME)
SELECT id, last_name, first_name FROM table2
A VIEW is a virtual table, which is a result of a query.
They can be used to create virtual tables of complex queries.
CREATE VIEW view1 AS
SELECT col1, col2
FROM table1
WHERE …
The Joy of JOINs
A B A B
RIGHT OUTER JOIN - all rows from table B,
even if they do not exist in table A
INNER JOIN - fetch the results that
exist in both tables
LEFT OUTER JOIN - all rows from table A,
even if they do not exist in table B
Updates on JOINed Queries
You can use JOINs in your UPDATEs
UPDATE t1 SET a = 1
FROM table1 t1 JOIN table2 t2 ON t1.id = t2.t1_id
WHERE t1.col1 = 0 AND t2.col2 IS NULL;
NB! Use database specific syntax, it might be faster!
Semi JOINs
You can use subqueries instead of JOINs:
SELECT col1, col2 FROM table1 WHERE id IN
(SELECT t1_id FROM table2 WHERE date >
CURRENT_TIMESTAMP)
Indexes
If you query by a column, index it!
CREATE INDEX index1 ON table1 (col1)
Don’t forget:
Avoid overlapping indexes
Avoid indexing on too many columns
Indexes can speed up DELETE and UPDATE operations
Reporting
Use aggregation functions
COUNT - return the number of rows
SUM - cumulate the values
AVG - return the average for the group
MIN / MAX - smallest / largest value
Useful Utility Functions
-- convert strings to dates:
TO_DATE (Oracle, PostgreSQL), STR_TO_DATE (MySQL)
-- return the first non-NULL argument:
COALESCE (col1, col2, “default value”)
-- return current time:
CURRENT_TIMESTAMP
-- compute set operations on two result sets
SELECT col1, col2 FROM table1
UNION / EXCEPT / INTERSECT
SELECT col3, col4 FROM table2;
Union -	 returns data from both queries
Except -	 rows from the first query that are not present
	 in the second query
Intersect - rows that are returned from both queries

More Related Content

PPTX
What is Link list? explained with animations
PPT
Java exception
PDF
Java arrays
PPT
Database Relationships
PDF
SQL JOINS
PPT
Sequences and indexes
PPT
List in java
DOCX
Base tables for order to cash
What is Link list? explained with animations
Java exception
Java arrays
Database Relationships
SQL JOINS
Sequences and indexes
List in java
Base tables for order to cash

What's hot (20)

PDF
Concurrency control
PDF
Object Based Databases
PPT
Polymorphism in java, method overloading and method overriding
ODP
Introduction to triggers
PDF
OOAD - UML - Sequence and Communication Diagrams - Lab
PDF
Cursors
PPTX
Abstract class and Interface
PPT
ASP.NET 08 - Data Binding And Representation
PPT
PPTX
Triggers o disparadores
PDF
Classification in Data Mining
PDF
PL-SQL, Cursors & Triggers
PPTX
Singly & Circular Linked list
PPT
Design rule 3
PDF
OOP Assignment 03.pdf
PPT
Types of Load distributing algorithm in Distributed System
PPT
Graph traversal-BFS & DFS
PPSX
Parallel Database
PDF
Oracle R12 Multi org ivas
Concurrency control
Object Based Databases
Polymorphism in java, method overloading and method overriding
Introduction to triggers
OOAD - UML - Sequence and Communication Diagrams - Lab
Cursors
Abstract class and Interface
ASP.NET 08 - Data Binding And Representation
Triggers o disparadores
Classification in Data Mining
PL-SQL, Cursors & Triggers
Singly & Circular Linked list
Design rule 3
OOP Assignment 03.pdf
Types of Load distributing algorithm in Distributed System
Graph traversal-BFS & DFS
Parallel Database
Oracle R12 Multi org ivas
Ad

Similar to Sql cheat-sheet (20)

PDF
SQL learning notes and all code.pdf
PDF
1670595076250.pdf
PDF
Cheat sheet SQL commands with examples and easy understanding
PDF
SQL 🌟🌟🔥.pdf
PDF
Discover the power of Recursive SQL and query transformation with Informix da...
PDF
dbms.pdf
PDF
SQL Quick Reference Card
PDF
Simple Spreadsheet Tips
PDF
Assignment#02
PPTX
DBMS and SQL(structured query language) .pptx
PPTX
SQL Class Note By Amit Maity PowerPoint Presentation
ODP
Prabu's sql quries
DOC
Most useful queries
PPT
Lab_04.ppt opreating system of computer lab
PPTX
Introduction to sql new
PPT
Mysql 120831075600-phpapp01
PPTX
PDF
Table partitioning in PostgreSQL + Rails
DOCX
Technical
SQL learning notes and all code.pdf
1670595076250.pdf
Cheat sheet SQL commands with examples and easy understanding
SQL 🌟🌟🔥.pdf
Discover the power of Recursive SQL and query transformation with Informix da...
dbms.pdf
SQL Quick Reference Card
Simple Spreadsheet Tips
Assignment#02
DBMS and SQL(structured query language) .pptx
SQL Class Note By Amit Maity PowerPoint Presentation
Prabu's sql quries
Most useful queries
Lab_04.ppt opreating system of computer lab
Introduction to sql new
Mysql 120831075600-phpapp01
Table partitioning in PostgreSQL + Rails
Technical
Ad

Recently uploaded (20)

PPTX
Geodesy 1.pptx...............................................
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PPTX
Sustainable Sites - Green Building Construction
PDF
Structs to JSON How Go Powers REST APIs.pdf
PDF
Arduino robotics embedded978-1-4302-3184-4.pdf
PDF
Digital Logic Computer Design lecture notes
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPTX
CH1 Production IntroductoryConcepts.pptx
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PPTX
Internet of Things (IOT) - A guide to understanding
PPTX
web development for engineering and engineering
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PDF
composite construction of structures.pdf
PPTX
Construction Project Organization Group 2.pptx
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
Geodesy 1.pptx...............................................
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
Sustainable Sites - Green Building Construction
Structs to JSON How Go Powers REST APIs.pdf
Arduino robotics embedded978-1-4302-3184-4.pdf
Digital Logic Computer Design lecture notes
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
CH1 Production IntroductoryConcepts.pptx
Embodied AI: Ushering in the Next Era of Intelligent Systems
Internet of Things (IOT) - A guide to understanding
web development for engineering and engineering
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
composite construction of structures.pdf
Construction Project Organization Group 2.pptx
OOP with Java - Java Introduction (Basics)
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
CYBER-CRIMES AND SECURITY A guide to understanding

Sql cheat-sheet

  • 1. SQL cheat sheet Basic Queries Views -- filter your columns SELECT col1, col2, col3, ... FROM table1 -- filter the rows WHERE col4 = 1 AND col5 = 2 -- aggregate the data GROUP by … -- limit aggregated data HAVING count(*) > 1 -- order of the results ORDER BY col2 Useful keywords for SELECTS: DISTINCT - return unique results BETWEEN a AND b - limit the range, the values can be numbers, text, or dates LIKE - pattern search within the column text IN (a, b, c) - check if the value is contained among given. Data Modification -- update specific data with the WHERE clause UPDATE table1 SET col1 = 1 WHERE col2 = 2 -- insert values manually INSERT INTO table1 (ID, FIRST_NAME, LAST_NAME) VALUES (1, ‘Rebel’, ‘Labs’); -- or by using the results of a query INSERT INTO table1 (ID, FIRST_NAME, LAST_NAME) SELECT id, last_name, first_name FROM table2 A VIEW is a virtual table, which is a result of a query. They can be used to create virtual tables of complex queries. CREATE VIEW view1 AS SELECT col1, col2 FROM table1 WHERE … The Joy of JOINs A B A B RIGHT OUTER JOIN - all rows from table B, even if they do not exist in table A INNER JOIN - fetch the results that exist in both tables LEFT OUTER JOIN - all rows from table A, even if they do not exist in table B Updates on JOINed Queries You can use JOINs in your UPDATEs UPDATE t1 SET a = 1 FROM table1 t1 JOIN table2 t2 ON t1.id = t2.t1_id WHERE t1.col1 = 0 AND t2.col2 IS NULL; NB! Use database specific syntax, it might be faster! Semi JOINs You can use subqueries instead of JOINs: SELECT col1, col2 FROM table1 WHERE id IN (SELECT t1_id FROM table2 WHERE date > CURRENT_TIMESTAMP) Indexes If you query by a column, index it! CREATE INDEX index1 ON table1 (col1) Don’t forget: Avoid overlapping indexes Avoid indexing on too many columns Indexes can speed up DELETE and UPDATE operations Reporting Use aggregation functions COUNT - return the number of rows SUM - cumulate the values AVG - return the average for the group MIN / MAX - smallest / largest value Useful Utility Functions -- convert strings to dates: TO_DATE (Oracle, PostgreSQL), STR_TO_DATE (MySQL) -- return the first non-NULL argument: COALESCE (col1, col2, “default value”) -- return current time: CURRENT_TIMESTAMP -- compute set operations on two result sets SELECT col1, col2 FROM table1 UNION / EXCEPT / INTERSECT SELECT col3, col4 FROM table2; Union - returns data from both queries Except - rows from the first query that are not present in the second query Intersect - rows that are returned from both queries