SQL, the lifeπ©Έof databases, can either be your best friend π€ or your biggest time sink β. Whether you're wrangling data as a developer π¨βπ» or managing databases as an administrator, these 5οΈβ£ tricks are designed to make your SQL journey smoother π . I have tried these on my own and they have helped me to do things faster and more efficiently.
The WHERE & NULL weird relationship π«¨
SELECT * FROM Customers WHERE NAME = 'SHOBHIT'; β
SELECT * FROM Customers WHERE Name = NULL; β
SQL treats NULL as a special marker for missing or unknown data, and standard equality comparison (=) doesn't work with NULL.
SELECT * FROM Customers WHERE Name IS NULL; β
SELECT * FROM Customers WHERE Name IS NOT NULL; β
Undo PRODUCTION Queries π€©π
START TRANSACTION;
UPDATE Customers SET membership = true WHERE fees > 5000;
ROLLBACK;
A transaction
is a sequence of one or more SQL statements that are executed as a single unit of work. If you encounter any issues or want to cancel the changes made within the transaction, you can use a ROLLBACK
command to undo those changes.
However, if you don't face any issues, you can use COMMIT
instead of ROLLBACK
to end the transaction.
SARGABLE & NON-SARGABLE QUERIES π§π€¨π€
This concept will be more clearly understood if you have worked with indexes. For now, you can consider them as database structures that improve query performance by allowing for faster data retrieval based on specific columns
.
-- Search ARGument ABLE
SELECT * FROM customers WHERE LAST_NAME = 'SMITH'
-- Search ARGument NOT ABLE
SELECT * FROM customers WHERE UPPER(last_name) = 'SMITH'
Now, while executing the
Using ORDER BY Clause Efficiently π
This is quite a small enhancement but is quite useful when one has to work with SQL queries his/her whole day. (No offense π)
SELECT Title, ReleaseDate, Rating
FROM Movies
WHERE ReleaseDate BETWEEN '2010-01-01' AND '2020-12-31'
ORDER BY ReleaseDate DESC π
LIMIT 10;
SELECT Title, ReleaseDate, Rating
FROM Movies
WHERE ReleaseDate BETWEEN '2010-01-01' AND '2020-12-31'
ORDER BY 2 DESC π
LIMIT 10;
Hence, Instead of naming a particular column, we can just use a number which will depend upon the position of the SQL SELECT query π
β¨· Handling Multiple WHERE Conditions β¨·
-- Different Parameters
SELECT *
FROM Customers
WHERE Country = 'USA'
AND City = 'New York'
AND Age >= 25;
-- Don't Need to Add Where Multiple Times
-- Same Parameters
SELECT *
FROM Customers
WHERE Country = 'USA'
AND Country = 'India' β βΉοΈ
--------
SELECT *
FROM Customers
WHERE Country = 'USA'
OR Country = 'India' β
π
--------
SELECT *
FROM Customers
WHERE Country IN ('USA','INDIA') β
π
Well, That brings us to the end βοΈ of the article. If you want more such content do subscribe to my newsletter π°. Also, you can follow me on Twitter π to get daily updates about the web world π€.