Skip to content

Instantly share code, notes, and snippets.

@AndrewSavetchuk
Last active August 20, 2024 19:44
Show Gist options
  • Save AndrewSavetchuk/41e5402459669d3a926905c9e93cf795 to your computer and use it in GitHub Desktop.
Save AndrewSavetchuk/41e5402459669d3a926905c9e93cf795 to your computer and use it in GitHub Desktop.

Truncate Table

Truncate table with disabled foreign key checks.

SET FOREIGN_KEY_CHECKS=0;

TRUNCATE TABLE table_name;

SET FOREIGN_KEY_CHECKS=1;

Update Table Column

Update a single table column and set new value.

UPDATE table_name SET column_name = NULL;

Update a single table column where the condition is met and set the new value.

UPDATE table_name SET column_name = NULL WHERE condition;

Display Duplicate Values

SELECT column_name from table_name GROUP BY column_name HAVING count(column_name) > 1;

Example

Input:
Users table:
+----+---------+
| id | email   |
+----+---------+
| 1  | [email protected] |
| 2  | [email protected] |
| 3  | [email protected] |
+----+---------+

Output: 
+---------+
| email   |
+---------+
| [email protected] |
+---------+

Explanation: [email protected] is repeated two times.

Solution

SELECT email from users GROUP BY email HAVING count(email) > 1;

Select Second Max Value

Select second max value from the table. If there is no second highest value, the query should report null.

Example

Input: 
+----+--------+
| id | value  |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+

Output: 
+---------------------+
| SecondHighestValue  |
+---------------------+
| 200                 |
+---------------------+
Input: 
+----+--------+
| id | value  |
+----+--------+
| 1  | 100    |
+----+--------+

Output: 
+---------------------+
| SecondHighestValue  |
+---------------------+
| null                |
+---------------------+

Solution

SELECT MAX(value) as SecondHighestValue FROM TableName WHERE value < (SELECT MAX(value) FROM TableName);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment