0% found this document useful (0 votes)
3 views

SQL Database Cheat Sheet-1

This document is a comprehensive SQL Database Cheat Sheet covering Data Definition Language (DDL) and Data Manipulation Language (DML) commands. It includes syntax for creating, altering, and dropping database objects, as well as inserting, updating, deleting, and selecting data. Additionally, it outlines data types, constraints, joins, aggregate functions, and the use of subqueries.

Uploaded by

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

SQL Database Cheat Sheet-1

This document is a comprehensive SQL Database Cheat Sheet covering Data Definition Language (DDL) and Data Manipulation Language (DML) commands. It includes syntax for creating, altering, and dropping database objects, as well as inserting, updating, deleting, and selecting data. Additionally, it outlines data types, constraints, joins, aggregate functions, and the use of subqueries.

Uploaded by

Football& Babgy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

SQL Database Cheat Sheet

DDL ( Data Definition Language ):

Specify data types, structures and constraints for the data to be stored in the database.

• CREATE: Creates a new table or any other database object.


• ALTER: Modifies an existing database object, such as a table.
• DROP: Removes an entire table or any other object in database.

• CREATE:

CREATE DATABASE <DB_Name>; // Create a database


CREATE TABLE <Table_Name> // Create a table
(
STAFF_ID int Primary Key,
STAFF_NAME char(20) Not Null,
STAFF_SALARY real Null,
STAFF_PHOTO image Null
);

• DROP:

DROP DATABASE <DB_Name>; // Drop a database


DROP TABLE <Table_Name>; // Drop a table

• ALTER:

ALTER TABLE <Table_Name> // Add a column


ADD <Column_Name> <Data_Type>;

ALTER TABLE <Table_Name> // Change datatype of a column


ALTER COLUMN <Column_Name> <New_DataType>;

ALTER TABLE <Table_Name> // Remove a column


DROP COLUMN <Column_Name>;

1
• Data Types:

1. Numeric: INT, SMALLINT, BIGINT, FLOAT, REAL


2. Character: CHAR(n) → Fixed Length VARCHAR(n) → Variable Length
3. Boolean: TRUE or FALSE
4. Timestamp

• SQL Constraints:
NOT NULL: A Constraint that ensures that a column cannot have NULL value.
DEFAULT: A Constraint that provides a default value for a column when none is specified.
UNIQUE: A Constraint that ensures that all values in a column are different or NULL.
PRIMARY KEY (PK): A Constraint that uniquely identify each row/record in a database table
(NOT NULL + UNIQUE).
FOREIGN KEY (FK): A Constraint that ensures referential integrity. A foreign key from 1
table to another is used link a tuple in the 1st table to a unique tuple in the 2nd table.
CHECK: A constraint that ensures that all values in a column satisfy a certain condition.

// Add PK to Student table


ALTER TABLE STUDENT
ADD PRIMARY KEY (SSN);
// OR
ALTER TABLE STUDENT
ADD CONSTRAINT PK1 PRIMARY KEY (SSN);

// Add FK Constraint to Student table


ALTER TABLE STUDENT
ADD CONSTRAINT FK_1 FOREIGN KEY (Major) REFERENCES Department
(DeptCode);

// Delete a unique constraint


ALTER TABLE <Table_Name>
DROP CONSTRAINT <Constraint_Name>;

2
DML ( Data Manipulation Language ):

( INSERT – UPDATE – DELETE – SELECT )

• INSERT:

// Adding all values to all columns (The order is important)


INSERT INTO <Table_Name> VALUES ( 1, ‘Ali’, 20, ‘Cairo’ );

// Adding to specific columns


INSERT INTO <Table_Name> ( Id, Name, Age, City ) VALUES ( 1, ‘Ali’, 20, ‘Cairo’ );

• UPDATE:

// Change a value to all rows


UPDATE <Table_Name> SET Age = Age + 1;

// Using WHERE Clause


UPDATE <Table_Name> SET Name = ‘Ahmed’, Age = 20 WHERE Id = 20230200;

• DELETE:

// Delete all table values


DELETE FROM <Table_Name>;

// Delete a specific value


DELETE FROM <Table_Name> WHERE Id = 20;
DELETE FROM <Table_Name> WHERE Id = 20 OR Id = 10;

// OR
DELETE FROM <Table_Name> WHERE Id IN ( 10, 20 );

3
• SELECT:

// Select specific columns


SELECT Column1, Column2 FROM <Table_Name> WHERE <Condition>;

// Select all attributes


SELECT * FROM <Table_Name>;

// Distinct Keyword (Removes any duplicates)


SELECT DISTINCT Column FROM <Table_Name>;

// Instead of using AND


SELECT Name FROM Student WHERE Age >= 19 AND Age <= 22;

// Use BETWEEN Age1 AND Age2


SELECT Name FROM Student WHERE Age BETWEEN 19 AND 22;

// using LIKE
SELECT Name FROM Student WHERE Name LIKE ‘A%’;

‘A%’ → Starting with A ‘%A’ → Ending with A


‘%A%’ → Including A ‘_a%’ → Second letter is a

// Ordering values
SELECT Name, Age FROM Student ORDER BY Age;
SELECT Name, Age FROM Student ORDER BY Age DESC;

// SQL Select Top Clause


SELECT TOP 5 * FROM Student WHERE Age > 20;
SELECT TOP 50 PERCENTAGE * FROM Student;

// SQL Alias
SELECT Products.productid FROM Products AS ID

4
• JOINS:

// Inner Join = Intersection


SELECT column_name(s)
FROM table1 INNER JOIN table2
ON table1.column_name = table2.column_name;
// OR
SELECT column_name(s)
FROM table1, table2 INNER JOIN
WHERE table1.column_name = table2.column_name;

// Left Join = Table on the left + Intersection


SELECT column_name(s)
FROM table1 LEFT OUTTER JOIN table2
ON table1.column_name = table2.column_name; LEFT JOIN

// Right Join = Table on the right+ Intersection


SELECT column_name(s)
FROM table1 RIGHT OUTTER JOIN table2
ON table1.column_name = table2.column_name;
RIGHT JOIN

// Full Join = Table1 + Table2


SELECT column_name(s)
FROM table1 FULL OUTTER JOIN table2
ON table1.column_name = table2.column_name;
FULL JOIN

// Cross Join = It gives combinations of each row of first table with all records
in second table.
SELECT column_name(s)
FROM table1 CROSS JOIN table2;

CROSS JOIN

5
• SET OPERATORS: ( The columns: same order, data type, and number )

// UNION
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2

// UNION ALL
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2

// INTERSECT
SELECT column_name(s) FROM table1
INTERSECT
SELECT column_name(s) FROM table2

// EXCEPT
SELECT column_name(s) FROM table1
EXCEPT
SELECT column_name(s) FROM table2

• AGGREGATE FUNCTIONS:
( COUNT( ) – SUM( ) – AVR( ) – MAX( ) – MIN( ) )
All aggregate functions ignore NULL values when it performs the calculation, except for
the count function.
COUNT(column_name) → ignore NULL
COUNT(*) → counts NULL

6
• GROUP BY:
Group by is used to group a set of rows by a specific column or columns and use
aggregations over these groups.

// For each country, list the number of customers.


SELECT Country, COUNT(CustomerID)
FROM Customers
GROUP BY Country;

• HAVING:
The HAVING clause works as a condition on the groups resulting from the GROUP BY
clause, because the WHERE keyword could not be used with aggregate functions.

// List the number of customers in each country. Only include countries with
more than 5 customers.
SELECT Country, COUNT(CustomerID)
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;

• SQL SYNTAX SUMMARY:

SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);

7
• SUB QUERY / NESTED QUERY:
A subquery is a query nested within another query.
A subquery is called an inner query while the query that contains the subquery is called
an outer query. A subquery must be enclosed in parentheses.

// Display the first name of all employees who are living in UK and have the
same job title as Omar or Amr.
SELECT FirstName
FROM Employees
WHERE Country = ‘UK’
AND Title IN ( SELECT Title
FROM Employees
WHERE FirstName IN (‘Omar’, ‘Amr’) );

Simple sub queries: inner queries that do not reference any columns in the outer query.
Correlated sub queries: inner queries that do reference columns in the outer query.

• SUB QUERY WITH EXISTS / NOT EXISTS OPERATOR:

EXISTS returns FALSE if the subquery returns no rows.


NOT EXISTS returns TRUE if the subquery returns no rows.

// Get the names of customers who placed orders with amount over 5000.

SELECT CustomerName
FROM Customer
WHERE EXISTS ( SELECT Id
FROM CustomerOrder
WHERE CustomerId = Customer.Id
AND TotalAmount > 5000 );
// Get the names of customers who did not place orders with amount over 5000.

SELECT CustomerName
FROM Customer
WHERE NOT EXISTS ( SELECT Id
FROM CustomerOrder
WHERE CustomerId = Customer.Id
AND TotalAmount > 5000 );

You might also like