Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (1 vote)
2K views

SQL Cheat Sheet

This document provides a cheat sheet overview of common SQL commands and functions. It summarizes key clauses like SELECT, FROM, WHERE, GROUP BY, ORDER BY, LIMIT, JOIN and provides examples of commands for querying, filtering, sorting, aggregating and joining data from one or more tables. Joins allow retrieving and matching rows between tables. The cheat sheet also covers data definition and manipulation commands like CREATE DATABASE, CREATE TABLE, ALTER TABLE, as well as transaction management commands like COMMIT and ROLLBACK.

Uploaded by

Anjan Goud
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (1 vote)
2K views

SQL Cheat Sheet

This document provides a cheat sheet overview of common SQL commands and functions. It summarizes key clauses like SELECT, FROM, WHERE, GROUP BY, ORDER BY, LIMIT, JOIN and provides examples of commands for querying, filtering, sorting, aggregating and joining data from one or more tables. Joins allow retrieving and matching rows between tables. The cheat sheet also covers data definition and manipulation commands like CREATE DATABASE, CREATE TABLE, ALTER TABLE, as well as transaction management commands like COMMIT and ROLLBACK.

Uploaded by

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

SQL CHEAT-SHEET PAGE 1

LEFT JOIN
1 ATA B ASE
D
dml commands
BETWEEN The BETWEEN operator can be used to filter SELECT * FROM table_name LIMIT 5 ;
by a range of values.
G RANT SELECT , UP DATE ON TABLE_1
--Limit is used to limit the result set SELECT col1, col2

CREATE DATABASE database_name; TO USER_1, USER_2; FROM table_name t1

-- reates a new database LIKE The LIKE operator can be used inside of a to the specified number of rows.
C
--Used to grant a user access WHERE clause to match a specified pattern.
LEFT JOIN table_name t2

U SE database_name; privileges to a database.


The % wildcard can be used in a LIKE
SELECT col1, col2 FROM table_name
ON condition;
--Uses the specified database
%

Wildcard operator pattern to match zero or more ORDER BY col1 ASC [ DESC ] ; TABLE 1 TABLE 2
G RANT SELECT , UP DATE ON TABLE_1
unspecified character(s). --Sort the result set in ascending or L
TO USER_1, USER_2; The _ wildcard can be used in a LIKE
descending order 1 E
F
A 1 B
CO MM AN S --Used to grant a user access
2 sql
=
_

privileges to a database. Wildcard operator pattern to match any single


unspecified character. SELECT col1, col2 FROM table_name
2 T

J
B 2 A
database ORDER BY col1 LIMIT n OFFSET offset; O
CREATE TABLE table_name
dcl commands
IN
The IN operator is used to compare the
specified value. AS - Columns or tables can
--Skip offset of rows and return the 3 I
N C 3
( column1 datatype,
c o mmi t Saves all the transactions made on a be aliased using the AS clause. next n rows based on LIMIT.
Returns all rows from the table on the left side of the
column2 datatype,
database.
It is used to search for the presence of a row SELECT col1, aggregate (col2)
JOIN and matched rows from the right side of the Join
column3 datatype); E IST
It is used to undo transactions which are
FROM table_name G RO UP BY col1;
X
ro llb a ck in a table.
--The create table statement creates not yet been saved.
--GROUP BY Groups rows using an aggregate R I GH T JOIN
a new table in a database tcl commands
where
function
SELECT column_name FROM table_name
SELECT col1, col2

ALTER TABLE table_name


SELECT col1,col2.. FROM table_name; WHERE column_name IS N U LL ;
SELECT col1, aggregate(col2)
FROM table_name t1

ADD column_name datatype; --Retrieve data from specified columns -- olumn values can be or have no FROM table_name
RI G HT JOIN table_name t2

in the table G RO UP BY col1 HA V IN G condition;


C NULL

--The Alter table statement is used value. These records can be atc ed using m h ON condition;
to odify the columns of an existing
m
SELECT * FROM table_name; the and operators. --Filter groups using the HAVING clause. TABLE 1 TABLE 2
table and add a new column.
IS NULL IS NOT NULL
R
--Retrieve the data from all fields in union 1 I
G A 1 B
ALTER TABLE table_name
the table. SELECT col1, col2 FROM table_name
DESC table_name; H
ADRO P COL U MN column_name; SELECT col1,col2..FROM table_name
U NION --Describes the structure of the table. 2 T

J
O
B = 2 A
--The Alter table statement is used WHERE condition; SELECT col1, col2 FROM table_name;
3 I
N C C
to odify the columns of an existing
m
--Used to filter the records based --Co bine rows from two queries wit out 10 CASE
table and Drop column. on a particular condition.
m

any duplicates.
h

Returns all rows from the table on the right side of the
ALTER TABLE table_name
SELECT column_name,
JOIN and matched rows from the left side of the Join
RENAME col_name TO col_newname; 7 S Q L CONST R AINTS union all CASE

SELECT col1, col2 FROM table_name WHEN Condition THEN ‘output’


C R OSS JOIN
--Rena es the column names in the
m NOT N U LL Specifies that this column cannot store a
NULL value. U NION ALL
WHEN Condition THEN ‘output’

existing table. SELECT col1, col2 FROM table_name; .


SELECT col1, col2

U NI QU E Specifies that this column can have only


-- ombine rows from two queries with .
FROM table_name t1

D rop ta bl e table_name; unique values C

duplicates .
CROSS JOIN table_name t2

--Drop deletes both structure and P RIMAR Y


ON condition;
records in the table. K EY
It is a field using which it is possible to
uniquely identify each row in a table. intersect
ELSE ‘output’

END ‘new_colname’ FROM table_name; TABLE 1 TABLE 2


T run c ate ta bl e table_name; FOREI GN
It is a field using which it is possible to SELECT col1, col2 FROM table_name
-- runcate deletes the table but not K EY
uniquely identify each row in some other INTERSECT 11 JOINS 1 c
r A 1 A
T table. SELECT col1, col2 FROM table_name;
o
the structure
CHEC K It validates if all values in a column --Return the co on rows of two queries.
mm INNE R JOIN 2
s
s

J
B = 1 B
ddl commands
satisfy some particular condition or not
union SELECT col1, col2
3 O
I C 1 C
DEFA U LT It specifies a default value for a column
FROM table_name t1
N
INSERT INTO table_name
when no value is specified for that field SELECT col1, col2 FROM table_name
INNER JOIN table_name t2

2 A
V AL U ES (value1, value2); MIN U S
8 O P E R ATO R S SELECT col1, col2 FROM table_name;
ON condition; 2 B
UP DATE table_name

SET column1 = value1,column2 = value2


and The NOT operator allows the negotiation of the
--Returns the values from the first table TABLE 1 I TABLE 2 2 C
WHERE some_column =some_value; condition. after re oving t e values from the second 1 N
A 1 B 3 A
m h
N
--The PDA E statement is used to edit or The OR operator allows multiple conditions to be table. E
2 R

B = 2 A 3 B
U T

records (rows) in a table. combined. Records match either condition.


J
Querying
not The AND operator allows multiple conditions to be O
9 D ata

DELETE FROM table_name


combined. Records must match both conditions
SELECT DISTINCT (column_name)
3 N
I C 3 C
WHERE some_column = some_value; ALL It compares a value to all the values in another set. FROM table_name;
--The delete statement is used to -- nique values of the columns are Only returns rows that meet the join condition Produce a Cartesian product of rows in tables
delete records (rows) in a table. ANY It compares the values in the list according to the
condition.
U

retrieved from the table.


SQL CHEAT-SHEET PAGE 2

FULL JOIN L AST _ anking is assigned to the rows based The implementation of APPROX_COUNT_DISTINCT() Creating a search index:
in d o w


Gives the last value to all rows. R

V A LU E ()
w
on a specified column. Ranks are not has a much smaller memory requirement as Indexes are created for one or more columns in
SE L ECT col1, col2
functions skipped. compared to the COUNT(DISTINCT) function a table, using the CREATE INDEX command.

F RO M table_name t 1
last_

Gives the last value to all rows. Syntax: CREATE SEARCH INDEX index_name ON
FULL J OIN table_name t2
value() s e l e ct the database selects the given columns,
lo w er () :
`dataset.table_name` (column_name);
ON condition; istinct
Nth
d repeated values are removed, The LOWER() function converts a string to lowercase.
Gives Nth value to all rows. Dropping a search index:
TABLE 1 TABLE 2 value()
union /
upper () :
B An index can be dropped using SQL DROP command.
1 A 1 NTILE() Divides the rows to ‘n’ number of small int e r s e ct /
the database applies set operations, The UPPER() function converts a string to uppercase.
buckets. e xc e pt Syntax: DROP SEARCH INDEX index_name
2 B = 2 A
The cumulative percentage of the records order the results are sorted,
REGEXP _ C ONT AI N S () :
ON `dataset.table_name`;
cume_
by
Returns TRUE if the value is a partial match for
is calculated from the first row to the ●

3 C C dist() current row for the specified column. O FF SET the first rows are skipped, the regular expression, regex.

18 sql partitioning
3 l imit / ● If the regex argument is invalid, the
Partitioning is a database process where very
14 i
v e ws f e tch / top
only the first rows are selected function returns an error.
large tables are divided into multiple
Returns all rows from bith sides even if join condition is ● You can search for a full match by using ^
smaller, individual parts.

not met SE L ECT V IE W view_name


(beginning of text) and $ (end of text).

AS SE L ECT * F RO M table_name; 16 a d v an c e sql


● By splitting a large table, queries that

12 aggr e gat e fu n c tions --It creates a simple view. Syntax: REGEXP_CONTAINS(value, regex) access only limited amount of data can run
count ( )
faster because there is less data to scan.

avg() returns the average of a list Function with the DISTINCT clause eliminates the REGEXP _ extract () :
SE L ECT V IE W view_name
repetitive appearance of the same data. The DISTINCT

● Returns the first substring in value that


sum() returns the total of a list. AS SELECT col1, col2
can come only once in a given select statement. ● You can partition BigQuery tables by:
matches the regular expression, regex.
count()
F RO M table_name t1
Returns NULL if there is no match.

returns the number of elements of a list. -Time-unit column: Tables are partitioned based on
INNER JOIN table_name t2
count (*)

a TIMESTAMP, DATE, or DATETIME column in the
min() returns the minimum value of a list. ON condition; When * is used as an argument, it simply counts the ● If the regular expression contains a table.

max() returns the maximum value of a list. --It creates a complex view total number of rows including the NULLs.
capturing group, the function returns the -Ingestion time: Tables are partitioned based on
substring that is matched by that capturing the timestamp when BigQuery ingests the data.

count ( 1 )
13 a d v an c e d aggr e gat e fu n c tions CREATE TE M PORAR Y V IE W view_name
group.

With COUNT(1), there is a misconception that it


AS SE L ECT col1, col2
-Integer range: Tables are partitioned based on an
counts records from the first column. What COUNT(1)
t is a window function used inside every F RO M table_name; If the expression does not contain a integer column.

ov e r () I
really does is that it replaces all the records you ●
analytical function --It creates a temporary view. get from query results with the value 1 and then capturing group, the function returns the
Use the CREATE TABLE statement with a SELECT AS
P a r tition counts the rows meaning it even replaces a NULL with entire matching substring.

C reates a partition internally and later clause for the query. Include a PARTITION BY
() 1 meaning it takes NULLs into consideration while

by p erforms the specified operations. DROP V IE W view_name; clause to configure the partitioning.
counting. ● Returns an error if:

r o w _ num b e r
Provides row numbers for all the rows --Delete a view. --The regular expression is invalid
Copying individual partitions:
() based on a specified column in the table. C OUNT ( colu m n _ na m e ) - --The regular expression has more than one ● You can copy the data from one or more

Ranking is assigned to the rows based


15 sql trigg e rs When a column name is used as an argument, it simply capturing group
partitions to another table.

r an k () on a specified column. Skips the rank counts the total number of rows excluding the NULLs
All query elements are processed in a very strict order:
meaning it will not take NULLs into consideration.
Syntax: REGEXP_EXTRACT(value, regex) Copying partitions is not supported by
when it contains the same values. ●
Query execution order. Console.

anking is assigned to the rows based 17 sql in d e x e s


de ns e _
R
COUNT(DISTINCT expr,[expr...])
on a specified column. Ranks are not the database gets the data from tables in
r an k () ● However you can copy them using the API
skipped. f r om FROM clause and if necessary performs
the JOINs,
APPROX _ CO U NT _ DISTINC T
●A SQL index is a quick lookup table used to

Deleting a partition
PERCENT _
Assigns the rank to the specified is useful if an exact result is not required. quickly retrieve data from a database.

r an k () column within the range of 0-1.


w here the data are filtered with conditions ● You can delete an individual partition
specified in the WHERE clause, Compared to SE L ECT from a partitioned table.

● ● Indexes are generally used for large


The first value becomes NULL. CO U NT ( DISTINCT <co l umn> ) , which calculates

L A G () the data are grouped by conditions databases. They are small, fast, and less
C ompares the current value with the g r oup by
the exact number of distinct values in a ● But you can't delete the special NULL or
p revious value. specified in the WHERE clause, memory-consuming.

column of the table, APPROX _ CO U NT _ DISTINCT UN-PARTITIONED partitions.

The last value becomes NULL. Compares A gg r e gat e the aggregate functions are applied to the can run much faster and consume significantly ● Indexing a table or view surely improves
L EAD () functions groups created in the GROUP BY phase,
the current value with the next value. less memory. the performance of queries and applications. ● You can only delete one partition at a

F IRST _ the groups are filtered with the given time


Gives the first value to all rows. H aving condition,
V A LU E ()

You might also like