SQL Basics Cheat Sheet (2024)

Download this 2-page SQL Basics Cheat Sheet in PDF or PNG format, print it out, and stick to your desk.

The SQL Basics Cheat Sheet provides you with the syntax of all basics clauses, shows you how to write different conditions, and has examples. You can download this cheat sheet as follows:

  • SQL
  • Sample Data
  • Querying Single Table
  • Aliases
    • Columns
    • Tables
  • Filtering The Output
    • Comparison Operators
    • Text Operators
    • Other Operators
  • Querying Multiple Tables
    • INNER JOIN
    • LEFT JOIN
    • RIGHT JOIN
    • FULL JOIN
    • CROSS JOIN
    • NATURAL JOIN
  • Aggregation and Grouping
    • Aggregate Functions
    • Example Queries
  • Subqueries
    • Single Value
    • Multiple Values
    • Correlated
  • Set Operations
    • UNION
    • INTERSECT
    • EXCEPT

SQL

SQL, or Structured Query Language, is a language to talk to databases. It allows you to select specific data and to build complex reports. Today, SQL is a universal language of data. It is used in practically all technologies that process data.

SAMPLE DATA

SQL Basics Cheat Sheet (1)

QUERYING SINGLE TABLE

Fetch all columns from the country table:

SELECT *FROM country;

Fetch id and name columns from the city table:

SELECT id, nameFROM city;

Fetch city names sorted by the rating column in the default ASCending order:

SELECT nameFROM cityORDER BY rating [ASC];

Fetch city names sorted by the rating column in the DESCending order:

SELECT nameFROM cityORDER BY rating DESC;

Learn SQL by actually writing SQL code. Complete 129 interactive exercises in our SQL Basics course and gain confidence in your coding skills.

Aliases

Columns

SELECT name AS city_nameFROM city;

Tables

SELECT co.name, ci.nameFROM city AS ciJOIN country AS co ON ci.country_id = co.id;

FILTERING THE OUTPUT

COMPARISON OPERATORS

Fetch names of cities that have a rating above 3:

SELECT nameFROM cityWHERE rating > 3;

Fetch names of cities that are neither Berlin nor Madrid:

SELECT nameFROM cityWHERE name != 'Berlin' AND name != 'Madrid';

TEXT OPERATORS

Fetch names of cities that start with a 'P' or end with an 's':

SELECT nameFROM cityWHERE name LIKE 'P%' OR name LIKE '%s';

Fetch names of cities that start with any letter followed by'ublin' (like Dublin in Ireland or Lublin in Poland):

SELECT nameFROM cityWHERE name LIKE '_ublin';

OTHER OPERATORS

Fetch names of cities that have a population between 500K and 5M:

SELECT nameFROM cityWHERE population BETWEEN 500000 AND 5000000;

Fetch names of cities that don't miss a rating value:

SELECT nameFROM cityWHERE rating IS NOT NULL;

Fetch names of cities that are in countries with IDs 1, 4, 7, or 8:

SELECT nameFROM cityWHERE country_id IN (1, 4, 7, 8);

QUERYING MULTIPLE TABLES

INNER JOIN

JOIN (or explicitly INNER JOIN) returns rows that have matching values in both tables.

SELECT city.name, country.nameFROM city[INNER] JOIN country ON city.country_id = country.id;
SQL Basics Cheat Sheet (2)

LEFT JOIN

LEFT JOIN returns all rows from the left table with corresponding rows from the right table. If there's no matching row, NULLs are returned as values from the second table.

SELECT city.name, country.nameFROM cityLEFT JOIN country ON city.country_id = country.id;
SQL Basics Cheat Sheet (3)

RIGHT JOIN

RIGHT JOIN returns all rows from the right table with corresponding rows from the left table. If there's no matching row, NULLs are returned as values from the left table.

SELECT city.name, country.nameFROM cityRIGHT JOIN country ON city.country_id = country.id;
SQL Basics Cheat Sheet (4)

FULL JOIN

FULL JOIN (or explicitly FULL OUTER JOIN) returns all rows from both tables – if there's no matching row in the second table, NULLs are returned.

SELECT city.name, country.nameFROM cityFULL [OUTER] JOIN country ON city.country_id = country.id;
SQL Basics Cheat Sheet (5)

CROSS JOIN

CROSS JOIN returns all possible combinations of rows from both tables. There are two syntaxes available.

SELECT city.name, country.nameFROM cityCROSS JOIN country;SELECT city.name, country.nameFROM city, country;
SQL Basics Cheat Sheet (6)

NATURAL JOIN

NATURAL JOIN will join tables by all columns with the same name.

SELECT city.name, country.nameFROM cityNATURAL JOIN country;
SQL Basics Cheat Sheet (7)

NATURAL JOIN used these columns to match rows:
city.id, city.name, country.id, country.name.
NATURAL JOIN is very rarely used in practice.

AGGREGATION AND GROUPING

GROUP BY groups together rows that have the same values in specified columns. It computes summaries (aggregates) for each unique combination of values.

SQL Basics Cheat Sheet (8)

AGGREGATE FUNCTIONS

  • avg(expr) − average value for rows within the group
  • count(expr) − count of values for rows within the group
  • max(expr) − maximum value within the group
  • min(expr) − minimum value within the group
  • sum(expr) − sum of values within the group

The best way to learn SQL is through practice. Try out our interactive SQL Basics course.

EXAMPLE QUERIES

Find out the number of cities:

SELECT COUNT(*)FROM city;

Find out the number of cities with non-null ratings:

SELECT COUNT(rating)FROM city;

Find out the number of distinctive country values:

SELECT COUNT(DISTINCT country_id)FROM city;

Find out the smallest and the greatest country populations:

SELECT MIN(population), MAX(population)FROM country;

Find out the total population of cities in respective countries:

SELECT country_id, SUM(population)FROM cityGROUP BY country_id;

Find out the average rating for cities in respective countries if the average is above 3.0:

SELECT country_id, AVG(rating)FROM cityGROUP BY country_idHAVING AVG(rating) > 3.0;

SUBQUERIES

A subquery is a query that is nested inside another query, or inside another subquery. There are different types of subqueries.

SINGLE VALUE

The simplest subquery returns exactly one column and exactly one row. It can be used with comparison operators =, <, <=, >, or >=.

This query finds cities with the same rating as Paris:

SELECT nameFROM cityWHERE rating = ( SELECT rating FROM city WHERE name = 'Paris');

MULTIPLE VALUES

A subquery can also return multiple columns or multiple rows. Such subqueries can be used with operators IN, EXISTS, ALL, or ANY.

This query finds cities in countries that have a population above 20M:

SELECT nameFROM cityWHERE country_id IN ( SELECT country_id FROM country WHERE population > 20000000);

CORRELATED

A correlated subquery refers to the tables introduced in the outer query. A correlated subquery depends on the outer query. It cannot be run independently from the outer query.

This query finds cities with a population greater than the average population in the country:

SELECT *FROM city main_cityWHERE population > ( SELECT AVG(population) FROM city average_city WHERE average_city.country_id = main_city.country_id);

This query finds countries that have at least one city:

SELECT nameFROM countryWHERE EXISTS ( SELECT * FROM city WHERE country_id = country.id);

SET OPERATIONS

Set operations are used to combine the results of two or more queries into a single result. The combined queries must return the same number of columns and compatible data types. The names of the corresponding columns can be different

SQL Basics Cheat Sheet (9)

UNION

UNION combines the results of two result sets and removes duplicates. UNION ALL doesn't remove duplicate rows.

This query displays German cyclists together with German skaters:

SELECT nameFROM cyclingWHERE country = 'DE'UNION / UNION ALLSELECT nameFROM skatingWHERE country = 'DE';
SQL Basics Cheat Sheet (10)

INTERSECT

INTERSECT returns only rows that appear in both result sets.

This query displays German cyclists who are also German skaters at the same time:

SELECT nameFROM cyclingWHERE country = 'DE'INTERSECTSELECT nameFROM skatingWHERE country = 'DE';
SQL Basics Cheat Sheet (11)

EXCEPT

EXCEPT returns only the rows that appear in the first result set but do not appear in the second result set.

This query displays German cyclists unless they are also German skaters at the same time:

SELECT nameFROM cyclingWHERE country = 'DE'EXCEPT / MINUSSELECT nameFROM skatingWHERE country = 'DE';
SQL Basics Cheat Sheet (12)

Try out the interactive SQL Basics course at LearnSQL.com, and check out our other SQL courses.

SQL Basics Cheat Sheet (2024)

FAQs

How can I learn SQL easily? ›

Getting started with SQL
  1. Step 1: identifying motivation. Before diving headfirst into learning SQL, it's important to understand your motivation. ...
  2. Step 2: learning the basics quickly. ...
  3. Step 3: work on guided projects. ...
  4. Step 4: build your own SQL projects. ...
  5. Step 5: work on more advanced projects.
5 days ago

What are the basics of SQL? ›

Structured query language (SQL) is a programming language for storing and processing information in a relational database. A relational database stores information in tabular form, with rows and columns representing different data attributes and the various relationships between the data values.

How to practice SQL for beginners? ›

Here are some helpful resources:
  1. Interactive tutorials: Websites like [LearnSQL.com] offer interactive tutorials that introduce you to SQL through practical exercises.
  2. Online Courses: Platforms like Coursera, Udemy, or Khan Academy have beginner-friendly SQL courses you can complete in a week.
May 29, 2024

Is SQL hard to learn? ›

The SQL syntax is easy to learn, and there are hundreds of tutorials online that can help you. You can test your knowledge of the basics with flashcards, online challenges, and free quizzes. There are also dozens of free resources like this SQL Query Cheatsheet.

How long does it take to learn SQL? ›

SQL is considered one of the easiest programming languages to learn due to its straightforward, English-based syntax. Although mastering SQL requires dedication, most experts agree that it takes the average learner about two to three weeks to become proficient with this programming language.

Can SQL be self taught? ›

Even if you lack experience with web or software development, you can begin learning SQL on your own and start working toward a mastery of the language.

What is the hardest thing to learn in SQL? ›

Learning SQL can be challenging due to advanced concepts such as recursive queries, query tuning, temporary functions, and self-joins.

Which SQL is best for beginners? ›

If you are just starting to learn SQL and want to get some hands-on experience, MySQL or PostgreSQL might be good choices since they are free and easy to set up. If you are interested in pursuing a career in a specific industry, it might be worth researching which RDBMS are commonly used in that field.

How to write SQL queries for beginners? ›

How to Create a SQL Statement
  1. Start your query with the select statement. select [all | distinct] ...
  2. Add field names you want to display. field1 [,field2, 3, 4, etc.] ...
  3. Add your statement clause(s) or selection criteria. Required: ...
  4. Review your select statement. Here's a sample statement:
Oct 13, 2022

Is SQL beginner friendly? ›

SQL (Structured Query Language) is a programming language used to manage data stored in relational databases, which store structured data in tables. Its syntax is easy to read, so it's easy to pick up on even if you're completely new to programming, and it's even useful for non-technical careers.

What is an example of SQL? ›

An SQL SELECT statement retrieves records from a database table according to clauses (for example, FROM and WHERE ) that specify criteria. The syntax is: SELECT column1, column2 FROM table1, table2 WHERE column2='value';

What should I learn first before SQL? ›

Having prior knowledge of databases, Microsoft Excel, and basic programming can be advantageous to learning SQL. SQL knowledge is crucial for any career involving data handling, with its applications ranging from searching, updating, and maintaining databases to transforming raw data into valuable insights.

What is the best way to learn SQL quickly? ›

Best way to learn SQL
  1. Create your own database and practice on it.
  2. Solve SQL puzzles and challenges available online.
  3. Participate in online SQL communities and forums.
  4. Use online SQL tutorials and courses.
  5. Attend SQL workshops and webinars.
  6. Practice SQL queries on real-world datasets.
Mar 13, 2023

What are the 5 built in functions in SQL? ›

COUNT, SUM, AVG, MAX and MIN is the built-in functions provided by SQL. DIV and MULT are not available in SQL.

What are the 5 Sublanguages of SQL? ›

SQL: What is SQL and its 5 Subgroups DQL, DML, TCL, DDL, DCL?
  • DQL = Data Query Language.
  • DML = Data Manipulation Language.
  • TCL = Transaction Control Language.
  • DDL = Data Definition Language.
  • DCL = Data Control Language.
Jul 5, 2022

What are the 5 category of SQL? ›

Different Types of SQL Commands – DDL, DML, DCL, TCL, DQL. In the dynamic world of databases, SQL commands serve as the guiding stars, illuminating the path to effective data management.

What is the most basic command in SQL? ›

Some of The Most Important SQL Commands
  • SELECT - extracts data from a database.
  • UPDATE - updates data in a database.
  • DELETE - deletes data from a database.
  • INSERT INTO - inserts new data into a database.
  • CREATE DATABASE - creates a new database.
  • ALTER DATABASE - modifies a database.
  • CREATE TABLE - creates a new table.

Top Articles
Latest Posts
Article information

Author: Rob Wisoky

Last Updated:

Views: 6226

Rating: 4.8 / 5 (68 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Rob Wisoky

Birthday: 1994-09-30

Address: 5789 Michel Vista, West Domenic, OR 80464-9452

Phone: +97313824072371

Job: Education Orchestrator

Hobby: Lockpicking, Crocheting, Baton twirling, Video gaming, Jogging, Whittling, Model building

Introduction: My name is Rob Wisoky, I am a smiling, helpful, encouraging, zealous, energetic, faithful, fantastic person who loves writing and wants to share my knowledge and understanding with you.