SQL Queries and Concepts
SQL Queries and Concepts
3. WHERE: It is used to extract only those records that fulfill a specified condition.
- SEELCT ‘column’ FROM ‘table’ WHERE ‘condition’;
- SELECT * FROM Customers WHERE Country='Mexico';
SELECT * FROM PRODUCTS WHERE PRICE = 18;
SELECT * FROM PRODUCTS WHERE PRICE >= 30;
SELECT * FROM PRODUCTS WHERE PRICE <= 30;
SELECT * FROM Products WHERE Price <> 18; || SELECT * FROM Products WHERE Price != 18;
SELECT * FROM Products WHERE Price BETWEEN 50 AND 60;
SELECT * FROM Customers WHERE City LIKE 's%';
SELECT * FROM Customers WHERE City IN ('Paris' , 'London');
5. AND: SELECT * FROM Customers WHERE Country = 'Spain' AND CustomerName LIKE 'G%';
6. OR: SELECT * FROM Customers WHERE City = 'Berlin' OR CustomerName LIKE 'G%' OR Country = 'Norway';
12. COUNT : Returns the count of the number of rows matching the specified criterion
- SELECT COUNT(*) FROM PRODUCTS (Returns the total number of rows)
- SELECT COUNT(COLUMN_NAME) FROM TABLE WHERE CONDITION
- SELECT COUNT(DISTINCT COLUMN_NAME) FROM TABLE WHERE CONDITION
15. SELECT* FROM TABLE_NAME WHERE COL_NAME LIKE ‘anything from the image given below’
16. IN SYNTAX:
- SELECT * FROM Customers WHERE Country IN ('Germany', 'France', 'UK');
- SELECT * FROM Customers WHERE Country NOT IN ('Germany', 'France', 'UK');
- SELECT * FROM Customers WHERE Country IN (SELECT Country FROM Suppliers);
JOINS IN SQL
1. INNER JOIN: Selects rows from both the tables which overlap based on a common column.
- SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE FROM Student INNER JOIN StudentCourse ON
Student.ROLL_NO = StudentCourse.ROLL_NO;
+
2. LEFT JOIN:
SELECT Student.NAME,StudentCourse.COURSE_ID FROM Student LEFT JOIN StudentCourse ON StudentCourse.ROLL_NO =
Student.ROLL_NO;
18. UNION: The UNION operator is used to combine the result-set of two or more SELECT statements.
Every SELECT statement within UNION must have the same number of columns.
The columns must also have similar data types.
The columns in every SELECT statement must also be in the same order.
19) Group By: Groups rows having same values to summary rows. Generally used with Sum(), Count(), Max(), Min()
- SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country;
- SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country ORDER BY COUNT(CustomerID) DESC;
20) HAVING(): Introduced because WHERE() cannot be used with aggregation functions like Count(), Max(), Min()
- SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country HAVING COUNT(CustomerID) > 5;
-
IMPORTANT QUESTION:
1) How to print duplicate rows in a table?
A) Select col_name from table_name group by col_name having count(col_name)>1;
Eg: select name,emp_id,salary,department,age from employees group by name,emp_id,salary,department,age having
count(*)>1;
3) KEYS IN DBMS:
They are one or more attributes in table. Used for uniquely identifying tuple in a table.