SELECT Clause
WHERE Clause
SQL Query Syntax & Security
SQL SELECT Statement Structure
SELECT: Specifies the columns to retrieve. Use * for all columns.
FROM: Specifies the table to query.
WHERE: Filters rows based on conditions. Multiple conditions can be combined with AND/OR.
ORDER BY: Sorts the result set by specified column(s). ASC for ascending, DESC for descending.
LIMIT: Restricts the number of rows returned.
SQL Injection Prevention:
This tool automatically parameterizes values to prevent SQL injection attacks. Always use parameterized queries in production code.
❌ Vulnerable (DO NOT USE):
SELECT * FROM users WHERE username = '" + userInput + "'
✅ Secure (Use parameterized queries):
SELECT * FROM users WHERE username = ?
Frequently Asked Questions
SQL injection is a code injection technique that attackers use to execute malicious SQL statements by manipulating user input.
Example of SQL injection attack:
If a login form uses this vulnerable code:
String query = "SELECT * FROM users WHERE username = '" + username + "' AND password = '" + password + "'";
An attacker could enter:
- Username:
admin'-- - Password: [anything]
This would create the query:
SELECT * FROM users WHERE username = 'admin'--' AND password = 'anything'
The -- comments out the rest of the query, allowing unauthorized access.
How this tool prevents SQL injection:
- Parameterization: All values are treated as parameters, not executable code
- Input sanitization: Special characters are properly escaped
- Safe formatting: Generated SQL uses proper quoting and escaping
- Validation: Inputs are validated before being included in queries
Best practices for production code:
- Always use parameterized queries or prepared statements
- Validate and sanitize all user inputs
- Use stored procedures when appropriate
- Implement least privilege database access
- Regularly audit and test your applications
SQL operators are used in WHERE clauses to filter records. Here are the most common ones:
| Operator | Description | Example |
|---|---|---|
= |
Equal | WHERE age = 25 |
!= or <> |
Not equal | WHERE status != 'inactive' |
>, < |
Greater/Less than | WHERE salary > 50000 |
>=, <= |
Greater/Less than or equal | WHERE age >= 18 |
LIKE |
Pattern matching | WHERE name LIKE 'J%' |
IN |
Match any in a list | WHERE id IN (1, 2, 3) |
BETWEEN |
Between a range | WHERE age BETWEEN 18 AND 65 |
IS NULL |
Null check | WHERE email IS NULL |
LIKE Operator Wildcards:
%– Matches any sequence of characters (zero or more)_– Matches exactly one character
Examples:
WHERE name LIKE 'A%'– Names starting with ‘A’WHERE name LIKE '%son'– Names ending with ‘son’WHERE name LIKE '_ohn'– 4-letter names ending with ‘ohn’WHERE name LIKE '%test%'– Names containing ‘test’
Combining Conditions:
AND– All conditions must be trueOR– At least one condition must be trueNOT– Negates a condition
Example: WHERE (age > 18 AND status = 'active') OR is_admin = true
SQL query optimization is crucial for application performance. Here are key optimization techniques:
1. Use Specific Columns Instead of SELECT *
Inefficient: SELECT * FROM users
Optimized: SELECT id, name, email FROM users
Fetching only needed columns reduces data transfer and memory usage.
2. Add Appropriate Indexes
Indexes speed up WHERE, JOIN, and ORDER BY operations:
CREATE INDEX idx_email ON users(email); CREATE INDEX idx_dept_salary ON employees(department, salary);
Index Best Practices:
- Index columns used in WHERE, JOIN, and ORDER BY clauses
- Use composite indexes for multiple column queries
- Avoid over-indexing (indexes slow down INSERT/UPDATE/DELETE)
- Regularly analyze and rebuild fragmented indexes
3. Use LIMIT for Large Result Sets
Optimized: SELECT * FROM logs ORDER BY timestamp DESC LIMIT 100
4. Avoid Functions on Indexed Columns in WHERE
Inefficient: WHERE YEAR(created_at) = 2023
Optimized: WHERE created_at BETWEEN '2023-01-01' AND '2023-12-31'
5. Use EXISTS Instead of IN for Subqueries
Inefficient:
SELECT * FROM users WHERE id IN (SELECT user_id FROM orders WHERE total > 1000)
Optimized:
SELECT * FROM users u WHERE EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id AND o.total > 1000)
6. Avoid SELECT DISTINCT When Possible
DISTINCT requires sorting and removing duplicates, which is expensive. Consider using GROUP BY or reviewing data model.
7. Use UNION ALL Instead of UNION When Possible
UNION removes duplicates (expensive), while UNION ALL doesn’t (faster).
8. Monitor Query Performance
Use database tools to analyze query execution plans:
- MySQL:
EXPLAIN SELECT ... - PostgreSQL:
EXPLAIN ANALYZE SELECT ... - SQL Server: Include Actual Execution Plan
9. Pagination for Large Datasets
Instead of loading all records, use pagination:
-- Offset pagination (simpler but slower for deep pages) SELECT * FROM products ORDER BY id LIMIT 20 OFFSET 40; -- Keyset pagination (faster for deep pages) SELECT * FROM products WHERE id > 40 ORDER BY id LIMIT 20;
Performance Checklist:
- ❑ Use specific columns instead of SELECT *
- ❑ Add indexes on frequently queried columns
- ❑ Use LIMIT to restrict result sets
- ❑ Avoid functions on indexed columns in WHERE
- ❑ Use EXISTS instead of IN for subqueries
- ❑ Review execution plans regularly
- ❑ Implement proper pagination
- ❑ Regularly update database statistics
While SQL is a standard language, different database systems have their own dialects and extensions. Here are key differences:
Syntax Differences
| Feature | MySQL | PostgreSQL | SQL Server |
|---|---|---|---|
| String Concatenation | CONCAT() |
|| or CONCAT() |
+ or CONCAT() |
| Current Date/Time | NOW() |
CURRENT_TIMESTAMP |
GETDATE() |
| Top N Rows | LIMIT n |
LIMIT n |
TOP n |
| Auto-increment | AUTO_INCREMENT |
SERIAL or identity columns |
IDENTITY(1,1) |
| Boolean Type | TINYINT(1) or BOOL |
BOOLEAN |
BIT |
Feature Support
| Feature | MySQL | PostgreSQL | SQL Server |
|---|---|---|---|
| Window Functions | ✓ (8.0+) | ✓ Excellent | ✓ (2005+) |
| Common Table Expressions | ✓ (8.0+) | ✓ Excellent | ✓ (2005+) |
| JSON Support | ✓ (5.7+) | ✓ Excellent | ✓ (2016+) |
| Full-Text Search | ✓ Built-in | ✓ Built-in | ✓ Built-in |
| Geospatial Data | ✓ | ✓ Excellent (PostGIS) | ✓ |
Portability Tips
To write more portable SQL:
- Use standard SQL functions: Prefer
COALESCE()overIFNULL()(MySQL) orISNULL()(SQL Server) - Standard date format: Use ISO format
YYYY-MM-DD HH:MI:SS - String quoting: Use single quotes for strings:
'text' - Identifier quoting: Use double quotes for identifiers with spaces:
"table name" - Case sensitivity: Be aware that identifier case sensitivity varies by platform and configuration
When to Choose Which Database:
- MySQL: Web applications, simple to moderate complexity, high read workloads
- PostgreSQL: Complex queries, data integrity, advanced features, geospatial data
- SQL Server: Enterprise applications, Windows ecosystem, business intelligence
Note: The SQL generated by this tool uses ANSI SQL standards that are compatible with most database systems.