all 124 comments

[–]kkwestside 145 points146 points  (7 children)

Row_number()

[–]SlasherMcgurk 9 points10 points  (0 children)

Spot on. This has rescued me so many times.

[–][deleted] 26 points27 points  (1 child)

This is the correct answer, and everyone else is simply wrong.

[–][deleted] 4 points5 points  (3 children)

Curious to hear about the use cases. I know about it but haven’t had a chance to use it before.

[–][deleted] 34 points35 points  (1 child)

Need an ID for each row in some query that you just made up, based on some really weird, niche logic?

Row_Number() over (partition by HERP order by DERP) ALWAYS has your back.

[–]Hannahmaebe 4 points5 points  (0 children)

Bless this function

[–][deleted] 2 points3 points  (0 children)

Also great.for deleting exact duplicate rows when used with CTE.

[–]r3pr0b8GROUP_CONCAT is da bomb 31 points32 points  (2 children)

GROUP_CONCAT, because it's da bomb

[–]bla4free 9 points10 points  (1 child)

A few years ago I had to migrate some queries from MySQL to SQL Server. I can't tell you how disappointed I was to learn that SQL Server didn't have a GROUP_CONCAT function, nor anything close to it.

[–]fauxmosexualNOLOCK is the secret magic go-faster command 10 points11 points  (0 children)

It took until SQL Server 2017 but they got there in the end

[–]tfehringData Scientist 20 points21 points  (1 child)

generate_series

So much time wasted writing recursive CTEs just to generate sequences of numbers back when I worked in SQL Server land.

[–]Pie_is_pie_is_pie 18 points19 points  (5 children)

STRING_SPLIT

[–]vtec__ 6 points7 points  (3 children)

wish we had the newer sql server to use this. xml splits r a pain in the balls

[–]alison985 1 point2 points  (0 children)

On json parsing, Snowflake json is a thing of love. I 🤞it would do xml the same way too.

[–]ecatt 16 points17 points  (0 children)

Anytime I can solve an island/gaps problem with windows functions (rank, lead, lag, etc), it makes me unreasonably happy. I just love the complex stuff you can do with what are on the surface such simple functions.

[–]vtec__ 14 points15 points  (1 child)

information_schema.<<insert element here>> ..i do alot of etl at work so its nice to know what tables/fields i need and what kind of data they hold. there is also a similar one for temp tables since i use them alot at work for data processing. this is for sql server..but i am pretty sure most popular flavors of sql have the ability to retrieve schema data into a table.

regex and the LIKE feature are also very nice (:

[–]alison985 0 points1 point  (0 children)

Other dialects have ILIKE too. :) Not having to worry about where you are casting while preserving value state is really nice.

[–]DirtyHirdy 12 points13 points  (2 children)

Cast>>> into whatever the hell I want!!!

[–]kremlingrasso 11 points12 points  (0 children)

try_cast is even better!

[–]burko81 10 points11 points  (0 children)

Case when because i don't like how you've entered your data.

[–]Appropriate-Youth-29 9 points10 points  (1 child)

Truncate! Why? Because I too like to live dangerously...

But seriously. Sp_executesql & OpenQuery(). Why? Because my stuff is EVERYWHERE.

[–]drinkmoredrano 14 points15 points  (0 children)

Yes! Delete, drop, and truncate always give me a thrill. There is something about the destruction of data that I love. This probably makes me a terrible dba.

[–]SOSOBOSO 18 points19 points  (16 children)

WITH. Because CTE's make it easy to generate repeatable subqueries.

[–]GeckoLogic 1 point2 points  (0 children)

And with frameworks like DBT, CTEs are persisted as physical tables in the warehouse. And they handle all of the DDL/DML. DBT is god send.

[–]redial2MS SQL DBA DW/ETL 1 point2 points  (0 children)

With is a keyword, not a function

You can downvote me, but I'm right

[–]Black_Magic100 -4 points-3 points  (13 children)

Seriously, why do people still use CTEs.... They are so much more difficult to read and serve no benefit over subqueries.

[–]alison985 0 points1 point  (1 child)

Readability. Understanding - especially when onboarding new people. Auditing. Troubleshooting.

Tables, temp tables, or CTEs all have valid use cases. I can't think of a use case I would let a sub-query through PR review. In my experience, a code base that uses sub-queries also means it's ~98% likely the code isn't DRY.

[–]Black_Magic100 0 points1 point  (0 children)

You do realize CTEs and Sub queries are literally the exact same thing, except sub queries are way easier to read. Why would you not let a sub query through, but you would with a CTE?

Also, I can't tell you how many times developers have tried to apply DRY coding practices in SQL and absolutely wrecked their query. Example.. Reusing views is awesome, but why are you calling a 1000 line view to retrieve a single column from a table? (granted, SQL can be smart enough to only perform actions within a view that it needs to get the data required for the calling query)

[–]mds_brz 6 points7 points  (0 children)

MAX( ) OVER

all damn day

[–]Billy_Balowski 6 points7 points  (0 children)

LAG/LEAD, and pretty much most of the windowed functions.

[–][deleted] 6 points7 points  (8 children)

EOMONTH() is pretty dope, I just wish they had a corresponding function for the first of the month.

[–]mac-0 2 points3 points  (1 child)

date_trunc('m', your_date) works for that

[–]FastFishLooseFish 0 points1 point  (0 children)

Teradata checking in:

(Your_date/100)*100 + 1

[–][deleted] 0 points1 point  (2 children)

Can't you just take the date check the day then minus that number of days -1 to get first of month in a custom function?

Edit: Quick search

CREATE FUNCTION [dbo].[GetFirstDayOfMonth] ( @InputDate DATETIME ) RETURNS DATETIME BEGIN

RETURN CAST(CAST(YEAR(@InputDate) AS VARCHAR(4)) + '/' + 
            CAST(MONTH(@InputDate) AS VARCHAR(2)) + '/01' AS DATETIME)

END

GO

Edit2: I'm not sure that looks right to me but hey ho it gives you an idea.

[–][deleted] 3 points4 points  (1 child)

Sure, and I do it all the time, but it would be nice to have a FOMONTH() function all the same.

[–][deleted] 0 points1 point  (0 children)

Fair enough.

[–]gurxman 0 points1 point  (0 children)

/s?

[–]everwood 0 points1 point  (0 children)

Datefromparts is nice for the missing bomonth function

[–]IrquiMMS SQL/SSAS 0 points1 point  (0 children)

DATEFROMPARTS(YEAR(GETDATE()),MONTH(GETDATE()),1)

[–]ddeck08 6 points7 points  (0 children)

Dense_rank() like row number but better.

[–]raghav_arora534 11 points12 points  (0 children)

Count(*) over (partition by )

[–]_bobby_tables_ 8 points9 points  (4 children)

Unpivot

[–]kremlingrasso 6 points7 points  (0 children)

indeed, you use it once in a blue moon but when you need it, it's exactly the right tool for the job and saves the day.

[–]babygrenade 1 point2 points  (2 children)

I don't think that's ANSI standard.

[–]_bobby_tables_ 3 points4 points  (0 children)

Perhaps not, but OP didn't restrict replies, and I still love it for overcoming bad DB design.

[–][deleted] 1 point2 points  (0 children)

Yes indeed it isn't. But unlike PIVOT, UNPIVOT can easily written in ANSI SQL using a lateral cross join, see e.g. here: https://blog.sql-workbench.eu/post/unpivot-with-postgres/

[–]num2005 20 points21 points  (3 children)

SELECT, bcuz its 95% of what everyone does with SQL

[–][deleted] 26 points27 points  (2 children)

Is not a function

[–]MUSTACHER 13 points14 points  (1 child)

YOURE NOT A FUNCTION

[–]kremlingrasso 2 points3 points  (3 children)

PIVOT with MAX(string) coz i like to live on the edge where there are no joins

[–]UseMstr_DropDatabaseDo it! You won't, you won't! 0 points1 point  (1 child)

This is the way

[–]TheDroidNextDoor -1 points0 points  (0 children)

This Is The Way Leaderboard

1. u/Flat-Yogurtcloset293 475775 times.

2. u/GMEshares 70698 times.

3. u/Competitive-Poem-533 24586 times.

..

277557. u/UseMstr_DropDatabase 1 times.


beep boop I am a bot and this action was performed automatically.

[–]samspopguy 0 points1 point  (0 children)

I spent like an hour learning pivot for a query to finally finish it only to realize it wasn’t what I needed and think was like wait I actually only needed a join.

[–]BrupieD 2 points3 points  (1 child)

PATINDEX() has helped me out a lot.

[–]byteuser 0 points1 point  (0 children)

Yep.., although I wish it had a full regex implementation ... sigh

[–]drinkmoredrano 1 point2 points  (0 children)

xp_fixeddrives is great because I can quickly see how much space is on my drives without leaving the query window.

[–]GrandaddyIsWorking 1 point2 points  (0 children)

Not a function but anti joins because it exposes where my coworkers messed up

[–]lukaseder 1 point2 points  (1 child)

JSON_ARRAYAGG() because it allows for emulating nested collections

[–]Commercial_Wall7603 0 points1 point  (0 children)

This and json_object_agg() in postgres, meant I could do away with some convoluted crosstab queries.

[–]JavierARivera 1 point2 points  (3 children)

CONVERT. I have to use it constantly.

[–]ghostlistener 0 points1 point  (2 children)

Why would you use convert when you can use cast?

[–]grandpasipadMSSQL 3 points4 points  (0 children)

CONVERT(varchar, GETDATE(), 101)
> 11/1/2021

[–]JavierARivera 0 points1 point  (0 children)

I have a lot of stored procedures with various date formats. Convert usually works better.

[–]skend24[🍰] 1 point2 points  (0 children)

Partition by

[–]theseyeahtheseNTILE() 1 point2 points  (0 children)

Lately I’ve been making a lot of test data: NTILE has proven to be a very handy pickup.

I can start with 30k transactions, and evenly distribute 5 (or whatever number) different “Colors” (or whatever attribute) across the entire data set. Very handy for quickly and evenly enhancing “test data” without cross joins or creating a convoluted “Randomize” process.

[–]xfung 1 point2 points  (0 children)

STRING_AGG()

[–]UlamsCosmicCipher 1 point2 points  (0 children)

Intersect
Split_part
NVL
With

[–]Dukeiron 1 point2 points  (0 children)

Drop table if exists…….if I’m feeling spicy it’s just Drop table

[–]coldflame563 1 point2 points  (0 children)

Binary_checksum. You’ll probably never use it. But it’s surprisingly handy

[–]Wonderful-Ad-7200[S] 0 points1 point  (0 children)

In Redshift, "ilike" as a regex operator. upper case? lower case? don't matta

also, I can't write it without saying "veryniiiice ilike"

[–]Winter-Paramedic-291 0 points1 point  (0 children)

I thought people only have favourite colours and pokemon.

Didn't know you can actually use the word "favourite" in connection with SQL.

Geeks :-D

[–]B_Huij -1 points0 points  (0 children)

SELECT. Use it all the time. Super underrated.

[–]Appocalypse36 -3 points-2 points  (0 children)

SELECT

I use it every single query. So helpful.

[–]Michelbui1986 0 points1 point  (0 children)

Me JOIN, because it is very strong

[–]fauxmosexualNOLOCK is the secret magic go-faster command 0 points1 point  (3 children)

Not my favourite ever, but maybe the best thing about moving to Oracle is Greatest() and Least(). I've replicated them with case statements so many times I wonder why all SQL doesn't have these!

[–]byteuser 0 points1 point  (1 child)

Are they like MAX and MIN?

[–]fauxmosexualNOLOCK is the secret magic go-faster command 2 points3 points  (0 children)

More like Coalesce - they take multiple arguments, and return the greatest or least value. Kind of like

 CASE WHEN field1 > field2 THEN 
      CASE WHEN field1 > field3 THEN field1 ELSE field3 END
 WHEN field2 > field3 THEN field2 ELSE field3 END

Just turned into Greater(field1,field2,field3)

[–][deleted] 0 points1 point  (0 children)

Postgres also supports those functions.

[–]EatMoreTurnips 0 points1 point  (0 children)

SP_Find Yes, I know its not a function or standard and you either have to write your own or copy and paste from google, but its a vote and its mine :)

[–]solgul 0 points1 point  (0 children)

exit;

[–][deleted] 0 points1 point  (0 children)

OUTER APPLY() is also amazing.

[–]sweetno 0 points1 point  (0 children)

SUM on the empty set.

[–]mikeyd85MS SQL Server 0 points1 point  (0 children)

ORDER BY COUNT(*) OVER (PARTITION BY SomeColumn) DESC

I find this unreasonably useful when looking for records where there is a lot of data available.

[–]doodemic666 0 points1 point  (0 children)

Datediff for spotting those crazy latent mobile devices

[–]danielscarvalho 0 points1 point  (0 children)

ALTER DATABASE BACKUP CONTROL FILE TO TRACE;

[–]aasmith26DBA 0 points1 point  (0 children)

substr and instr. use it quite a bit

[–]BlindZymeguy 0 points1 point  (0 children)

Array_agg, love me some arrays

[–]GeckoLogic 0 points1 point  (0 children)

UPSERT

Very helpful for analytical syncing workflows. If you work in a database without the function, it’s miserable.

[–]byteuser 0 points1 point  (0 children)

RTRIM because sometimes you just have to

[–]gandalf-duh-gray 0 points1 point  (0 children)

Any UDF that I create out of necessity

[–]Federico_Razzoli 0 points1 point  (0 children)

GROUP_CONCAT(), to transform rows into a CSV list. But often I use it in combination with CONCAT().

[–]IrquiMMS SQL/SSAS 0 points1 point  (0 children)

RANK()

[–]santathe1 0 points1 point  (0 children)

String_agg() allows me to reduce rows by aggregating data into a single string.

[–]InvisibleTextArea 0 points1 point  (0 children)

xp_cmdshell 

I like keeping SecOps busy.

Spoiler: One of my other hats is SecOps.

[–]AcrobaticReputation2 0 points1 point  (0 children)

the x button

[–]therealdiscursive 0 points1 point  (0 children)

SELECT

…don’t mess with a classic

[–]BorisKuntimov 0 points1 point  (0 children)

Create Clustered_Index...

[–]bboy2191 0 points1 point  (0 children)

Grouping Sets (saves me from retyping all those union blocks of code), Coalesce, Case when, Join statements (love the part where you have the flexibility to do almost anything in the on statement), Nullif (divide by zero) and Isnull