Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
33 views

SQL Commands Cheat Sheet - How To Learn SQL in 10 Minutes

This document provides an overview of SQL (Structured Query Language) and how to learn it in 10 minutes. It defines SQL and its use for managing relational databases. Examples show basic SQL queries and clauses. The article explains why SQL is useful and clarifies the difference between SQL as a language and MySQL as an implementation. It also provides instructions for installing MySQL and using tools like MySQL Workbench to write and execute SQL queries. Finally, it includes a cheatsheet of common SQL keywords.

Uploaded by

Loko Loko
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

SQL Commands Cheat Sheet - How To Learn SQL in 10 Minutes

This document provides an overview of SQL (Structured Query Language) and how to learn it in 10 minutes. It defines SQL and its use for managing relational databases. Examples show basic SQL queries and clauses. The article explains why SQL is useful and clarifies the difference between SQL as a language and MySQL as an implementation. It also provides instructions for installing MySQL and using tools like MySQL Workbench to write and execute SQL queries. Finally, it includes a cheatsheet of common SQL keywords.

Uploaded by

Loko Loko
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

4/3/22, 2:03 PM SQL Commands Cheat Sheet – How to Learn SQL in 10 Minutes

Forum
Donate

Learn to code — free 3,000-hour curriculum

NOVEMBER 23, 2021 / #SQL

SQL Commands Cheat Sheet –


How to Learn SQL in 10
Minutes
Jason Dsouza

I’m an AI researcher, so one of the main things I deal


with is data. A lot of it.

With more than 2.5 exabytes of data generated every day, it comes as
no surprise that this data needs to be stored somewhere where we
can access it when we need it.

This article will walk you through a hackable cheatsheet to get you up
and running with SQL quickly.

What is SQL?
SQL stands for Structured Query Language. It is a language for
relational database management systems. SQL is used today to store,
retrieve, and manipulate data within relational databases.

https://www.freecodecamp.org/news/learn-sql-in-10-minutes/ 1/27
4/3/22, 2:03 PM SQL Commands Cheat Sheet – How to Learn SQL in 10 Minutes

Here’s what a basic relational database looks like: Forum


Donate

Learn to code — free 3,000-hour curriculum

Source

Using SQL, we can interact with the database by writing queries.

Here’s what an example query looks like:

SELECT * FROM customers;

Using this SELECT statement, the query selects all the data from all
the columns in the customer’s table and returns data like so:

https://www.freecodecamp.org/news/learn-sql-in-10-minutes/ 2/27
4/3/22, 2:03 PM SQL Commands Cheat Sheet – How to Learn SQL in 10 Minutes

Forum
Donate

Learn to code — free 3,000-hour curriculum

Source: Database Guide


The asterisk wildcard character (*) refers to “all” and selects all the
rows and columns. We can replace it with specific column names
instead — here only those columns will be returned by the query

SELECT FirstName, LastName FROM customers;

Adding a WHERE clause allows you to filter what gets returned:

SELECT * FROM customers WHERE age >= 30 ORDER BY age ASC;

This query returns all data from the products table with an age value
of greater than 30.

The use of ORDER BY keyword just means the results will be ordered
using the age column from the lowest value to the highest

Using the INSERT INTO statement, we can add new data to a table.

H ’ b i l ddi
https://www.freecodecamp.org/news/learn-sql-in-10-minutes/ t th t t bl 3/27
4/3/22, 2:03 PM SQL Commands Cheat Sheet – How to Learn SQL in 10 Minutes
Here’s a basic example adding a new user to the customers table:
Forum
Donate

Learn to code — free 3,000-hour curriculum


INSERT INTO customers(FirstName, LastName, address, email)

VALUES ('Jason', 'Dsouza', 'McLaren Vale, South Australia', 'test@fakeGma

Of course, these examples demonstrate only a very small selection of


what the SQL language can do. We'll learn more about it in this guide.

Why Learn SQL?


We live in the age of Big Data, where data is used extensively to find
insights and inform strategy, marketing, advertising and a plethora of
other operations.

Big businesses like Google, Amazon, AirBnb utilize large, relational


databases as a basis of improving customer experience.
Understanding SQL is a great skill to have not only for data scientists
and analysts but for everyone.

How do you think that you suddenly got a Youtube ad on shoes when just a
few minutes ago, you were Googling your favourite shoes? That’s SQL (or a
form of SQL) at work!

SQL vs MySQL
Before we move on, I just want to clarify an often-confused topic — the
difference between SQL and MySQL. As it turns out, they aren’t the
same thing!

SQL i l hil M SQL i


https://www.freecodecamp.org/news/learn-sql-in-10-minutes/ t t i l t SQL 4/27
4/3/22, 2:03 PM SQL Commands Cheat Sheet – How to Learn SQL in 10 Minutes
SQL is a language, while MySQL is a system to implement SQL.
Forum
Donate
SQL outlines syntax that allows you to write queries that manage
Learn to code — free 3,000-hour curriculum
relational databases.

MySQL is a database system that runs on a server. It allows you to


write queries using SQL syntax to manage MySQL databases.

In addition to MySQL, there are other systems that implement SQL.


Some of the more popular ones include:

SQLite

Oracle Database

PostgreSQL

Microsoft SQL Server

How to Install MySQL


For most cases, MySQL is the preferred choice for a database
management system. Many popular Content Management Systems
(like Wordpress) use MySQL by default, so using MySQL to manage
those applications can be a good idea.

In order to use MySQL, you’ll need to install it on your system:

Install MySQL on Windows


The recommended way to install MySQL on Windows is by using the
MSI installer from the MySQL website.

This resource will guide you with the installation process.

I ll M SQL
https://www.freecodecamp.org/news/learn-sql-in-10-minutes/ OS 5/27
4/3/22, 2:03 PM SQL Commands Cheat Sheet – How to Learn SQL in 10 Minutes

Install MySQL on macOS Forum


Donate
On macOS, installing MySQL also involves downloading an installer.
Learn to code — free 3,000-hour curriculum

This resource will guide you through the installation process.

How to Use MySQL


With MySQL now installed on your system, I recommend that you use
some sort of SQL management application to make managing your
databases a much easier process.

There are lots of apps to choose from which largely do the same job,
so it’s down to your own personal preference on which one to use:

MySQL Workbench developed by Oracle

phpMyAdmin (operates in the web browser)

HeidiSQL (Recommended for Windows)

Sequel Pro (Recommended for macOS)

When you’re ready to start writing your own SQL queries, consider
importing dummy data rather than creating your own database.

Here are some dummy databases that are available for download free
of charge.

SQL Cheatsheet – The Icing on the


Cake 
SQL Keywords
H fi d ll ti
https://www.freecodecamp.org/news/learn-sql-in-10-minutes/ fk d d i SQL t t t 6/27
4/3/22, 2:03 PM SQL Commands Cheat Sheet – How to Learn SQL in 10 Minutes
Here you can find a collection of keywords used in SQL statements, a
Forum
Donate
description, and where appropriate an example. Some of the more
Learnhave
advanced keywords to code — free
their own3,000-hour
dedicatedcurriculum
section.

Where MySQL is mentioned next to an example, this means this


example is only applicable to MySQL databases (as opposed to any
other database system).

ADD -- Adds a new column to an existing table

ADD CONSTRAINT -- Creates a new constraint on an existing table, which is


ALTER TABLE -- Adds, deletes or edits columns in a table. It can also be


ALTER COLUMN -- Changes the data type of a table’s column.

ALL -- Returns true if all of the subquery values meet the passed conditi

AND -- Used to join separate conditions within a WHERE clause.

ANY -- Returns true if any of the subquery values meet the given conditio

AS -- Renames a table or column with an alias value which only exists for

ASC -- Used with ORDER BY to return the data in ascending order.

BETWEEN -- Selects values within the given range.

CASE -- Changes query output depending on conditions.

CHECK -- Adds a constraint that limits the value which can be added to a

CREATE DATABASE -- Creates a new database.

CREATE TABLE -- Creates a new table.

DEFAULT -- Sets a default value for a column

DELETE -- Delete data from a table.

DESC -- Used with ORDER BY to return the data in descending order.

DROP COLUMN -- Deletes a column from a table


https://www.freecodecamp.org/news/learn-sql-in-10-minutes/ 7/27
4/3/22, 2:03 PM SQL Commands Cheat Sheet – How to Learn SQL in 10 Minutes
DROP COLUMN -- Deletes a column from a table.


Forum
Donate
DROP DATABASE -- Deletes the entire database.


Learn to code — free 3,000-hour curriculum
DROP DEAFULT -- Removes a default value for a column.

DROP TABLE -- Deletes a table from a database.

EXISTS -- Checks for the existence of any record within the subquery, ret

FROM -- Specifies which table to select or delete data from.

IN -- Used alongside a WHERE clause as a shorthand for multiple OR condi


INSERT INTO -- Adds new rows to a table.

IS NULL -- Tests for empty (NULL) values.

IS NOT NULL -- The reverse of NULL. Tests for values that aren’t empty /

LIKE -- Returns true if the operand value matches a pattern.

NOT -- Returns true if a record DOESN’T meet the condition.

OR -- Used alongside WHERE to include data when either condition is true.


ORDER BY -- Used to sort the result data in ascending (default) or descen


ROWNUM -- Returns results where the row number meets the passed condition

SELECT -- Used to select data from a database, which is then returned in


SELECT DISTINCT -- Sames as SELECT, except duplicate values are excluded.


SELECT INTO -- Copies data from one table and inserts it into another.

SELECT TOP -- Allows you to return a set number of records to return from

SET -- Used alongside UPDATE to update existing data in a table.

SOME -- Identical to ANY.

TOP -- Used alongside SELECT to return a set number of records from a tab

TRUNCATE TABLE -- Similar to DROP, but instead of deleting the table and

UNION -- Combines the results from 2 or more SELECT statements and return
https://www.freecodecamp.org/news/learn-sql-in-10-minutes/ 8/27
4/3/22, 2:03 PM SQL Commands Cheat Sheet – How to Learn SQL in 10 Minutes
UNION -- Combines the results from 2 or more SELECT statements and return

Forum
Donate
UNION ALL -- The same as UNION, but includes duplicate values.


Learn to code — free 3,000-hour curriculum
UNIQUE -- This constraint ensures all values in a column are unique.

UPDATE -- Updates existing data in a table.

VALUES -- Used alongside the INSERT INTO keyword to add new values to a t

WHERE -- Filters results to only include data which meets the given condi

Comments in SQL
Comments allow you to explain sections of your SQL statements,
without being executed directly.

In SQL, there are 2 types of comments, single line and multiline.

Single Line Comments in SQL


Single line comments start with ‘- -’. Any text after these 2 characters
to the end of the line will be ignored.

-- This part is ignored

SELECT * FROM customers;

Multiline Comments in SQL


Multiline comments start with /* and end with */. They stretch across
multiple lines until the closing characters have been found.

https://www.freecodecamp.org/news/learn-sql-in-10-minutes/ 9/27
4/3/22, 2:03 PM SQL Commands Cheat Sheet – How to Learn SQL in 10 Minutes

Forum
Donate
/*


Learn to code — free 3,000-hour curriculum
This is a multiline comment.

It can span across multiple lines.

*/

SELECT * FROM customers;

/*

This is another comment.

You can even put code within a comment to prevent its execution

SELECT * FROM icecreams;

*/

Data Types in MySQL


When creating a new table or editing an existing one, you must specify
the type of data that each column accepts.

In this example, data passed to the id column must be an int (integer),


while the FirstName column has a VARCHAR data type with a
maximum of 255 characters.

CREATE TABLE customers(

id int,

FirstName varchar(255)

);

1. String Data Types


https://www.freecodecamp.org/news/learn-sql-in-10-minutes/ 10/27
4/3/22, 2:03 PM SQL Commands Cheat Sheet – How to Learn SQL in 10 Minutes

Forum
CHAR(size) -- Fixed length string which can contain letters, numbers
and
Donate

VARCHAR(size) Learn to codelength


-- Variable — freestring
3,000-hour curriculum
similar to CHAR(), but with a max

BINARY(size) -- Similar to CHAR() but stores binary byte strings.

VARBINARY(size) -- Similar to VARCHAR() but for binary byte strings.

TINYBLOB -- Holds Binary Large Objects (BLOBs) with a max length of 255 b

TINYTEXT -- Holds a string with a maximum length of 255 characters. Use V


TEXT(size) -- Holds a string with a maximum length of 65535 bytes. Again,


BLOB(size) -- Holds Binary Large Objects (BLOBs) with a max length of 655

MEDIUMTEXT -- Holds a string with a maximum length of 16,777,215 characte


MEDIUMBLOB -- Holds Binary Large Objects (BLOBs) with a max length of 16,

LONGTEXT -- Holds a string with a maximum length of 4,294,967,295 charact


LONGBLOB -- Holds Binary Large Objects (BLOBs) with a max length of 4,294

ENUM(a, b, c, etc…) -- A string object that only has one value, which is

SET(a, b, c, etc…) -- A string object that can have 0 or more values, whi

2. Numeric Data Types

BIT(size) -- A bit-value type with a default of 1. The allowed number of b


TINYINT(size) -- A very small integer with a signed range of -128 to 127,


BOOL -- Essentially a quick way of setting the column to TINYINT with a si


BOOLEAN -- Same as BOOL.

SMALLINT(size) -- A small integer with a signed range of -32768 to 32767,


MEDIUMINT(size) -- A medium integer with a signed range of -8388608 to 838


https://www.freecodecamp.org/news/learn-sql-in-10-minutes/ 11/27
4/3/22, 2:03 PM SQL Commands Cheat Sheet – How to Learn SQL in 10 Minutes
MEDIUMINT(size) -- A medium integer with a signed range of -8388608 to 838

Forum
Donate
INT(size) -- A medium integer with a signed range of -2147483648 to 214748

Learn to code — free 3,000-hour curriculum
INTEGER(size) -- Same as INT.

BIGINT(size) -- A medium integer with a signed range of -92233720368547758


FLOAT(p) -- A floating point number value. If the precision (p) parameter


DOUBLE(size, d) -- A floating point number value where the total digits ar


DECIMAL(size, d) -- An exact fixed point number where the total number of


DEC(size, d) -- Same as DECIMAL.

3. Date/Time Data Types

DATE -- A simple date in YYYY-MM–DD format, with a supported range from ‘


DATETIME(fsp) -- A date time in YYYY-MM-DD hh:mm:ss format, with a suppor


TIMESTAMP(fsp) -- A Unix Timestamp, which is a value relative to the numb


By adding DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT TIMESTAMP to th

TIME(fsp) -- A time in hh:mm:ss format, with a supported range from ‘-838


YEAR -- A year, with a supported range of ‘1901’ to ‘2155’.

SQL Operators
1. Arithmetic Operators in SQL

+ -- Add

– -- Subtract

* -- Multiply
https://www.freecodecamp.org/news/learn-sql-in-10-minutes/ 12/27
4/3/22, 2:03 PM SQL Commands Cheat Sheet – How to Learn SQL in 10 Minutes
* -- Multiply

/ -- Divide
Forum
Donate
% -- Modulus
Learn to code — free 3,000-hour curriculum

2. Bitwise Operators in SQL

& -- Bitwise AND

| -- Bitwise OR

^-- Bitwise XOR

3. Comparison Operators in SQL

= -- Equal to

> -- Greater than

< -- Less than

>= -- Greater than or equal to

<= -- Less than or equal to

<> -- Not equal to

4. Compound Operators in SQL

+= -- Add equals

-= -- Subtract equals
*= -- Multiply equals
/= -- Divide equals

%= -- Modulo equals

&= -- Bitwise AND equals

^-= -- Bitwise exclusive equals

|*= -- Bitwise OR equals

SQL F ti
https://www.freecodecamp.org/news/learn-sql-in-10-minutes/ 13/27
4/3/22, 2:03 PM SQL Commands Cheat Sheet – How to Learn SQL in 10 Minutes

SQL Functions Forum


Donate
1. String Functions in SQL
Learn to code — free 3,000-hour curriculum

ASCII -- Returns the equivalent ASCII value for a specific character.

CHAR_LENGTH -- Returns the character length of a string.

CHARACTER_LENGTH -- Same as CHAR_LENGTH.

CONCAT -- Adds expressions together, with a minimum of 2.

CONCAT_WS -- Adds expressions together, but with a separator between each


FIELD -- Returns an index value relative to the position of a value withi


FIND IN SET -- Returns the position of a string in a list of strings.

FORMAT -- When passed a number, returns that number formatted to include


INSERT -- Allows you to insert one string into another at a certain point

INSTR -- Returns the position of the first time one string appears within

LCASE -- Converts a string to lowercase.

LEFT -- Starting from the left, extracts the given number of characters f

LENGTH -- Returns the length of a string, but in bytes.

LOCATE -- Returns the first occurrence of one string within another,

LOWER -- Same as LCASE.

LPAD -- Left pads one string with another, to a specific length.


LTRIM -- Removes any leading spaces from the given string.

MID -- Extracts one string from another, starting from any position.

POSITION -- Returns the position of the first time one substring appears

REPEAT -- Allows you to repeat a string

REPLACE -- Allows you to replace any instances of a substring within a st

https://www.freecodecamp.org/news/learn-sql-in-10-minutes/ 14/27
4/3/22, 2:03 PM SQL Commands Cheat Sheet – How to Learn SQL in 10 Minutes

REVERSE -- Reverses the string. Forum


Donate

Learn
RIGHT -- Starting to code
from — free extracts
the right, 3,000-hour
thecurriculum
given number of characters

RPAD -- Right pads one string with another, to a specific length.

RTRIM -- Removes any trailing spaces from the given string.

SPACE -- Returns a string full of spaces equal to the amount you pass it.

STRCMP -- Compares 2 strings for differences

SUBSTR -- Extracts one substring from another, starting from any position

SUBSTRING -- Same as SUBSTR

SUBSTRING_INDEX -- Returns a substring from a string before the passed su


TRIM -- Removes trailing and leading spaces from the given string. Same a

UCASE -- Converts a string to uppercase.

UPPER -- Same as UCASE.

2. Numeric Functions in SQL

ABS -- Returns the absolute value of the given number.

ACOS -- Returns the arc cosine of the given number.

ASIN -- Returns the arc sine of the given number.

ATAN -- Returns the arc tangent of one or 2 given numbers.

ATAN2 -- Returns the arc tangent of 2 given numbers.

AVG -- Returns the average value of the given expression.

CEIL -- Returns the closest whole number (integer) upwards from a given d

https://www.freecodecamp.org/news/learn-sql-in-10-minutes/ 15/27
4/3/22, 2:03 PM SQL Commands Cheat Sheet – How to Learn SQL in 10 Minutes

CEILING -- Same as CEIL.


Forum
Donate

COS -- ReturnsLearn to codeof—afree


the cosine 3,000-hour
given number.
curriculum

COT -- Returns the cotangent of a given number.

COUNT -- Returns the amount of records that are returned by a SELECT quer

DEGREES -- Converts a radians value to degrees.

DIV -- Allows you to divide integers.

EXP -- Returns e to the power of the given number.

FLOOR -- Returns the closest whole number (integer) downwards from a give

GREATEST -- Returns the highest value in a list of arguments.

LEAST -- Returns the smallest value in a list of arguments.

LN -- Returns the natural logarithm of the given number.

LOG -- Returns the natural logarithm of the given number, or the logarith

LOG10 -- Does the same as LOG, but to base 10.

LOG2 -- Does the same as LOG, but to base 2.

MAX -- Returns the highest value from a set of values.

MIN -- Returns the lowest value from a set of values.

MOD -- Returns the remainder of the given number divided by the other giv

PI -- Returns PI.

POW -- Returns the value of the given number raised to the power of the o

POWER -- Same as POW.

RADIANS -- Converts a degrees value to radians.

RAND -- Returns a random number.

ROUND -- Rounds the given number to the given amount of decimal places.

https://www.freecodecamp.org/news/learn-sql-in-10-minutes/ 16/27
4/3/22, 2:03 PM SQL Commands Cheat Sheet – How to Learn SQL in 10 Minutes

SIGN -- Returns the sign of the given number.


Forum
Donate

SIN -- ReturnsLearn to code


the sine — free
of the 3,000-hour
given number.
curriculum

SQRT -- Returns the square root of the given number.

SUM -- Returns the value of the given set of values combined.

TAN -- Returns the tangent of the given number.

TRUNCATE -- Returns a number truncated to the given number of decimal pla

3. Date Functions in SQL

ADDDATE -- Adds a date interval (eg: 10 DAY) to a date (eg: 20/01/20) a


ADDTIME -- Adds a time interval (eg: 02:00) to a time or datetime (05:0


CURDATE -- Gets the current date.

CURRENT_DATE -- Same as CURDATE.

CURRENT_TIME -- Gest the current time.

CURRENT_TIMESTAMP -- Gets the current date and time.

CURTIME -- Same as CURRENT_TIME.

DATE -- Extracts the date from a datetime expression.

DATEDIFF -- Returns the number of days between the 2 given dates.

DATE_ADD -- Same as ADDDATE.

DATE_FORMAT -- Formats the date to the given pattern.

DATE_SUB -- Subtracts a date interval (eg: 10 DAY) to a date (eg: 20/01


DAY -- Returns the day for the given date.

DAYNAME -- Returns the weekday name for the given date


https://www.freecodecamp.org/news/learn-sql-in-10-minutes/ 17/27
4/3/22, 2:03 PM SQL Commands Cheat Sheet – How to Learn SQL in 10 Minutes
DAYNAME -- Returns the weekday name for the given date.


Forum
Donate
DAYOFWEEK -- Returns the index for the weekday for the given date.


Learn to code — free 3,000-hour curriculum
DAYOFYEAR -- Returns the day of the year for the given date.

EXTRACT -- Extracts from the date the given part (eg MONTH for 20/01/20

FROM DAYS -- Returns the date from the given numeric date value.

HOUR -- Returns the hour from the given date.

LAST DAY -- Gets the last day of the month for the given date.

LOCALTIME -- Gets the current local date and time.

LOCALTIMESTAMP -- Same as LOCALTIME.

MAKEDATE -- Creates a date and returns it, based on the given year and

MAKETIME -- Creates a time and returns it, based on the given hour, min

MICROSECOND -- Returns the microsecond of a given time or datetime.

MINUTE -- Returns the minute of the given time or datetime.

MONTH -- Returns the month of the given date.

MONTHNAME -- Returns the name of the month of the given date.

NOW -- Same as LOCALTIME.

PERIOD_ADD -- Adds the given number of months to the given period.

PERIOD_DIFF -- Returns the difference between 2 given periods.

QUARTER -- Returns the year quarter for the given date.

SECOND -- Returns the second of a given time or datetime.

SEC_TO_TIME -- Returns a time based on the given seconds.

STR_TO_DATE -- Creates a date and returns it based on the given string


SUBDATE -- Same as DATE_SUB.

SUBTIME -- Subtracts a time interval (eg: 02:00) to a time or datetime


https://www.freecodecamp.org/news/learn-sql-in-10-minutes/ 18/27
4/3/22, 2:03 PM SQL Commands Cheat Sheet – How to Learn SQL in 10 Minutes
SUBTIME -- Subtracts a time interval (eg: 02:00) to a time or datetime

Forum
Donate
SYSDATE -- Same as LOCALTIME.


Learn to code — free 3,000-hour curriculum
TIME -- Returns the time from a given time or datetime.

TIME_FORMAT -- Returns the given time in the given format.

TIME_TO_SEC -- Converts and returns a time into seconds.

TIMEDIFF -- Returns the difference between 2 given time/datetime expres


TIMESTAMP -- Returns the datetime value of the given date or datetime.

TO_DAYS -- Returns the total number of days that have passed from ‘00-0

WEEK -- Returns the week number for the given date.

WEEKDAY -- Returns the weekday number for the given date.

WEEKOFYEAR -- Returns the week number for the given date.

YEAR -- Returns the year from the given date.

YEARWEEK -- Returns the year and week number for the given date.

4. Miscellaneous Functions in SQL

BIN -- Returns the given number in binary.

BINARY -- Returns the given value as a binary string.

CAST -- Converst one type into another.

COALESCE -- From a list of values, returns the first non-null value.

CONNECTION_ID -- For the current connection, returns the unique connect


CONV -- Converts the given number from one numeric base system into ano

CONVERT -- Converts the given value into the given datatype or characte

https://www.freecodecamp.org/news/learn-sql-in-10-minutes/ 19/27
4/3/22, 2:03 PM SQL Commands Cheat Sheet – How to Learn SQL in 10 Minutes

Forum
CURRENT_USER -- Returns the user and hostname which was used
Donate
to authent

Learn
DATABASE -- Gets thetoname
codeof—the
freecurrent
3,000-hour curriculum
database.

GROUP BY -- Used alongside aggregate functions (COUNT, MAX, MIN, SUM, A


HAVING -- Used in the place of WHERE with aggregate functions.

IF -- If the condition is true it returns a value, otherwise it returns


IFNULL -- If the given expression equates to null, it returns the given


ISNULL -- If the expression is null, it returns 1, otherwise returns 0


LAST_INSERT_ID -- For the last row which was added or updated in a tabl

NULLIF -- Compares the 2 given expressions. If they are equal, NULL is


SESSION_USER -- Returns the current user and hostnames.

SYSTEM_USER -- Same as SESSION_USER.

USER -- Same as SESSION_USER.

VERSION -- Returns the current version of the MySQL powering the databa

Wildcard Characters in SQL


In SQL, Wildcards are special characters used with the LIKE and NOT
LIKE keywords. This allows us to search for data with sophisticated
patterns rather efficiently.

% -- Equates to zero or more characters.

-- Example: Find all customers with surnames ending in ‘ory’.

SELECT * FROM customers

WHERE surname LIKE '%ory';

-- Equates to any single character


https://www.freecodecamp.org/news/learn-sql-in-10-minutes/ 20/27
4/3/22, 2:03 PM SQL Commands Cheat Sheet – How to Learn SQL in 10 Minutes
_ -- Equates to any single character.

-- Example: Find all customers living in cities beginningForum


with any 3
chDonate
SELECT * FROM customers

Learn
WHERE city LIKE '_ _to_vale';

code — free 3,000-hour curriculum


[charlist] -- Equates to any single character in the list.

-- Example: Find all customers with first names beginning with J, K or


SELECT * FROM customers

WHERE first_name LIKE '[jkt]%';

SQL Keys
In relational databases, there is a concept of primary and foreign keys.
In SQL tables, these are included as constraints, where a table can
have a primary key, a foreign key, or both.

1. Primary Keys in SQL


A primary lets each record in a table be uniquely identified. You can
only have one primary key per table, and you can assign this constraint
to any single or combination of columns. However, this means each
value within this column(s) needs to be unique.

Typically in a table, the ID column is a primary key, and is usually


paired with the AUTO_INCREMENT keyword. This means the value
increases automatically as and when new records are created.

Example (MySQL)
Create a new table and set the primary key to the ID column.

CREATE TABLE customers (

id int NOT NULL AUTO_INCREMENT,

FirstName varchar(255),

Last Name varchar(255) NOT NULL,

address varchar(255)
https://www.freecodecamp.org/news/learn-sql-in-10-minutes/ 21/27
4/3/22, 2:03 PM SQL Commands Cheat Sheet – How to Learn SQL in 10 Minutes
address varchar(255),

email varchar(255),
Forum
Donate
PRIMARY KEY (id)

); Learn to code — free 3,000-hour curriculum

2. Foreign Keys in SQL


You can apply a foreign key to one column or many. You use it to link 2
tables together in a relational database.

The table containing the foreign key is called the child key,

The table containing the referenced (or candidate) key is called the
parent table.

This essentially means that the column data is shared between 2


tables, because a foreign key also prevents invalid data from being
inserted which isn’t also present in the parent table.

Example (MySQL)
Create a new table and turn any column that references IDs in other
tables into foreign keys.

CREATE TABLE orders (


id int NOT NULL,

user_id int,

product_id int,

PRIMARY KEY (id),

FOREIGN KEY (user_id) REFERENCES users(id),

FOREIGN KEY (product_id) REFERENCES products(id)

);

https://www.freecodecamp.org/news/learn-sql-in-10-minutes/ 22/27
4/3/22, 2:03 PM SQL Commands Cheat Sheet – How to Learn SQL in 10 Minutes

Indexes in SQL Forum


Donate
Indexes are attributes
Learn tothat
codecan be assigned
— free tocurriculum
3,000-hour columns that are
frequently searched against to make data retrieval a quicker and more
efficient process.

CREATE INDEX -- Creates an index named ‘idx_test’ on the first_name and s


CREATE INDEX idx_test
ON users (first_name, surname);

CREATE UNIQUE INDEX -- The same as the above, but no duplicate values.

CREATE UNIQUE INDEX idx_test

ON users (first_name, surname);

DROP INDEX -- Removes an index.

ALTER TABLE users

DROP INDEX idx_test;

SQL Joins
In SQL, a JOIN clause is used to return a result which combines data
from multiple tables, based on a common column which is featured in
both of them.

There are a number of different joins available for you to use:

Inner Join (Default): Returns any records which have matching


values in both tables.

Left Join: Returns all of the records from the first table, along
with any matching records from the second table.

Right Join: Returns all of the records from the second table,
along with any matching records from the first.

Full Join: Returns all records from both tables when there is a
match.
https://www.freecodecamp.org/news/learn-sql-in-10-minutes/ 23/27
4/3/22, 2:03 PM SQL Commands Cheat Sheet – How to Learn SQL in 10 Minutes

Forum
Donate
A common wayLearn
of visualising
to code —how
free joins work is
3,000-hour like this:
curriculum

Source: Website Setup

SELECT orders.id, users.FirstName, users.Surname, products.name as ‘produ


FROM orders

INNER JOIN users on orders.user_id = users.id

INNER JOIN products on orders.product_id = products.id;

Views in SQL
A view is essentially an SQL results set that gets stored in the
database under a label, so you can return to it later without having to
rerun the query.

These are especially useful when you have a costly SQL query which
you might need a number of times. So instead of running it over and
over to generate the same results set, you can just do it once and save
it as a view.

How to Create Views in SQL


To create a view, you can do so like this:

https://www.freecodecamp.org/news/learn-sql-in-10-minutes/ 24/27
4/3/22, 2:03 PM SQL Commands Cheat Sheet – How to Learn SQL in 10 Minutes

CREATE VIEW priority_users AS


Forum
Donate
SELECT * FROM users

WHERE country Learn to code


= ‘United — free 3,000-hour curriculum
Kingdom’;

Then in future, if you need to access the stored result set, you can do
so like this:

SELECT * FROM [priority_users];

How to Replace Views in SQL


With the CREATE OR REPLACE command, you can update a view like
this:

CREATE OR REPLACE VIEW [priority_users] AS

SELECT * FROM users

WHERE country = ‘United Kingdom’ OR country=’USA’;

How to Delete Views in SQL


To delete a view, simply use the DROP VIEW command.

DROP VIEW priority_users;

Conclusion
Th j it f b it
https://www.freecodecamp.org/news/learn-sql-in-10-minutes/ d li ti l ti ld t b i 25/27
4/3/22, 2:03 PM SQL Commands Cheat Sheet – How to Learn SQL in 10 Minutes
The majority of websites and applications use relational databases in
Forum
Donate
some way or the other. This makes SQL extremely valuable to know as
it allows you toLearn
createtomore
code — free 3,000-hour
complex, curriculum
functional systems.

Be sure to follow me on Twitter for updates on future articles. Happy


learning!

Jason Dsouza
AI Researcher @Harvard, Teacher @freeCodeCamp. Part-time Compiler
Warlock.

If you read this far, tweet to the author to show them you care.
Tweet a thanks

Learn to code for free. freeCodeCamp's open source curriculum has


helped more than 40,000 people get jobs as developers.
Get started

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) nonprofit organization (United States


Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of
videos, articles, and interactive coding lessons - all freely available to the public. We also have
thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers,

services, and staff.


You can make a tax-deductible donation here.
https://www.freecodecamp.org/news/learn-sql-in-10-minutes/ 26/27
4/3/22, 2:03 PM SQL Commands Cheat Sheet – How to Learn SQL in 10 Minutes

Forum
Donate
Trending Guides
Learn to code — free 3,000-hour curriculum

CSV File Format HTML Div

Python Open File Learn SQL

Python Sort List Emoji List

JavaScript Online HTML Tables

Python Create File SQL Order By

How to mute on Zoom HTML Padding

Python Do While Loop Learn Python

Python Print Variable CSS Font Color

Span vs Div HTML Tags Free Textbooks

Function in JS Example CSS Positioning

Transparent Background What is Graphic Design?

Save Google Doc as PDF Share Screen on Android

Java Array Declaration Problem Resetting Your PC

JavaScript Switch Case Open Task Manager Windows 10

REST API best practices Delete Albums on iPhone

Our Nonprofit

About Alumni Network Open Source Shop Support Sponsors Academic Honesty

Code of Conduct Privacy Policy Terms of Service Copyright Policy

https://www.freecodecamp.org/news/learn-sql-in-10-minutes/ 27/27

You might also like