Docsity

SQL Syntax Cheat Sheet, Cheat Sheet of Database Management Systems (DBMS)

Partial preview of the text

Download SQL Syntax Cheat Sheet and more Cheat Sheet Database Management Systems (DBMS) in PDF only on Docsity!

SQL

Cheat Sheet

Basics

USE sql_store; SELECT FROM customers * WHERE ORDER stateBY first_name = ‘CA’ LIMIT 3;

  • • SQL isIn MySQL, every statement must be terminated with a semicolon. not a case-sensitive language.

Comments We use comments to add notes to our code.

—- This is a comment and it won’t get executed.

SELECT Clause —- Using expressions

SELECT FROM customers (points * 10 + 20) AS discount_factor

Order of operations: • Parenthesis

  • • Multiplication / divisionAddition / subtraction

—- Removing duplicates SELECT FROM customers DISTINCT state

IN Operator —- Returns customers in any of these states: VA, NY, CA

SELECT FROM customers * WHERE state IN (‘VA’, ‘NY’, ‘CA’)

BETWEEN Operator SELECT *

FROM WHERE customers points BETWEEN 100 AND 200

LIKE Operator —- Returns customers whose first name starts with b

SELECT FROM customers * WHERE first_name LIKE ‘b%’

  • • %: any number of characters_: exactly one character

REGEXP Operator —- Returns customers whose first name starts with a

SELECT FROM customers * WHERE first_name REGEXP ‘^a’

  • • ^: beginning of a string$: end of a string
  • • |: logical OR[abc]: match any single characters
  • [a-d]: any characters from a to d

More Examples —- WHERE Returns first_name customers REGEXP whose ‘ey$|on$’ first name ends with EY or ON —- —- Returnsor contains customers SE whose first name starts with MY WHERE first_name REGEXP ‘^my|se’ —- —- ReturnsR or U customers whose first name contains B followed by WHERE first_name REGEXP ‘b[ru]’

IS NULL Operator —- Returns customers who don’t have a phone number

SELECT FROM customers * WHERE phone IS NULL

ORDER BY Clause —- Sort customers by state (in ascending order), and then

—- SELECT by their * first name (in descending order) FROM ORDER customers BY state, first_name DESC

LIMIT Clause —- Return only 3 customers

SELECT FROM customers * LIMIT 3

Unions —- Combine records from multiple result sets

SELECT FROM customers name, address UNION SELECT name, address FROM clients

Inserting Data —- Insert a single record

INSERT VALUES INTO(‘Mosh’, customers(first_name, NULL, DEFAULT) phone, points)

—- INSERT Insert INTO multiple customers(first_name, single records phone, points) VALUES (‘Mosh’, NULL, DEFAULT), (‘Bob’, ‘1234’, 10)