SQL Query Playground
Test your SQL queries in this interactive environment. Try different examples and see instant feedback!
SQL Fundamentals
Retrieve data from one or more tables. The most fundamental SQL command.
-- Basic SELECT
SELECT column1, column2 FROM table_name;
-- SELECT with WHERE clause
SELECT * FROM customers
WHERE country = 'USA' AND age > 25;
-- SELECT DISTINCT
SELECT DISTINCT country FROM customers;
Filter records based on specific conditions.
-- Comparison operators
SELECT * FROM products
WHERE price >= 100 AND stock < 50;
-- LIKE operator (pattern matching)
SELECT * FROM employees
WHERE name LIKE 'John%';
-- IN operator
SELECT * FROM orders
WHERE status IN ('Pending', 'Processing');
-- BETWEEN operator
SELECT * FROM sales
WHERE sale_date BETWEEN '2024-01-01' AND '2024-12-31';
Sort the result set in ascending or descending order.
-- Ascending order (default)
SELECT * FROM employees
ORDER BY salary ASC;
-- Descending order
SELECT * FROM products
ORDER BY price DESC;
-- Multiple columns
SELECT * FROM students
ORDER BY grade DESC, name ASC;
Add new records to a table.
-- Insert single row
INSERT INTO customers (name, email, country)
VALUES ('John Doe', 'john@email.com', 'USA');
-- Insert multiple rows
INSERT INTO products (name, price, stock)
VALUES
('Laptop', 999.99, 50),
('Mouse', 29.99, 200),
('Keyboard', 79.99, 150);
Modify existing records in a table.
-- Update single column
UPDATE employees
SET salary = 75000
WHERE employee_id = 101;
-- Update multiple columns
UPDATE customers
SET email = 'newemail@example.com',
phone = '555-1234'
WHERE customer_id = 501;
Remove records from a table.
-- Delete specific records
DELETE FROM orders
WHERE order_date < '2023-01-01';
-- Delete all records (use with caution!)
DELETE FROM temp_data;
Advanced SQL Techniques
Queries within queries for complex data retrieval.
-- Subquery in WHERE clause
SELECT name, salary
FROM employees
WHERE salary > (
SELECT AVG(salary) FROM employees
);
-- Subquery in FROM clause
SELECT dept_name, avg_salary
FROM (
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department
) AS dept_averages;
Create temporary named result sets for better query readability.
-- Simple CTE
WITH HighEarners AS (
SELECT employee_id, name, salary
FROM employees
WHERE salary > 100000
)
SELECT * FROM HighEarners;
-- Multiple CTEs
WITH
SalesCTE AS (
SELECT product_id, SUM(quantity) AS total_sold
FROM sales
GROUP BY product_id
),
ProductCTE AS (
SELECT product_id, product_name, price
FROM products
)
SELECT p.product_name, p.price, s.total_sold
FROM ProductCTE p
JOIN SalesCTE s ON p.product_id = s.product_id;
Perform calculations across sets of rows related to the current row.
-- ROW_NUMBER()
SELECT
employee_id,
name,
salary,
ROW_NUMBER() OVER (ORDER BY salary DESC) AS salary_rank
FROM employees;
-- RANK() and DENSE_RANK()
SELECT
product_name,
category,
price,
RANK() OVER (PARTITION BY category ORDER BY price DESC) AS price_rank
FROM products;
-- Running total with SUM()
SELECT
order_date,
revenue,
SUM(revenue) OVER (ORDER BY order_date) AS running_total
FROM daily_sales;
Add conditional logic to your queries.
-- Simple CASE
SELECT
name,
salary,
CASE
WHEN salary < 50000 THEN 'Low'
WHEN salary < 100000 THEN 'Medium'
ELSE 'High'
END AS salary_category
FROM employees;
-- CASE in aggregation
SELECT
department,
SUM(CASE WHEN gender = 'M' THEN 1 ELSE 0 END) AS male_count,
SUM(CASE WHEN gender = 'F' THEN 1 ELSE 0 END) AS female_count
FROM employees
GROUP BY department;
Combine results from multiple SELECT statements.
-- UNION (removes duplicates)
SELECT customer_id, name FROM customers_usa
UNION
SELECT customer_id, name FROM customers_canada;
-- UNION ALL (keeps duplicates)
SELECT product_id, sales_amount FROM sales_2023
UNION ALL
SELECT product_id, sales_amount FROM sales_2024;
Check for the existence of rows in a subquery.
-- EXISTS example
SELECT customer_id, name
FROM customers c
WHERE EXISTS (
SELECT 1 FROM orders o
WHERE o.customer_id = c.customer_id
AND o.order_date > '2024-01-01'
);
-- NOT EXISTS example
SELECT product_id, product_name
FROM products p
WHERE NOT EXISTS (
SELECT 1 FROM sales s
WHERE s.product_id = p.product_id
);
SQL Functions & Operators
Aggregate Functions
-- COUNT() - Count rows
SELECT COUNT(*) FROM orders;
SELECT COUNT(DISTINCT customer_id) FROM orders;
-- SUM() - Calculate total
SELECT SUM(amount) AS total_revenue FROM sales;
-- AVG() - Calculate average
SELECT AVG(salary) AS avg_salary FROM employees;
-- MIN() and MAX()
SELECT MIN(price) AS lowest_price, MAX(price) AS highest_price
FROM products;
-- GROUP BY with aggregates
SELECT department, COUNT(*) AS emp_count, AVG(salary) AS avg_salary
FROM employees
GROUP BY department;
-- HAVING clause (filter after grouping)
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department
HAVING AVG(salary) > 75000;
String Functions
-- CONCAT() - Combine strings
SELECT CONCAT(first_name, ' ', last_name) AS full_name
FROM employees;
-- UPPER() and LOWER()
SELECT UPPER(name), LOWER(email) FROM customers;
-- SUBSTRING() - Extract part of string
SELECT SUBSTRING(product_code, 1, 3) AS category_code
FROM products;
-- LENGTH() - Get string length
SELECT name, LENGTH(name) AS name_length FROM customers;
-- TRIM() - Remove spaces
SELECT TRIM(email) AS clean_email FROM users;
-- REPLACE() - Replace text
SELECT REPLACE(phone, '-', '') AS clean_phone
FROM contacts;
Date & Time Functions
-- CURRENT_DATE and CURRENT_TIMESTAMP
SELECT CURRENT_DATE, CURRENT_TIMESTAMP;
-- DATE_FORMAT() - Format dates
SELECT DATE_FORMAT(order_date, '%Y-%m-%d') FROM orders;
-- DATEDIFF() - Calculate date difference
SELECT DATEDIFF(CURRENT_DATE, hire_date) AS days_employed
FROM employees;
-- DATE_ADD() and DATE_SUB()
SELECT DATE_ADD(CURRENT_DATE, INTERVAL 7 DAY) AS next_week;
SELECT DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) AS last_month;
-- EXTRACT() - Get specific date parts
SELECT EXTRACT(YEAR FROM order_date) AS order_year,
EXTRACT(MONTH FROM order_date) AS order_month
FROM orders;
Mathematical Functions
-- ROUND() - Round numbers
SELECT ROUND(price, 2) AS rounded_price FROM products;
-- CEILING() and FLOOR()
SELECT CEILING(price), FLOOR(price) FROM products;
-- ABS() - Absolute value
SELECT ABS(profit_loss) FROM financial_records;
-- POWER() and SQRT()
SELECT POWER(2, 3) AS result; -- 2^3 = 8
SELECT SQRT(16) AS result; -- √16 = 4
-- MOD() - Modulo operation
SELECT MOD(10, 3) AS remainder; -- 10 % 3 = 1
SQL Joins & Relationships
Returns records that have matching values in both tables.
-- Basic INNER JOIN
SELECT
customers.name,
orders.order_id,
orders.order_date,
orders.total_amount
FROM customers
INNER JOIN orders
ON customers.customer_id = orders.customer_id;
-- Multiple table joins
SELECT
c.name AS customer_name,
o.order_id,
p.product_name,
oi.quantity
FROM customers c
INNER JOIN orders o ON c.customer_id = o.customer_id
INNER JOIN order_items oi ON o.order_id = oi.order_id
INNER JOIN products p ON oi.product_id = p.product_id;
Returns all records from the left table and matching records from the right table.
-- LEFT JOIN example
SELECT
c.customer_id,
c.name,
o.order_id,
o.order_date
FROM customers c
LEFT JOIN orders o
ON c.customer_id = o.customer_id;
-- Find customers with no orders
SELECT
c.customer_id,
c.name
FROM customers c
LEFT JOIN orders o
ON c.customer_id = o.customer_id
WHERE o.order_id IS NULL;
Returns all records from the right table and matching records from the left table.
-- RIGHT JOIN example
SELECT
o.order_id,
o.order_date,
c.name
FROM customers c
RIGHT JOIN orders o
ON c.customer_id = o.customer_id;
Returns all records when there is a match in either left or right table.
-- FULL OUTER JOIN
SELECT
c.customer_id,
c.name,
o.order_id,
o.order_date
FROM customers c
FULL OUTER JOIN orders o
ON c.customer_id = o.customer_id;
Returns the Cartesian product of both tables (all possible combinations).
-- CROSS JOIN example
SELECT
colors.color_name,
sizes.size_name
FROM colors
CROSS JOIN sizes;
Join a table to itself to compare rows within the same table.
-- Find employees and their managers
SELECT
e1.name AS employee_name,
e2.name AS manager_name
FROM employees e1
LEFT JOIN employees e2
ON e1.manager_id = e2.employee_id;
Join Comparison Table
| Join Type | Description | Use Case |
|---|---|---|
| INNER JOIN | Returns only matching records | Get orders with customer details |
| LEFT JOIN | All left table + matching right | Find customers with/without orders |
| RIGHT JOIN | All right table + matching left | All orders even if customer deleted |
| FULL OUTER JOIN | All records from both tables | Complete data reconciliation |
| CROSS JOIN | Cartesian product | Generate all size-color combinations |
| SELF JOIN | Table joined to itself | Employee-manager relationships |
User Guide
Learn how to use this advanced SQL cheat sheet tool effectively.
- Write Your Query: Type or paste your SQL query in the editor
- Load Examples: Click example buttons to load pre-built queries
- Analyze Query: Click "Analyze Query" to get detailed feedback
- Format Code: Use the format button to beautify your SQL
- Clear Editor: Reset the editor to start fresh
Result Analysis: The tool will show you:
- SQL command type identified
- Tables and columns detected
- Complexity assessment
- Best practices recommendations
- Performance tips
The search bar at the top allows you to quickly find SQL commands, functions, or concepts:
- Type keywords like "JOIN", "SELECT", "aggregate"
- Search works across all tabs and sections
- Results are highlighted in real-time
- Click "Clear" to reset the search
Every code block has a "Copy" button in the top-right corner:
- Click the copy button to copy the entire code block
- You'll see a confirmation toast notification
- Paste directly into your SQL editor or IDE
- Syntax highlighting helps identify different SQL elements
This tool is fully responsive and works on all devices:
- Mobile: Tabs stack vertically, code blocks scroll horizontally
- Tablet: Optimized layout with touch-friendly buttons
- Desktop: Full-width layout with all features visible
- All interactive features work on touch devices
Key Features
Interactive Playground
- Real-time query analysis
- Pre-loaded examples
- Code formatting
- Syntax detection
Comprehensive Reference
- 100+ SQL commands
- 50+ code examples
- All join types
- Advanced techniques
Smart Search
- Instant results
- Cross-tab search
- Keyword highlighting
- Easy navigation
About This Tool
The Advanced SQL Cheat Sheet is a comprehensive, production-ready reference tool designed for both technical developers and non-technical users preparing for SQL interviews or working with databases. This tool combines interactive learning with extensive documentation to help you master SQL.
Purpose & Goals
This tool was created to provide a single, accessible resource for SQL learning and reference. Whether you're preparing for a technical interview, learning SQL for the first time, or need a quick reference for complex queries, this cheat sheet has you covered.
Who Is This For?
Students
Learning SQL for courses or certifications
Job Seekers
Preparing for technical interviews
Developers
Quick reference for daily work
Analysts
Data analysis and reporting
SQL Best Practices & Tips
-
Use Meaningful Table and Column Names
Choose descriptive names that clearly indicate the data they contain. Use underscores for multi-word names (snake_case).
-
Always Use WHERE Clauses in UPDATE/DELETE
Never run UPDATE or DELETE without a WHERE clause in production! Always test with SELECT first.
-
Index Your Columns
Create indexes on columns frequently used in WHERE, JOIN, and ORDER BY clauses for better performance.
-
Use JOINs Instead of Subqueries When Possible
JOINs are often more efficient than subqueries, especially for large datasets.
-
Avoid SELECT * in Production
Explicitly name columns you need. It's clearer, more maintainable, and often faster.
-
Use Transactions for Multiple Operations
Wrap related operations in BEGIN/COMMIT transactions to ensure data consistency.
-
Comment Your Complex Queries
Add comments to explain complex logic. Your future self will thank you!
-
Use LIMIT for Testing
When testing queries on large tables, use LIMIT to return fewer rows initially.
Interesting SQL Facts
History
SQL was developed in the early 1970s at IBM by Donald D. Chamberlin and Raymond F. Boyce.
Universal Language
SQL is used by virtually every database system: MySQL, PostgreSQL, Oracle, SQL Server, SQLite, and more.
Industry Standard
SQL has been an ANSI standard since 1986 and ISO standard since 1987.
Still Relevant
Despite being over 50 years old, SQL remains one of the most in-demand skills in tech.
Common Use Cases
Managing products, orders, customers, and inventory
Business intelligence, reporting, and data analysis
Authentication, permissions, and user profiles
Transactions, accounting, and financial reporting
Interview Preparation Tips
-
Practice Writing Queries by Hand
Many interviews involve whiteboard coding. Practice writing SQL without IDE assistance.
-
Understand Query Execution Order
Know the order: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT
-
Master All Join Types
Be able to explain and write INNER, LEFT, RIGHT, FULL OUTER, CROSS, and SELF joins.
-
Know Performance Optimization
Understand indexes, query optimization, and common performance pitfalls.
-
Study Real-World Scenarios
Practice with realistic data problems: ranking, running totals, finding duplicates, etc.
| Feature | Details |
|---|---|
| Price | Free |
| Rendering | Client-Side Rendering |
| Language | JavaScript |
| Paywall | No |
0 Comments