SlideShare a Scribd company logo
1 of 1
Download to read offline
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

What's hot

Dimensional Modeling
Dimensional ModelingDimensional Modeling
Dimensional Modelingaksrauf
 
Simplifying Change Data Capture using Databricks Delta
Simplifying Change Data Capture using Databricks DeltaSimplifying Change Data Capture using Databricks Delta
Simplifying Change Data Capture using Databricks DeltaDatabricks
 
Dongwon Kim – A Comparative Performance Evaluation of Flink
Dongwon Kim – A Comparative Performance Evaluation of FlinkDongwon Kim – A Comparative Performance Evaluation of Flink
Dongwon Kim – A Comparative Performance Evaluation of FlinkFlink Forward
 
ETL Testing Training Presentation
ETL Testing Training PresentationETL Testing Training Presentation
ETL Testing Training PresentationApurba Biswas
 
Understanding sas data step processing.
Understanding sas data step processing.Understanding sas data step processing.
Understanding sas data step processing.Ravi Mandal, MBA
 
We Love Performance! How Tic Toc Games Uses ECS in Mobile Puzzle Games
We Love Performance! How Tic Toc Games Uses ECS in Mobile Puzzle GamesWe Love Performance! How Tic Toc Games Uses ECS in Mobile Puzzle Games
We Love Performance! How Tic Toc Games Uses ECS in Mobile Puzzle GamesUnity Technologies
 
Data Warehouse Fundamentals
Data Warehouse FundamentalsData Warehouse Fundamentals
Data Warehouse FundamentalsRashmi Bhat
 
Insertion sort : Sorting Analysis with Program and Algorithm
Insertion sort : Sorting Analysis with Program and AlgorithmInsertion sort : Sorting Analysis with Program and Algorithm
Insertion sort : Sorting Analysis with Program and AlgorithmSoumen Santra
 
123 system
123 system123 system
123 systemRobert R
 
C++ Restrictions for Game Programming.
C++ Restrictions for Game Programming.C++ Restrictions for Game Programming.
C++ Restrictions for Game Programming.Richard Taylor
 
世界の動画技術動向を見据えた AbemaTV の向かう先 / AbemaTV DevCon 2018 TrackA Final Session
世界の動画技術動向を見据えた AbemaTV の向かう先 / AbemaTV DevCon 2018 TrackA Final Session世界の動画技術動向を見据えた AbemaTV の向かう先 / AbemaTV DevCon 2018 TrackA Final Session
世界の動画技術動向を見据えた AbemaTV の向かう先 / AbemaTV DevCon 2018 TrackA Final SessionAbemaTV, Inc.
 

What's hot (13)

Dimensional Modeling
Dimensional ModelingDimensional Modeling
Dimensional Modeling
 
Simplifying Change Data Capture using Databricks Delta
Simplifying Change Data Capture using Databricks DeltaSimplifying Change Data Capture using Databricks Delta
Simplifying Change Data Capture using Databricks Delta
 
Dongwon Kim – A Comparative Performance Evaluation of Flink
Dongwon Kim – A Comparative Performance Evaluation of FlinkDongwon Kim – A Comparative Performance Evaluation of Flink
Dongwon Kim – A Comparative Performance Evaluation of Flink
 
ETL Testing Training Presentation
ETL Testing Training PresentationETL Testing Training Presentation
ETL Testing Training Presentation
 
Understanding sas data step processing.
Understanding sas data step processing.Understanding sas data step processing.
Understanding sas data step processing.
 
We Love Performance! How Tic Toc Games Uses ECS in Mobile Puzzle Games
We Love Performance! How Tic Toc Games Uses ECS in Mobile Puzzle GamesWe Love Performance! How Tic Toc Games Uses ECS in Mobile Puzzle Games
We Love Performance! How Tic Toc Games Uses ECS in Mobile Puzzle Games
 
Data Warehouse Fundamentals
Data Warehouse FundamentalsData Warehouse Fundamentals
Data Warehouse Fundamentals
 
Insertion sort : Sorting Analysis with Program and Algorithm
Insertion sort : Sorting Analysis with Program and AlgorithmInsertion sort : Sorting Analysis with Program and Algorithm
Insertion sort : Sorting Analysis with Program and Algorithm
 
glTF 2.0 Reference Guide
glTF 2.0 Reference GuideglTF 2.0 Reference Guide
glTF 2.0 Reference Guide
 
123 system
123 system123 system
123 system
 
C++ Restrictions for Game Programming.
C++ Restrictions for Game Programming.C++ Restrictions for Game Programming.
C++ Restrictions for Game Programming.
 
世界の動画技術動向を見据えた AbemaTV の向かう先 / AbemaTV DevCon 2018 TrackA Final Session
世界の動画技術動向を見据えた AbemaTV の向かう先 / AbemaTV DevCon 2018 TrackA Final Session世界の動画技術動向を見据えた AbemaTV の向かう先 / AbemaTV DevCon 2018 TrackA Final Session
世界の動画技術動向を見据えた AbemaTV の向かう先 / AbemaTV DevCon 2018 TrackA Final Session
 
Tableau data terminology
Tableau   data terminologyTableau   data terminology
Tableau data terminology
 

Similar to Sql cheat-sheet

Cheat sheet SQL commands with examples and easy understanding
Cheat sheet SQL commands with examples and easy understandingCheat sheet SQL commands with examples and easy understanding
Cheat sheet SQL commands with examples and easy understandingVivekanandaGN1
 
SQL 🌟🌟🔥.pdf
SQL 🌟🌟🔥.pdfSQL 🌟🌟🔥.pdf
SQL 🌟🌟🔥.pdfLightWolf2
 
SQL learning notes and all code.pdf
SQL learning notes and all code.pdfSQL learning notes and all code.pdf
SQL learning notes and all code.pdf79TarannumMulla
 
Discover the power of Recursive SQL and query transformation with Informix da...
Discover the power of Recursive SQL and query transformation with Informix da...Discover the power of Recursive SQL and query transformation with Informix da...
Discover the power of Recursive SQL and query transformation with Informix da...Ajay Gupte
 
SQL Quick Reference Card
SQL Quick Reference CardSQL Quick Reference Card
SQL Quick Reference CardTechcanvass
 
Simple Spreadsheet Tips
Simple Spreadsheet TipsSimple Spreadsheet Tips
Simple Spreadsheet TipsInside Access
 
DBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptxDBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptxjainendraKUMAR55
 
SQL Class Note By Amit Maity PowerPoint Presentation
SQL Class Note By Amit Maity PowerPoint PresentationSQL Class Note By Amit Maity PowerPoint Presentation
SQL Class Note By Amit Maity PowerPoint Presentationmaitypradip938
 
Prabu's sql quries
Prabu's sql quries Prabu's sql quries
Prabu's sql quries Prabu Cse
 
Most useful queries
Most useful queriesMost useful queries
Most useful queriesSam Depp
 
Introduction to sql new
Introduction to sql newIntroduction to sql new
Introduction to sql newSANTOSH RATH
 
Mysql 120831075600-phpapp01
Mysql 120831075600-phpapp01Mysql 120831075600-phpapp01
Mysql 120831075600-phpapp01sagaroceanic11
 
Table partitioning in PostgreSQL + Rails
Table partitioning in PostgreSQL + RailsTable partitioning in PostgreSQL + Rails
Table partitioning in PostgreSQL + RailsAgnieszka Figiel
 
2. DBMS Experiment - Lab 2 Made in SQL Used
2. DBMS Experiment - Lab 2 Made in SQL Used2. DBMS Experiment - Lab 2 Made in SQL Used
2. DBMS Experiment - Lab 2 Made in SQL UsedTheVerse1
 

Similar to Sql cheat-sheet (20)

1670595076250.pdf
1670595076250.pdf1670595076250.pdf
1670595076250.pdf
 
Cheat sheet SQL commands with examples and easy understanding
Cheat sheet SQL commands with examples and easy understandingCheat sheet SQL commands with examples and easy understanding
Cheat sheet SQL commands with examples and easy understanding
 
SQL 🌟🌟🔥.pdf
SQL 🌟🌟🔥.pdfSQL 🌟🌟🔥.pdf
SQL 🌟🌟🔥.pdf
 
SQL learning notes and all code.pdf
SQL learning notes and all code.pdfSQL learning notes and all code.pdf
SQL learning notes and all code.pdf
 
Discover the power of Recursive SQL and query transformation with Informix da...
Discover the power of Recursive SQL and query transformation with Informix da...Discover the power of Recursive SQL and query transformation with Informix da...
Discover the power of Recursive SQL and query transformation with Informix da...
 
dbms.pdf
dbms.pdfdbms.pdf
dbms.pdf
 
SQL Quick Reference Card
SQL Quick Reference CardSQL Quick Reference Card
SQL Quick Reference Card
 
Simple Spreadsheet Tips
Simple Spreadsheet TipsSimple Spreadsheet Tips
Simple Spreadsheet Tips
 
Assignment#02
Assignment#02Assignment#02
Assignment#02
 
DBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptxDBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptx
 
Sql
SqlSql
Sql
 
SQL Class Note By Amit Maity PowerPoint Presentation
SQL Class Note By Amit Maity PowerPoint PresentationSQL Class Note By Amit Maity PowerPoint Presentation
SQL Class Note By Amit Maity PowerPoint Presentation
 
Prabu's sql quries
Prabu's sql quries Prabu's sql quries
Prabu's sql quries
 
Most useful queries
Most useful queriesMost useful queries
Most useful queries
 
Introduction to sql new
Introduction to sql newIntroduction to sql new
Introduction to sql new
 
Mysql 120831075600-phpapp01
Mysql 120831075600-phpapp01Mysql 120831075600-phpapp01
Mysql 120831075600-phpapp01
 
SQL
SQLSQL
SQL
 
Table partitioning in PostgreSQL + Rails
Table partitioning in PostgreSQL + RailsTable partitioning in PostgreSQL + Rails
Table partitioning in PostgreSQL + Rails
 
Technical
TechnicalTechnical
Technical
 
2. DBMS Experiment - Lab 2 Made in SQL Used
2. DBMS Experiment - Lab 2 Made in SQL Used2. DBMS Experiment - Lab 2 Made in SQL Used
2. DBMS Experiment - Lab 2 Made in SQL Used
 

Recently uploaded

S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxSCMS School of Architecture
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueBhangaleSonal
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdfKamal Acharya
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationBhangaleSonal
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsvanyagupta248
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdfAldoGarca30
 
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxHOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxSCMS School of Architecture
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesMayuraD1
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Arindam Chakraborty, Ph.D., P.E. (CA, TX)
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayEpec Engineered Technologies
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadhamedmustafa094
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdfKamal Acharya
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARKOUSTAV SARKAR
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxmaisarahman1
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Call Girls Mumbai
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTbhaskargani46
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdfKamal Acharya
 

Recently uploaded (20)

S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech students
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
 
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxHOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal load
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdf
 

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