SQL Server operands order [duplicate] - sql

This question already has answers here:
Does the order of where clauses matter in SQL?
(6 answers)
Closed 7 years ago.
If there is a very large table T1(Id INT, Name VARCHAR(MAX), Category VARCHAR(MAX)) and Category is INDEX UNIQUE NONCLUSTERED, does it matter the order of operands if I do the select like
SELECT * FROM T1 WHERE Name = 'name' and Category = 'cat'
vs
SELECT * FROM T1 WHERE Category = 'cat' and Name = 'name'
?

Theres isnt any difference, you db planner will parse the code and choose the better option.
What is interesting is the order of execution can change if table sizes change. But how you write it wont.

There might be a difference based on which indexes you have on the table. Check actual execution plan to see what sql decides to use

Related

Select into temp table in PostgreSQL? [duplicate]

This question already has answers here:
Creating temporary tables in SQL
(2 answers)
Closed 7 years ago.
How to create temporary table using select into in PostgreSQL. For example in SQL Select * into temp_tab from source_tab;
You can try to use Create Table As command like this:
CREATE TEMP TABLE mytable AS
SELECT * from source_tab;
From the docs:
This command is functionally similar to SELECT INTO, but it is preferred since it is less likely to be confused with other uses of
the SELECT INTO syntax. Furthermore, CREATE TABLE AS offers a superset
of the functionality offered by SELECT INTO.
The CREATE TABLE AS command allows the user to explicitly specify
whether OIDs should be included. If the presence of OIDs is not
explicitly specified, the default_with_oids configuration variable is
used.

SQL ORDER BY (sequence) [duplicate]

This question already has answers here:
sql ORDER BY multiple values in specific order?
(12 answers)
Closed 9 years ago.
I have a sql statement which I would want to ORDER BY a specific sequence.
SELECT * FROM UserDB ORDER BY [Role]
How can I make it such that the data brought to my GridView table is listed from Admin on the top, follow by User and Guests?
So you want to order by Admin/User/Guest?
Try something like :
SELECT *
FROM UserDB
ORDER BY
CASE Role WHEN 'Admin' THEN 0
WHEN 'User' THEN 1
WHEN 'Guest' THEN 2
END
Does that work for you?
Another option would be to have (or add) a column Sequence to your Role table so you could define the sequence in the table itself - and then just to an ORDER BY Role.Sequence.
This is substantively identical to the question " sql ORDER BY multiple values in specific order? " and I strongly recommend you look at the solutions presented there.

Using local variable for "IN" criteria condition with SQL Server [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
SQL : in clause in storedprocedure:how to pass values
I'm using MS SQL Server 2005, and trying to basically script a 2-step process:
Query a table for a list of IDs matching certain criteria
Update a field in that table, where the ID is in the list of IDs returned by the first
With the catch being that steps 1 and 2 might be separated by a considerable time delay and executed in different sessions. Essential the list of IDs used in #2 is historical data: the values which #1 returned at a past point in time.
What I've attempted to do is write all of IDs from #1 into a varchar(8000) in "##, ##, ##, ##," format (this part is working great), and then use that string like:
UPDATE table SET field=newValue WHERE (id IN (#varcharOfCommaSeparatedIDs))
But this is giving me a syntax error, stating that it cannot convert that varchar value into whatever is needed (the error message is being truncated)
Is there a way to do this without putting the entire SQL command into a string and executing that (using EXEC or sp_executesql)? After years of avoiding injection attacks I have a somewhat instinctive (and perhaps irrational) aversion to "dynamic SQL"
If you're passing the values around between SP's on the SQL Server, I highly recommend storing the values in tables...
- Temp Tables (#mytable)
- Table Variables (#table)
- Real Tables
In SQL Server 2008 onwards you can have table valued input parameters...
If you're passing the values in from an app, the dread comma-separated-string is indeed useful. There are many answers on SO that give Table Valued Functions for turning a string into a table of ids, read to be joined on.
SELECT
*
FROM
foo
INNER JOIN
dbo.bar(#mystring) AS bar
ON foo.id = bar.id
Just write it out to a table.
IF EXISTS (SELECT 1 FROM Database.dbo.MyHoldingTable)
DROP TABLE Database.dbo.MyHoldingTable
SELECT <fields>
INTO Database.dbo.MyHoldingTable
FROM <other table>
WHERE <conditions>
Then, later:
UPDATE OtherTable
Set Column=NewValue
WHERE ID IN (SELECT id FROM Database.dbo.MyHoldingTable)
Also note you could also use an INNER JOIN on your table instead of a IN clause if you prefer.

Possible to exclude or reorder a column from `*`? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
SQL exclude a column using SELECT * [except columnA] FROM tableA?
Is it possible to exclude a column from a select * from table statement with SQL Server?
I have a need for this and this is my only option other than parsing a raw SQL string to get out the required field names (I really don't want to do that).
Just to be bold. When the query is made I do not have access to the list of fields needed from the table but I do know which field I do not need. This is part of a complex multi-part query.
Surely there must be some way even if it's "hackish" such as using table variables or views
My other option is to reorder the columns. My problem is with ExecuteScalar SQL functions which get the first row and first column.
EDIT
I can't add an answer since this is now closed but the way I ended up doing it was like so:
;with results_cte as (
select (calculation) as calculated_column, * from table
)
select * into #temptable from results_cte
where calculated_column<10 /*or whatever*/
alter table #temptable
drop column calculated_column
select * from #temptable
drop table #temptable
Nope. You'll have to build your statement manually or just select *.
No.
Instead, you could check syscolumns to get all of the field names, or (perhaps) SELECT * and ignore that column.
If you use dynamic SQL, you can generate the query from metadata about the table or view (INFORMATION_SCHEMA.COLUMNS) and exclude columns that way. I do this a lot to generate triggers or views.
But there is nothing in the SQL language which supports this.
The best way to handle this would be to select * and then just not present the excluded column to your users in your frontend. As others have noted, SQL has no direct capability of doing an all-columns-except construct.

Oracle SQL: How to use more than 1000 items inside an IN clause [duplicate]

This question already has answers here:
SQL IN Clause 1000 item limit
(5 answers)
Closed 8 years ago.
I have an SQL statement where I would like to get data of 1200 ep_codes by making use of IN clause. When I include more than 1000 ep_codes inside IN clause, Oracle says I'm not allowed to do that. To overcome this, I tried to change the SQL code as follows:
SELECT period, ...
FROM my_view
WHERE period = '200912'
...
AND ep_codes IN (...1000 ep_codes...)
OR ep_codes IN (...200 ep_codes...)
The code was executed succesfully but the results are strange (calculation results are fetched for all periods, not just for 200912, which is not what I want). Is it appropriate to do that using OR between IN clauses or should I execute two separate codes as one with 1000 and the other with 200 ep_codes?
Pascal Martin's solution worked perfectly. Thanks all who contributed with valuable suggestions.
The recommended way to handle this in Oracle is to create a Temporary Table, write the values into this, and then join to this. Using dynamically created IN clauses means the query optimizer does a 'hard parse' of every query.
create global temporary table LOOKUP
(
ID NUMBER
) on commit delete rows;
-- Do a batch insert from your application to populate this table
insert into lookup(id) values (?)
-- join to it
select foo from bar where code in (select id from lookup)
Not sure that using so many values in a IN() is that good, actually -- especially for performances.
When you say "the results are strange", maybe this is because a problem with parenthesis ? What if you try this, instead of what you proposed :
SELECT ...
FROM ...
WHERE ...
AND (
ep_codes IN (...1000 ep_codes...)
OR ep_codes IN (...200 ep_codes...)
)
Does it make the results less strange ?
Actually you can use collections/multisets here. You'll need a number table type to store them.
CREATE TYPE NUMBER_TABLE AS TABLE OF NUMBER;
...
SELECT *
FROM my_view
WHERE period MEMBER OF NUMBER_TABLE(1,2,3...10000)
Read more about multisets here:
Seems like it would be a better idea, both for performance and maintainability, to put the codes in a separate table.
SELECT ...
FROM ...
WHERE ...
AND ep_code in (select code from ep_code_table)
could you insert the 1200 ep_code values into a temporary table and then INNER JOIN to that table to filter rows instead?
SELECT a.*
FROM mytable a
INNER JOIN tmp ON (tmp.ep_code = a.ep_code)
WHERE ...