Hello friend! Are you looking to step up your SQL query game? As an experienced database developer, let me walk you through this comprehensive SQL cheat sheet.
Whether you‘re just getting started with database programming or have some experience under your belt, having a quick reference guide for SQL commands and syntax can save you tons of time and headaches!
In this guide, I‘ll provide easy to digest code snippets and examples for essential SQL statements, functions, joins and more. My goal is to break down complex concepts into bite-sized pieces that you can bookmark and refer to anytime.
Let‘s get started!
A Brief History of SQL
SQL, which stands for Structured Query Language, has an interesting history. It was originally developed by IBM researchers in the early 1970s for managing data in relational database systems.
The language went through a standards process in 1986 when SQL became an ANSI standard. It was later also standardized by ISO in 1987. So SQL is technically short for ANSI SQL or ISO SQL!
Today, SQL powers many of the popular database engines used around the world from Oracle and Microsoft SQL Server to open source platforms like MySQL, PostgreSQL and more. It has become the ubiquitous language for not only database administrators but software developers, data analysts, data scientists and others working with relational data.
With the rise of big data, SQL remains an integral part of the data professional‘s toolkit even when working with non-relational databases. The ability to query, analyze and manipulate large datasets is key.
Which brings me to…why this SQL cheat sheet guide can be so valuable.
SQL Statements for Managing Databases
SQL statements are instructions used to define schema, manipulate and access data within relational databases.
There are several categories of SQL statements we‘ll cover:
Data Definition Language
DDL or Data Definition Language statements are used to configure database structure and objects.
Some examples:
-- Create new table
CREATE TABLE customers (
id INT PRIMARY KEY,
name VARCHAR(50)
);
-- Add column to existing table
ALTER TABLE customers
ADD email VARCHAR(100);
-- Delete entire table
DROP TABLE customers;
As you can see, these statements allow you to build the schema of a database by creating tables, indexes, procedures and more. Plus alter or delete objects when needed.
Now let‘s see how to work with the data itself…
Manipulating Data
Data Manipulation Language or DML offers statements that allow you to query, insert, update and delete actual rows of data:
-- Insert new row
INSERT INTO customers (id, name, email)
VALUES (1, ‘Jane Smith‘, ‘[email protected]‘);
-- Retrieve data
SELECT *
FROM customers
WHERE id = 1;
-- Update
UPDATE customers
SET email = ‘[email protected]‘
WHERE id = 1;
-- Delete row
DELETE FROM customers
WHERE id = 1;
This makes it really easy to perform full CRUD (create, read, update, delete) operations!
Now that you‘ve seen the basics, let‘s look at some…
Advanced Statements
In addition to core DDL and DML statements, SQL offers additional statements for transactions, access control and stored procedures:
-- Transactions
BEGIN TRANSACTION;
UPDATE customers
SET name = ‘Jane Smith‘
WHERE id = 1;
COMMIT TRANSACTION;
-- Privileges
GRANT SELECT ON customers TO john;
REVOKE SELECT ON customers FROM john;
-- Stored procedures
CREATE PROCEDURE get_customer
AS
SELECT * FROM customers;
Now let‘s shift gears and talk about…
Built-in SQL Functions
SQL provides a vast library of built-in functions that allow you to transform, summarize and analyze data without needing to write complex procedures.
They save tons of time!
Here are just a few I use often:
Aggregate functions
-- Total customers
SELECT COUNT(id) FROM customers;
-- Highest revenue
SELECT MAX(revenue) FROM orders;
Scalar functions
-- Make uppercase
SELECT UPPER(name) FROM customers;
-- Date difference
SELECT DATEDIFF(DAY, start_date, end_date) AS days
FROM projects;
Analytic functions
-- Rank customers by revenue
SELECT
name, revenue,
RANK() OVER (ORDER BY revenue DESC) rank
FROM customers;
I‘ve just scratched the surface here showing you a few string, numeric and date functions. SQL defines dozens more that you‘ll find handy.
Now let‘s look at combining data from different sources using…
SQL Joins
One of the most powerful features of relational databases is the ability to match data from multiple tables using joins. This allows you to stitch together data and create interesting aggregates and analysis.
Here‘s a quick visual of joins:
And examples joining a orders table to the customers table to show order total by customer:
SELECT
c.name,
SUM(o.total) revenue
FROM customers c
INNER JOIN orders o
ON o.cust_id = c.id
GROUP BY c.name;
The join predicate allows you to match disparate datasets very easily either using primary keys, foreign keys or other columns.
There are several types of joins (inner, left outer, right outer, etc) each serving various needs to shape your result set.
Additional Tips for Expert Queries
I want to wrap up by sharing some best practices I‘ve learned for writing optimized SQL queries.
Formatting
Proper indentation and line spacing improves readability and maintainability:
SELECT
c.name,
SUM(o.total) revenue
FROM
customers c
INNER JOIN orders o
ON o.cust_id = c.id
GROUP BY
c.name;
Descriptive Names
Use consistent schemes and descriptive names for databases, tables and columns:
SELECT
customers.first_name,
orders.total_amount
FROM
TBL_CUSTOMERS customers
INNER JOIN TBL_ORDERS orders
ON customers.id = orders.cust_id
Comments
Liberal use of comments explain sections of SQL queries:
-- Join customer and order tables
SELECT
c.name,
o.total_amount
FROM
customers c
INNER JOIN
orders o
-- Match on customer id
ON c.id = o.cust_id
Testing & Performance
Check execution plans, optimize indexes, check performance with test data.
Following best practices will allow you to write robust, optimized SQL code.
I hope you‘ve found this guide helpful my friend! SQL can seem daunting but is quite easy to learn. This cheat sheet gave you a sampler of essential statements, functions and joins that will enable you to start querying databases like a pro!
Let me know if you have any other questions. Just drop me a line anytime.
Happy querying!