Hello 👋🏾 New blog post new dataday post... it's all about SQL queries
📓 All the examples below are based on this table ⬇️.
Customers | |||
ID | firstname | lastname | Country |
1 | John | Doe | Germany |
2 | Alice | Smith | UK |
3 | Sam | Doe | South Korea |
4 | Jessica | Mark | UK |
5 | Alex | Ami | Malaysia |
📝 Statement is the query.
SELECT
- this statement is used to select data from a database.
- Select DISTINCT is used to return only different values.
Example
Select * from Customers;
#returns all the table
Select DISTINCT Country from Customers;
#returns Germany, UK, South Korea, Malaysia
WHERE clause
- This clause is used to filter records.
- And is used to extract only those records that a specified condition.
- Operators in WHERE clause (= , > , <, != , BETWEEN, LIKE, IN).
Example
SELECT * FROM Customers WHERE Country = 'UK'
SQL AND, OR and NOT
- AND displays a record if all conditions are TRUE.
- OR displays a record if any of the conditions separated by OR is TRUE.
- NOT displays a record if the condition(s) is NOT TRUE.
Example
SELECT * FROM Customers WHERE lastname = "Doe" AND (Country= 'Germany' OR 'South Korea');
SQL ORDER BY keyword
- This one is used to sort the result in ascending or descending order, by default the records are ascending.
INSERT INTO
- This statement is used to insert a new row into a table.
Example
INSERT INTO Customers (firstname, lastname, country) VALUES ('james', 'bond', 'Finland')
SQL Null Values
- first Null value is equal to no value.
- It's not like zero value, it is a value that has been left blank during record creation.
Example
SELECT firstname FROM Customers WHERE firstname IS NULL;
#this query will not return anything.
SQL UPDATE
- update is to change existing records in a table.
- ⚠️ if you omit WHERE clause, All records will be updated
Example
UPDATE Customers SET firstname= 'Amy', lastname = 'Alex' WHERE ID=2;
#this will change Alice Smith to Amy Alex
SQL DELETE
- delete statement is used to delete existing records in a table.
Example
DELETE FROM Customers WHERE ID=2;
#this will delete id 2.
SQL SELECT TOP
- select top is used to specify the number of records to return.
- useful on large tables.
Example
#sql server
SELECT TOP 3 * FROM Customers;
#MYSQL
SELECT * FROM Customers Limit 3;
#oracle
SELECT * FROM Customers FETCH FIRST 3 ROWS ONLY;
I hope you enjoyed reading :)
You can reach me on Linkedin