simple queries Flashcards
select in descending order
SELECT Name
FROM Student
WHERE course IN [‘C1’, ‘C2’,C4]
ORDER BY Name DESC, course ASC
group with count example
SELECT Speciality, Count ()
FROM Student
GROUP BY Speciality
HAVING COUNT () > 2
Update example
UPDATE myDB.students
SET fname = ‘Captain’, lname = ‘America’
WHERE student_id =
UNION
SELECT name FROM Students
UNION
SELECT name FROM Contacts;
UNION with duplicates
SELECT name FROM Students
UNION ALL
SELECT name FROM Contacts;
MINUS
SELECT name FROM Students
MINUS
SELECT name FROM Contacts;
INTERSECT
SELECT name FROM Students
INTERSECT
SELECT name FROM Contacts;
cursor
DECLARE @name VARCHAR(50) /* Declare All Required Variables */
DECLARE db_cursor CURSOR FOR /* Declare Cursor Name*/
SELECT name
FROM myDB.students
WHERE parent_name IN (‘Sara’, ‘Ansh’)
OPEN db_cursor /* Open cursor and Fetch data into @name */
FETCH next
FROM db_cursor
INTO @name
CLOSE db_cursor /* Close the cursor and deallocate the resources */
DEALLOCATE db_cursor
alias example
SELECT A.emp_name AS “Employee” /* Alias using AS keyword /
B.emp_name AS “Supervisor”
FROM employee A, employee B / Alias without AS keyword */
WHERE A.emp_sup = B.emp_id;
Truncate
TRUNCATE command is used to delete all the rows from the table and free the space containing the table.
TRUNCATE TABLE Candidates;
Aggregate functions
AVG() - Calculates the mean of a collection of values.
COUNT() - Counts the total number of records in a specific table or view.
MIN() - Calculates the minimum of a collection of values.
MAX() - Calculates the maximum of a collection of values.
SUM() - Calculates the sum of a collection of values.
FIRST() - Fetches the first element in a collection of values.
LAST() - Fetches the last element in a collection of values.
Scalar functions
LEN() - Calculates the total length of the given field (column).
UCASE() - Converts a collection of string values to uppercase characters.
LCASE() - Converts a collection of string values to lowercase characters.
MID() - Extracts substrings from a collection of string values in a table.
CONCAT() - Concatenates two or more strings.
RAND() - Generates a random collection of numbers of given length.
ROUND() - Calculates the round off integer value for a numeric field (or decimal point values).
NOW() - Returns the current data & time.
FORMAT() - Sets the format to display a collection of values
Using the % wildcard to perform a simple search
SELECT *
FROM students
WHERE first_name LIKE ‘K%’
Omitting the patterns using the NOT keyword
SELECT *
FROM students
WHERE first_name NOT LIKE ‘K%’
Using the _ wildcard to match pattern at a specific position
SELECT *
FROM students
WHERE first_name LIKE ‘__K%’