Harish Kumar

SQL Cheat Sheet

Published on 16 August 2020 · sql query

QUERY FROM A TABLE

Create a new column with three column

SELECT c1, c2 FROM t; 

Delete the table from the database

DROP TABLE t;

Add a new column to the table

ALTER TABLE t ADD column;


QUERYING FROM MULTIPLE TABLES

Inner join t1 and t2

SELECT c1, c2 FROM t1 INNER JOIN t2 on condition;

Left join t1 and t2

SELECT c1, c2 FROM t1 LEFT JOIN t2 ON condition;

Produce a Cartesian product of rows in tables

SELECT c1, c2 FROM t1 CROSS JOIN t2;


USING SQL OPERATORS

Query rows between two values

SELECT c1, c2 FROM t WHERE c1 BETWEEN low AND high

Combine rows from two queries

SELECT c1, c2 FROM t1 UNION [ALL] SELECT c1, c2 FROM t2;

Check if values in a table is NULL or not

SELECT c1, c2 FROM t WHERE c1 IS [NOT] NULL;


MODIFYING DATA

Insert one row into a table

INSERT INTO t(column_list) VALUES(value_list);

Update new value in the column c1 for all rows

UPDATE t SET c1=new_value;

Delete all data in a table

DELETE FROM t;

Delete subset of rows in a table

DELETE FROM t WHERE condition;


MANAGING VIEWS

Create a new view that consist of c1 and c2

CREATE VIEW v(c1, c2) AS SELECT c1, c2 FROM t;

Create a temporary view

CREATE TEMPORARY VIEW v AS SELECT c1, c2 FROM t;