SQL Cheat Sheet

Learn via video course
FREE
View all courses
DBMS Course - Master the Fundamentals and Advanced Concepts
DBMS Course - Master the Fundamentals and Advanced Concepts
by Srikanth Varma
1000
5
Start Learning
DBMS Course - Master the Fundamentals and Advanced Concepts
DBMS Course - Master the Fundamentals and Advanced Concepts
by Srikanth Varma
1000
5
Start Learning
Topics Covered

Overview

The SQL commands are used to retrieve data from the database. The DBMS processes the SQL request, retrieves the requested data from the database, and returns it. This process of requesting data from the database and receiving back the results is called a database query and hence the name Structured Query Language.

SQL is used to control all the functions that a DBMS provides for its users, including :

  • Data Definition :
    SQL allows a user to define the structure and the organization of the data to be stored and the relationships among the stored data items
  • Data Retrieval :
    SQL allows a user or an application program to retrieve the stored data from the database
  • Data Manipulation :
    SQL lets a user or an application program update the database by allowing it to add new data, delete the existing data, and modify the existing data.
  • Access Control :
    SOL can be used to restrict a user's ability to retrieve, add, and modify data, thus protecting the stored data against unauthorized access

Installation

To install MySQL in Windows :

Download MySQL from its official website. Click here

To install MySQL in MAcOS :

Use package managers such as Homebrew and use the following command. Write the version name in <version>. brew install mysql brew install mysql@<version>

SQL Keywords

KeywordDescription
1.CREATE DATABASETo create a new database
2.CREATE TABLETo create a new table
3.INSERT INTOTo add new rows to a table
4.SELECTTo select data from a database that is returned in a results set.
5.SELECT INTOTo Copy data from one table and inserts it into another table.
6.WHERETo filter results to include data that meets the given condition.
7.VALUESTo add new values to a table.
8.UPDATETo update existing data in a table.
9.FROMTo specify the table to delete or select data from.
10.EXISTSTo check for any record within the subquery.
11.CHECKTo add a constraint that limits the value to be added to a column.
12.SETTo update existing data in a table.
13.DESCTo return the data in descending order.
14.UNIQUETo ensure all values in a column are unique.
15.UNIONTo Combine the results and return distinct values.
16.DELETETo Delete data from a table.
17.ALTER COLUMNTo Change the data type of a table’s column.
18.SELECT TOPTo return a set number of records to return from a table.
19.ANDTo join separate conditions within a WHERE clause.
20.UNION ALLTo include duplicate values.
21.TRUNCATE TABLETo delete the data without deleting the table.
22.ANYTo return if any of the subquery values meet the given condition.
23.ADDTo add a new column to an existing table
24.ORDER BYTo arrange data in ascending (default) or descending order.
25.ADD CONSTRAINTTo add a new constraint in the table.
26.ALTER TABLETo add, delete or modify columns in a table.
27.LIKETo return true if the operand value matches a pattern.
28.BETWEENTo select values within a specific range.
29.ALLTo return true if the subquery values meet the given condition.
30. ASTo rename a table or column with an alias value.
31.DROP COLUMNTo delete a column from a table.
32.DROP DATABASETo delete an entire database.
33.CASETo change query output depending on conditions.
34.DEFAULTTo set a default value for a column.
35.DROP TABLETo delete a table from a database.

To learn more about keywords in SQL, Click here.

SQL Commands

The five types of SQL commands are :

  1. Data Definition Language(DDL)

    • Create
    • Drop
    • Alter
    • Truncate
  2. Data Manipulation Language

    • Insert
    • Update
    • Delete
  3. Data Control Language

    • Grant
    • Revoke
  4. Transaction Control Language

    • Commit
    • Rollback
    • Save point
  5. Data Query Language

    • Select

Learn more here.

SQL Constraints

The kind of data stored in a table is put to certain limits by data types. Some kinds of constraints are defined while defining values for rows and columns in a table that raises an error when violated.

There are two types of constraints :

  1. Table Constraint :
    The constraint applicable to a column definition as well as to more than one column in a table.
  2. Column Constraint :
    The constraint applicable to only a specific column.

Crud Operations in SQL Commands

1. CREATE

C of CRUD in SQL commands is used to insert and add values to the table. To do so, First, we use the CREATE command to create a table and then INSERT INTO to add or insert values to the table.

CREATE

INSERT INTO

2. READ

R of CRUD in SQL is used to fetch data from the given table. Hence, we use the SELECT command to fetch data from the table.

SELECT

3. UPDATE

U of CRUD in SQL is used to update the existing records in the table. Hence, we use the UPDATE command.

4. DELETE

D of CRUD in SQL is used to delete the table or delete the records in the table. Hence, we use the DELETE command.

Clauses in SQL

GROUP BY CLAUSE

The GROUP BY clause is used with the SELECT statement to arrange similar data, into groups. It is used as an aggregation function following the WHEREclause and preceding the ORDER BYclause.

HAVING CLAUSE

HAVING is used with the GROUP BY clause to specify the search condition for a group.

ORDER BY CLAUSE

The ORDER BY clause is used to sort data in ascending (by default) or descending order(by using the DESC keyword).

Triggers in SQL

Whenever there's a special event, that occurs in the database due to which a stored procedure gets invoked, We call it to be a trigger.

Syntax :

Comments in SQL

To comment out code, SQL uses Single line comments and multiline comments.

1. Single Line Comment :

Starts with -.The characters after - are not considered to be a part of the code.

For example :

2. MultiLine Comment

Starts with /_ and ends with _/.

For example :

SQL Operators

SQL uses Arithmetic Operators, Bitwise operators, Comparison Operators, and Compound operators.

1. Arithmetic Operators

  • To Add- +
  • To Subtract- -
  • To Multiply- *
  • To divide-/
  • To get the remainder- %

2. Bitwise Operator

  • Bitwise AND - &
  • Bitwise OR - |
  • Bitwise exclusive OR - ^

3. Comparison Operators

  • Equal to - =
  • Greater than - >
  • Less than - <
  • Greater than or equal to - >=
  • Less than or equal to - <=
  • Not equal to - <>

4. Compound Operators

  • Add equals - +=
  • Subtract equals - -=
  • Multiply equals - *=
  • Divide equals - /=
  • Modulo equals - %=
  • Bitwise AND equals - &=
  • Bitwise exclusive equals - ^-=
  • Bitwise OR equals - |*=

Learn more here.

SQL Functions

String Functions

FunctionKeyword
ASCIIUsed to return the equivalent ASCII value for a given specific character.
CHAR_LENGTHUsed to Return the length of a character string.
CONCATUsed to merge expressions.
CONCAT_WSUsed to merge expressions with a separator between each value.
FIELDUsed to return an index value relative to the position of a value provided by a list of values.
FIND IN SETUsed to return the position of a string in a list of strings.
FORMATUsed to return the number formatted to include commas when a number is provided as input. (eg 3,405,600).
INSERTUsed to insert one string into another at a given point, for a required number of characters.
INSTRUsed to return the position of the first time one string appears within another.
LCASEUsed to convert a given string to lowercase.
LEFTUsed to extract the given number of characters from a string and return them as another, starting from the left.
LOCATEUsed to return the first occurrence of one string within another.
LPADUsed for adding left pad one string with another of a specific length.
LENGTHUsed to return the length of a string in bytes.
MIDUsed for extracting one string from another, starting from any position.
LTRIMUsed to remove leading spaces in a given string.
POSITIONUsed to return the position of the first time one substring appears within another.
REPLACEUsed to replace any instances of a substring within a string, with a new substring.
REPEATUsed for repetition of a string
RIGHTUsed to extract the given number of characters from a string and return them as another starting from the right.
REVERSEUsed to reverse a given string.
RTRIMUsed to remove any trailing spaces from the given string.
SPACEUsed to return a string full of spaces equal to the amount passed.
RPADUsed for applying right pads one string with another, to a specific length.
SUBSTRING_INDEXUsed to return a substring from a string before the passed substring is found the number of times equals the passed number.
STRCMPUsed for comparing two strings.
SUBSTRUsed to extract a substring from another, starting from any position.
UCASE/UPPERUsed to convert a string to uppercase.
TRIMUsed to remove trailing and leading spaces from the given string.

Numeric Functions

FunctionDescription
ABSUsed to return the absolute value of the given number.
ASINUsed to return the arc sine of a given number.
ATANUsed to return the arc tangent of given numbers.
ATAN2Used to return the arc tangent of given numbers.
ACOSUsed to return the arc cosine of a given number.
AVGUsed to return the average value of the given expression.
CEILUsed to return the closest whole number (integer) upwards from a given decimal point number.

To learn more about SQL functions, Read here.

Filtering in SQL

In SQL, the FILTER clause is used for filtering the input data to an aggregation function. It is even more flexible than the WHERE clause.

Learn more about Filtering in SQL here.

Wildcard Characters in SQL

Wildcard charactersDescription
%Matches with any string followed by any number of characters. Eg : 'B%' will match with all the strings starting with B followed by any number of characters. %B will match all strings starting with any characters and ending with B. %B% will match with a string consisting of B at any position.
_Matches string with two characters where the string must start with the specified character followed by any character of a single length. Eg : 'B\_' will match with the string starting with B followed by any other character. '\_B will match with any character followed by a B.'
[]Matches a single character starting with a given character but lying in a given in specific range ([a-f]) or set ([abcdef]). Eg : 'S[a,r,t]'will match with strings like Star,Start etc.
[^]Matches the character string starting with a given character but not lying in the specified range ([^a-f]) or set ([^abcdef]) Eg : 'S[^a,r,t]'will match all string starting with S but not strings like Star, Start, etc.

SQL Keys

  • Candidate Key :
    The set of one or more attributes that uniquely identify a row in a table.
  • Primary Key :
    An attribute that uniquely identifies a row from the table.
  • Alternate Key :
    Candidate keys apart from the primary keys are known as Alternate Key.
  • Composite Primary Key :
    A combination of more than one key attribute is known as Composite Primary Key.
  • Non-Key Attribute :
    The keys apart from the candidate keys are known as Non-Key attributes.
  • Foreign Key :
    The set of attributes whose values are matched with a column in the same table.

Indexes in SQL

To make data retrieval efficient, We use indexes. Indexes are the attributes assigned to columns to be searched against to make quick data retreival.

  • CREATE INDEX : Creates Indexes where duplicates are allowed.
  • CREATE UNIQUE INDEX : Creates indexes with no duplicate values.
  • DROP INDEX : Deletes an existing index.

To learn more, click here.

SQL Joins

Joins is used to combine data from multiple tables.

  • Inner Join (By Default) :
    Used to return records having matching values from both tables.
  • Left Join :
    Used to return all the records having macthing records from the second table from the first table.
  • Right Join :
    Used to return all the records from the second table along with any matching records from the first.
  • Full Join :
    Used to return records from both tables in case of a match.

To learn SQL Joins in detail, click here.

Views in SQL

Views in SQL are used to store the database under a label that prevents rerunning the query.

To Create a View :

To update a View :

To delete a view :

To learn more, Click here.

SQL Stored Procedures

SQL stored procedures are used to save a written code to prevent writing the code again and again.

It helps in code reusability.

SQL Injection

SQL injection is a technique in which malicious code is palced in SQL taking inputs from the webpage.

Conclusion

  • SQL commands are used to insert, update, retrieve, and perform operations in the database.
  • It helps in building complex websites dealing with a huge amount of data.
  • In this article, we skimmed through an entire overview of SQL concepts.
  • To learn more in detail, Follow this tutorial.
  • It's your turn now to play around with commands and explore the use of SQL commands considering sets of data and performing various operations.